PinyinText.vue 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. <!-- eslint-disable vue/no-v-html -->
  2. <template>
  3. <div class="pinyin-area" :style="{ 'text-align': pinyinOverallPosition, padding: pinyinPadding }">
  4. <AudioPlay
  5. v-if="isEnable(isEnableVoice)"
  6. :file-id="audioFileId"
  7. :theme-color="unifiedAttrib && unifiedAttrib.topic_color ? unifiedAttrib.topic_color : ''"
  8. />
  9. <!-- 新规则:使用 richTextList -->
  10. <div v-if="richTextList && richTextList.length > 0" class="rich-text-container" :style="bodyStyles">
  11. <template v-for="(block, index) in parsedBlocks">
  12. <!-- 文字块:包含 word_list -->
  13. <span
  14. v-if="block.type === 'text'"
  15. :key="'text-' + index"
  16. class="pinyin-sentence"
  17. :style="[{ 'align-items': pinyinPosition === 'top' ? 'flex-end' : 'flex-start' }, block.sentenceStyle]"
  18. >
  19. <span
  20. v-for="(word, wIndex) in block.word_list"
  21. :key="wIndex"
  22. :class="['pinyin-text', { spacing: isShowPinyin }]"
  23. :style="block.styleObj"
  24. >
  25. <span
  26. :title="isPreview ? '' : '点击校对'"
  27. :style="{
  28. cursor: isPreview ? '' : 'pointer',
  29. }"
  30. @click="!isPreview && handleWordClick(word, block.paragraphIndex, block.oldIndex, wIndex)"
  31. @mouseover="isPreview && handlePreviewHover(word, $event)"
  32. @mouseleave="onLeave"
  33. >
  34. <span
  35. v-if="word.pinyin_list && word.pinyin_list.length < Array.from(word.text).length"
  36. :style="{
  37. flexDirection: pinyinPosition === 'top' ? 'column' : 'column-reverse',
  38. 'align-items': getWordAlignItems(word, block),
  39. }"
  40. >
  41. <span v-if="shouldShowWordPinyin(word)" class="pinyin" :style="getPinyinStyle(word, block)">
  42. {{ getPinyinText(word) }}
  43. </span>
  44. <span class="py-char" :style="getCharStyle(word, block)">{{ convertText(word.text) }}</span>
  45. </span>
  46. <template v-else>
  47. <span v-for="(char, cIndex) in Array.from(word.text)" :key="cIndex">
  48. <span
  49. :style="{
  50. flexDirection: pinyinPosition === 'top' ? 'column' : 'column-reverse',
  51. 'align-items': getWordAlignItems(word, block),
  52. }"
  53. >
  54. <span v-if="shouldShowWordPinyin(word)" class="pinyin" :style="getPinyinStyle(word, block)">
  55. {{ getCharPinyin(word, cIndex) }}
  56. </span>
  57. <span class="py-char" :style="getCharStyle(word, block, cIndex)">{{ convertText(char) }}</span>
  58. </span>
  59. </span>
  60. </template>
  61. </span>
  62. </span>
  63. </span>
  64. <!-- 图片块 -->
  65. <span
  66. v-else-if="block.type === 'image'"
  67. :key="'image-' + index"
  68. :style="block.containerStyle"
  69. class="image-container"
  70. >
  71. <img
  72. :src="block.src"
  73. :alt="block.alt"
  74. :width="block.width"
  75. :height="block.height"
  76. :style="block.imageStyle"
  77. class="inline-image"
  78. />
  79. </span>
  80. <!-- 视频块 -->
  81. <span
  82. v-else-if="block.type === 'video'"
  83. :key="'video-' + index"
  84. :style="block.containerStyle"
  85. class="video-container"
  86. >
  87. <video
  88. :poster="block.poster"
  89. :width="block.width"
  90. :height="block.height"
  91. :style="block.mediaStyle"
  92. controls
  93. class="inline-video"
  94. >
  95. <source :src="block.src" :type="block.videoType" />
  96. 您的浏览器不支持视频播放
  97. </video>
  98. </span>
  99. <!-- 音频块 -->
  100. <span
  101. v-else-if="block.type === 'audio'"
  102. :key="'audio-' + index"
  103. :style="block.containerStyle"
  104. class="audio-container"
  105. >
  106. <audio :src="block.src" :style="block.mediaStyle" controls class="inline-audio">
  107. 您的浏览器不支持音频播放
  108. </audio>
  109. </span>
  110. <!-- 数学公式块(保留 MathJax 原始结构) -->
  111. <MathHtml
  112. v-else-if="block.type === 'math'"
  113. :key="'math-' + index"
  114. :html="block.html"
  115. :style-obj="block.containerStyle"
  116. :is-display="block.isDisplay"
  117. />
  118. <!-- 换行符 -->
  119. <br v-else-if="block.type === 'newline'" :key="'newline-' + index" />
  120. </template>
  121. </div>
  122. <!-- 老规则:使用 paragraphList -->
  123. <template v-else-if="paragraphList && paragraphList.length > 0">
  124. <div v-for="(paragraph, pIndex) in paragraphList" :key="pIndex" class="pinyin-paragraph" :style="bodyStyles">
  125. <div
  126. v-for="(sentence, sIndex) in paragraph"
  127. :key="sIndex"
  128. class="pinyin-sentence"
  129. :style="{ 'align-items': pinyinPosition === 'top' ? 'flex-end' : 'flex-start' }"
  130. >
  131. <span v-for="(word, wIndex) in sentence" :key="wIndex" :class="['pinyin-text', { spacing: isShowPinyin }]">
  132. <span
  133. :title="isPreview ? '' : '点击校对'"
  134. :style="{
  135. cursor: isPreview ? '' : 'pointer',
  136. 'align-items': wIndex == 0 ? 'flex-start' : 'center',
  137. }"
  138. @click="!isPreview && handleWordClick(word, block.paragraphIndex, block.oldIndex, wIndex)"
  139. @mouseover="isPreview && handlePreviewHover(word, $event)"
  140. @mouseleave="onLeave"
  141. >
  142. <span
  143. v-if="pinyinPosition === 'top' && hasPinyinInParagraph(sIndex)"
  144. class="pinyin"
  145. :style="{ 'font-size': pinyinSize }"
  146. >
  147. {{ getPinyinText(word) }}</span
  148. >
  149. <span class="py-char" :style="textStyle(word)">{{ convertText(word.text) }}</span>
  150. <span
  151. v-if="pinyinPosition !== 'top' && hasPinyinInParagraph(sIndex)"
  152. class="pinyin"
  153. :style="{ 'font-size': pinyinSize }"
  154. >
  155. {{ getPinyinText(word) }}</span
  156. >
  157. </span>
  158. </span>
  159. </div>
  160. </div>
  161. </template>
  162. <CorrectPinyin
  163. :visible.sync="visible"
  164. :new-version="newVersion"
  165. :select-content="selectContent"
  166. :component-type="componentType"
  167. @fillTonePinyin="fillTonePinyin"
  168. />
  169. <!-- 气泡弹窗 -->
  170. <el-popover
  171. ref="notePopover"
  172. :popper-options="{ boundariesElement: 'viewport' }"
  173. placement="bottom-start"
  174. trigger="manual"
  175. >
  176. <div class="popover-content" style="max-width: 530px; font-size: 14pt" v-html="sanitizeHTML(note)"></div>
  177. </el-popover>
  178. </div>
  179. </template>
  180. <script>
  181. import CorrectPinyin from '@/views/book/courseware/create/components/base/common/CorrectPinyin.vue';
  182. import { sanitizeHTML } from '@/utils/common';
  183. import { isEnable } from '@/views/book/courseware/data/common';
  184. import AudioPlay from '@/views/book/courseware/preview/components/character_base/components/AudioPlay.vue';
  185. // MathHtml 组件用于渲染数学公式的 HTML 内容,保留 MathJax 的原始结构
  186. const MathHtml = {
  187. name: 'MathHtml',
  188. functional: true,
  189. props: {
  190. html: {
  191. type: String,
  192. default: '',
  193. },
  194. styleObj: {
  195. type: Object,
  196. default: () => ({}),
  197. },
  198. isDisplay: {
  199. type: Boolean,
  200. default: false,
  201. },
  202. },
  203. render(h, context) {
  204. return h('span', {
  205. class: {
  206. 'math-container': true,
  207. 'math-display': context.props.isDisplay,
  208. },
  209. style: context.props.styleObj,
  210. domProps: {
  211. innerHTML: sanitizeHTML(context.props.html || ''),
  212. },
  213. });
  214. },
  215. };
  216. export default {
  217. name: 'PinyinText',
  218. components: {
  219. CorrectPinyin,
  220. AudioPlay,
  221. MathHtml,
  222. },
  223. inject: ['convertText'],
  224. props: {
  225. isEnableVoice: {
  226. type: String,
  227. default: 'false',
  228. },
  229. audioFileId: {
  230. type: String,
  231. default: '',
  232. },
  233. unifiedAttrib: {
  234. type: Object,
  235. default: () => ({}),
  236. },
  237. paragraphList: {
  238. type: Array,
  239. default: () => [],
  240. },
  241. richTextList: {
  242. type: Array,
  243. default: () => [],
  244. },
  245. richTextNoteList: {
  246. type: Array,
  247. default: () => [],
  248. },
  249. pinyinPosition: {
  250. type: String,
  251. required: true,
  252. },
  253. fontFamily: {
  254. type: String,
  255. default: '',
  256. },
  257. fontSize: {
  258. type: String,
  259. default: '12pt',
  260. },
  261. pinyinSize: {
  262. type: String,
  263. default: '12pt',
  264. },
  265. pinyinOverallPosition: {
  266. type: String,
  267. default: 'left',
  268. },
  269. isPreview: {
  270. type: Boolean,
  271. default: false,
  272. },
  273. componentType: {
  274. type: String,
  275. default: '',
  276. },
  277. pinyinPadding: {
  278. type: String,
  279. default: '0px 0px 0px 0px',
  280. },
  281. bodyStyles: {
  282. type: Object,
  283. default: () => ({}),
  284. },
  285. isShowPinyin: {
  286. type: Boolean,
  287. default: true,
  288. },
  289. },
  290. data() {
  291. return {
  292. isEnable,
  293. sanitizeHTML,
  294. visible: false,
  295. selectContent: {},
  296. paragraph_index: 0,
  297. sentence_index: 0,
  298. word_index: 0,
  299. note: '',
  300. isAllSetting: false,
  301. };
  302. },
  303. computed: {
  304. newVersion() {
  305. return this.richTextList && this.richTextList.length > 0;
  306. },
  307. styleWatch() {
  308. return {
  309. fontSize: this.fontSize,
  310. fontFamily: this.fontFamily,
  311. };
  312. },
  313. // 预处理 richTextList,合并分散的视频标签
  314. normalizedRichTextList() {
  315. if (!this.richTextList || this.richTextList.length === 0) return [];
  316. const result = [];
  317. let i = 0;
  318. while (i < this.richTextList.length) {
  319. const item = this.richTextList[i];
  320. // 检查是否是视频开始标签(且不包含结束标签)
  321. if (
  322. item.text &&
  323. typeof item.text === 'string' &&
  324. item.text.includes('<video') &&
  325. !item.text.includes('</video>')
  326. ) {
  327. let combinedText = item.text;
  328. let j = i + 1;
  329. // 向后查找 source 和结束标签,直到遇到 </video> 或超出范围
  330. while (j < this.richTextList.length) {
  331. const nextItem = this.richTextList[j];
  332. if (nextItem.text) {
  333. combinedText += `${nextItem.text}`;
  334. }
  335. // 如果找到了结束标签,合并完成,跳出内部循环
  336. if (nextItem.text && nextItem.text.includes('</video>')) {
  337. j += 1; // 跳过结束标签
  338. break;
  339. }
  340. j += 1;
  341. }
  342. // 将合并后的内容作为一个新项加入结果
  343. result.push({
  344. ...item,
  345. text: combinedText,
  346. is_merged_video: true, // 标记一下,可选
  347. });
  348. // 更新主循环索引,跳过已合并的项
  349. i = j;
  350. } else {
  351. // 其他项直接加入
  352. result.push(item);
  353. i += 1;
  354. }
  355. }
  356. return result;
  357. },
  358. // 解析 richTextList 为可渲染的块
  359. parsedBlocks() {
  360. const listToParse = this.normalizedRichTextList;
  361. if (!listToParse || listToParse.length === 0) return [];
  362. const blocks = [];
  363. let textBlockIndex = 0;
  364. let oldIndex = -1;
  365. let paragraphIndex = 0;
  366. const tagStack = [];
  367. let mathContext = null;
  368. for (const item of listToParse) {
  369. oldIndex += 1;
  370. if (mathContext) {
  371. mathContext.html += this.getRawItemText(item);
  372. if (item.is_style === 'true' || item.is_style === true) {
  373. this.updateHtmlTagStack(mathContext.stack, item.text || '');
  374. if (mathContext.stack.length === 0) {
  375. blocks.push(this.parseMathBlock(mathContext.html, tagStack));
  376. mathContext = null;
  377. }
  378. }
  379. continue;
  380. }
  381. if (this.isMathRootTag(item)) {
  382. const rootTag = this.extractTagName(item.text || '');
  383. mathContext = {
  384. html: this.getRawItemText(item),
  385. stack: rootTag ? [rootTag] : ['span'],
  386. };
  387. continue;
  388. }
  389. if (item.text && typeof item.text === 'string' && item.text.includes('<img')) {
  390. blocks.push(this.parseImageBlock(item, tagStack));
  391. } else if (item.text && typeof item.text === 'string' && item.text.includes('<video')) {
  392. // item.text 是完整的 video 标签串
  393. blocks.push(this.parseVideoBlock(item, tagStack));
  394. } else if (item.text && typeof item.text === 'string' && item.text.includes('<audio')) {
  395. blocks.push(this.parseAudioBlock(item, tagStack));
  396. } else if (item.is_style === 'true' || item.is_style === true) {
  397. if (item.text.includes('<br')) {
  398. blocks.push({ type: 'newline' });
  399. paragraphIndex += 1;
  400. } else {
  401. this.handleStyleTag(item, tagStack);
  402. }
  403. } else if (item.text === '\n') {
  404. blocks.push({ type: 'newline' });
  405. paragraphIndex += 1;
  406. } else if (item.word_list && item.word_list.length > 0) {
  407. const hasEmphasisDot = this.checkHasEmphasisDot(tagStack);
  408. blocks.push(this.createTextBlock(item, tagStack, textBlockIndex, oldIndex, paragraphIndex, hasEmphasisDot));
  409. textBlockIndex += 1;
  410. }
  411. }
  412. if (mathContext) {
  413. blocks.push(this.parseMathBlock(mathContext.html, tagStack));
  414. }
  415. return blocks;
  416. },
  417. },
  418. watch: {
  419. styleWatch: {
  420. handler() {
  421. this.isAllSetting = true;
  422. },
  423. immediate: true,
  424. deep: true,
  425. },
  426. },
  427. methods: {
  428. // 统一处理点击事件
  429. handleWordClick(item, pIndex, sIndex, wIndex) {
  430. if (item) {
  431. this.visible = true;
  432. this.selectContent = item;
  433. this.paragraph_index = pIndex;
  434. this.sentence_index = sIndex;
  435. this.word_index = wIndex;
  436. }
  437. },
  438. // 预览模式:悬停触发气泡
  439. handlePreviewHover(item, event) {
  440. if (!item) return;
  441. let noteContent = '';
  442. // 查找注释内容
  443. if (item.annota_id && this.richTextNoteList) {
  444. const noteItem = this.richTextNoteList.find((p) => p.id === item.annota_id);
  445. if (noteItem) {
  446. noteContent = noteItem.dataStr || noteItem.note || '';
  447. }
  448. } else if (item.note) {
  449. noteContent = item.note;
  450. }
  451. if (noteContent) {
  452. this.note = noteContent;
  453. const refEl = this.$refs.notePopover;
  454. refEl.referenceElm = event.target;
  455. refEl.showPopper = true;
  456. // 强制重新计算定位
  457. if (refEl.updatePopper) {
  458. refEl.updatePopper();
  459. }
  460. }
  461. },
  462. onLeave() {
  463. this.$refs.notePopover.showPopper = false;
  464. },
  465. // 检查标签栈中是否有着重点样式
  466. checkHasEmphasisDot(tagStack) {
  467. return tagStack.some((tagItem) => {
  468. if (!tagItem.className) return false;
  469. return tagItem.className.includes('rich-text-emphasis-dot');
  470. });
  471. },
  472. // 解析图片块
  473. parseImageBlock(item, tagStack) {
  474. const imgMatch = item.text.match(/<img\s+([^>]*)\/?\s*>/i);
  475. if (!imgMatch) return null;
  476. const attrs = imgMatch[1];
  477. const srcMatch = attrs.match(/src=["']([^"']*)["']/i);
  478. const altMatch = attrs.match(/alt=["']([^"']*)["']/i);
  479. const widthMatch = attrs.match(/width=["']?(\d+)["']?/i);
  480. const heightMatch = attrs.match(/height=["']?(\d+)["']?/i);
  481. const styleMatch = attrs.match(/style=["']([^"']*)["']/i);
  482. const containerStyleObj = {};
  483. tagStack.forEach((tagItem) => {
  484. if (tagItem.style) {
  485. this.mergeStyleString(containerStyleObj, tagItem.style);
  486. }
  487. });
  488. const imageStyleObj = {};
  489. if (styleMatch) {
  490. this.mergeStyleString(imageStyleObj, styleMatch[1]);
  491. }
  492. return {
  493. type: 'image',
  494. src: srcMatch ? srcMatch[1] : '',
  495. alt: altMatch ? altMatch[1] : '',
  496. width: widthMatch ? widthMatch[1] : null,
  497. height: heightMatch ? heightMatch[1] : null,
  498. containerStyle: containerStyleObj,
  499. imageStyle: imageStyleObj,
  500. };
  501. },
  502. // 解析视频块
  503. parseVideoBlock(item, tagStack) {
  504. const videoMatch = item.text.match(/<video\s+([^>]*)>/i);
  505. if (!videoMatch) return null;
  506. const attrs = videoMatch[1];
  507. const posterMatch = attrs.match(/poster=["']([^"']*)["']/i);
  508. const widthMatch = attrs.match(/width=["']?(\d+)["']?/i);
  509. const heightMatch = attrs.match(/height=["']?(\d+)["']?/i);
  510. const styleMatch = attrs.match(/style=["']([^"']*)["']/i);
  511. // 直接从完整的文本中匹配 source
  512. const sourceMatch = item.text.match(/<source\s+([^>]*)\/?\s*>/i);
  513. let src = '';
  514. let videoType = '';
  515. if (sourceMatch) {
  516. const sourceAttrs = sourceMatch[1];
  517. const srcMatch = sourceAttrs.match(/src\s*=\s*["']?([^"'\s>]+)["']?/i);
  518. const typeMatch = sourceAttrs.match(/type\s*=\s*["']?([^"'\s>]+)["']?/i);
  519. src = srcMatch ? srcMatch[1] : '';
  520. videoType = typeMatch ? typeMatch[1] : '';
  521. }
  522. const containerStyleObj = {};
  523. tagStack.forEach((tagItem) => {
  524. if (tagItem.style) {
  525. this.mergeStyleString(containerStyleObj, tagItem.style);
  526. }
  527. });
  528. const mediaStyleObj = {};
  529. if (styleMatch) {
  530. this.mergeStyleString(mediaStyleObj, styleMatch[1]);
  531. }
  532. return {
  533. type: 'video',
  534. poster: posterMatch ? posterMatch[1] : '',
  535. width: widthMatch ? widthMatch[1] : null,
  536. height: heightMatch ? heightMatch[1] : null,
  537. src,
  538. videoType,
  539. containerStyle: containerStyleObj,
  540. mediaStyle: mediaStyleObj,
  541. };
  542. },
  543. // 解析音频块
  544. parseAudioBlock(item, tagStack) {
  545. const audioMatch = item.text.match(/<audio\s+([^>]*)>/i);
  546. if (!audioMatch) return null;
  547. const attrs = audioMatch[1];
  548. const srcMatch = attrs.match(/src=["']([^"']*)["']/i);
  549. const styleMatch = attrs.match(/style=["']([^"']*)["']/i);
  550. const containerStyleObj = {};
  551. tagStack.forEach((tagItem) => {
  552. if (tagItem.style) {
  553. this.mergeStyleString(containerStyleObj, tagItem.style);
  554. }
  555. });
  556. const mediaStyleObj = {};
  557. if (styleMatch) {
  558. this.mergeStyleString(mediaStyleObj, styleMatch[1]);
  559. }
  560. return {
  561. type: 'audio',
  562. src: srcMatch ? srcMatch[1] : '',
  563. containerStyle: containerStyleObj,
  564. mediaStyle: mediaStyleObj,
  565. };
  566. },
  567. // 合并样式字符串到对象
  568. mergeStyleString(styleObj, styleStr) {
  569. styleStr.split(';').forEach((rule) => {
  570. if (rule.trim()) {
  571. const [prop, value] = rule.split(':').map((s) => s.trim());
  572. if (prop && value) {
  573. const camelProp = prop.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
  574. styleObj[camelProp] = value;
  575. }
  576. }
  577. });
  578. },
  579. // 处理样式标签
  580. handleStyleTag(item, tagStack) {
  581. const tagText = item.text || '';
  582. const closeTagMatch = tagText.match(/^<\/(\w+)>$/);
  583. if (closeTagMatch) {
  584. const tagName = closeTagMatch[1];
  585. this.removeTagFromStack(tagStack, tagName);
  586. } else {
  587. const openTagMatch = tagText.match(/^<(\w+)([^>]*)>$/);
  588. if (openTagMatch) {
  589. const tagName = openTagMatch[1];
  590. const attrs = openTagMatch[2];
  591. const { style, className } = this.extractTagInfo(attrs, tagName);
  592. tagStack.push({ tag: tagName, style, className });
  593. }
  594. }
  595. },
  596. // 提取标签信息(样式和类名)
  597. extractTagInfo(attrs, tagName) {
  598. const styleMatch = attrs.match(/style=["']([^"']*)["']/);
  599. let style = styleMatch ? styleMatch[1] : null;
  600. const classMatch = attrs.match(/class=["']([^"']*)["']/);
  601. const className = classMatch ? classMatch[1] : '';
  602. if (!style) {
  603. style = this.getDefaultTagStyle(tagName);
  604. }
  605. return { style, className };
  606. },
  607. // 获取标签默认样式
  608. getDefaultTagStyle(tagName) {
  609. const tagStyleMap = {
  610. strong: 'font-weight: bold',
  611. b: 'font-weight: bold',
  612. em: 'font-style: italic',
  613. i: 'font-style: italic',
  614. u: 'text-decoration: underline',
  615. s: 'text-decoration: line-through',
  616. del: 'text-decoration: line-through',
  617. sub: 'vertical-align: sub',
  618. sup: 'vertical-align: super',
  619. };
  620. return tagStyleMap[tagName] || null;
  621. },
  622. // 创建文本块
  623. createTextBlock(item, tagStack, textBlockIndex, oldIndex, paragraphIndex, hasEmphasisDot) {
  624. const combinedStyle = tagStack
  625. .filter((tagItem) => tagItem.style)
  626. .map((tagItem) => tagItem.style)
  627. .join(';');
  628. const styleObj = combinedStyle ? this.parseStyleToObject(combinedStyle) : null;
  629. // 提取 paddingLeft 用于段落缩进,从 styleObj 中移除
  630. const sentenceStyle = {};
  631. if (styleObj && styleObj.paddingLeft) {
  632. sentenceStyle.paddingLeft = styleObj.paddingLeft;
  633. delete styleObj.paddingLeft;
  634. }
  635. return {
  636. type: 'text',
  637. word_list: item.word_list,
  638. index: textBlockIndex,
  639. oldIndex,
  640. paragraphIndex,
  641. styleObj,
  642. sentenceStyle,
  643. rawStyleText: combinedStyle,
  644. hasEmphasisDot,
  645. };
  646. },
  647. // 解析样式字符串为对象
  648. parseStyleToObject(styleStr) {
  649. const styleObj = {};
  650. if (!styleStr) return styleObj;
  651. this.mergeStyleString(styleObj, styleStr);
  652. return styleObj;
  653. },
  654. parseMathBlock(html, tagStack) {
  655. const containerStyleObj = {};
  656. tagStack.forEach((tagItem) => {
  657. if (tagItem.style) {
  658. this.mergeStyleString(containerStyleObj, tagItem.style);
  659. }
  660. });
  661. const isDisplay =
  662. /<mjx-container[^>]*\bdisplay=["']true["']/i.test(html) ||
  663. /<mjx-assistive-mml[^>]*\bdisplay=["']block["']/i.test(html);
  664. return {
  665. type: 'math',
  666. html,
  667. containerStyle: containerStyleObj,
  668. isDisplay,
  669. };
  670. },
  671. isMathRootTag(item) {
  672. if (!item || !(item.is_style === 'true' || item.is_style === true) || !item.text) return false;
  673. return /class=["'][^"']*\bmathjax-container\b[^"']*\beditor-math\b[^"']*["']/i.test(item.text);
  674. },
  675. getRawItemText(item) {
  676. if (!item) return '';
  677. return item.text || '';
  678. },
  679. extractTagName(tagText) {
  680. const match = (tagText || '').match(/^<\/?\s*([a-zA-Z][\w-]*)/);
  681. return match ? match[1].toLowerCase() : '';
  682. },
  683. updateHtmlTagStack(tagStack, tagText) {
  684. if (!tagText || !tagStack) return;
  685. const tagName = this.extractTagName(tagText);
  686. if (!tagName) return;
  687. if (/^<\//.test(tagText)) {
  688. for (let i = tagStack.length - 1; i >= 0; i--) {
  689. if (tagStack[i] === tagName) {
  690. tagStack.splice(i, 1);
  691. break;
  692. }
  693. }
  694. } else if (!/\/>\s*$/.test(tagText)) {
  695. tagStack.push(tagName);
  696. }
  697. },
  698. getBlockColor(block) {
  699. const colorFromObject = block?.styleObj?.color;
  700. if (colorFromObject) return colorFromObject;
  701. const styleText = block?.rawStyleText || '';
  702. const colorMatch = styleText.match(/(?:^|;)\s*color\s*:\s*([^;]+)/i);
  703. return colorMatch ? colorMatch[1].trim() : '';
  704. },
  705. // 获取单个字符的样式(包括着重点)
  706. getCharStyle(word, block) {
  707. const baseStyle = { ...word.activeTextStyle };
  708. baseStyle['font-size'] = baseStyle.fontSize;
  709. baseStyle['font-family'] = baseStyle.fontFamily;
  710. const blockColor = this.getBlockColor(block);
  711. if (blockColor) {
  712. baseStyle.color = `${blockColor} !important`;
  713. }
  714. if (this.isAllSetting) {
  715. baseStyle['font-size'] = this.fontSize;
  716. baseStyle['font-family'] = this.fontFamily;
  717. this.isAllSetting = false;
  718. }
  719. // 如果该文字块有着重点标记,应用到字符上
  720. if (block.hasEmphasisDot) {
  721. const letterSpacing = block.styleObj?.letterSpacing || '0';
  722. const letterSpacingValue = parseFloat(letterSpacing) || 0;
  723. baseStyle['border-bottom'] = 'none';
  724. baseStyle['background-image'] = 'radial-gradient(circle at center, currentColor 0.08em, transparent 0.09em)';
  725. baseStyle['background-repeat'] = 'repeat-x';
  726. baseStyle['background-position'] = `${letterSpacingValue * -0.5}em 100%`;
  727. baseStyle['background-size'] = `${1 + letterSpacingValue}em 0.15em`;
  728. baseStyle['padding-bottom'] = '0.15em';
  729. baseStyle['display'] = 'inline';
  730. }
  731. return baseStyle;
  732. },
  733. // 兼容历史数据
  734. getPinyinText(item) {
  735. return this.checkShowPinyin(item.showPinyin) ? item.pinyin.replace(/\s+/g, '') : '\u200B';
  736. },
  737. shouldShowWordPinyin(item) {
  738. return this.checkShowPinyin(item && item.showPinyin);
  739. },
  740. // 拼音与汉字一一对应
  741. getCharPinyin(word, charIndex) {
  742. if (!this.checkShowPinyin(word.showPinyin)) {
  743. return '\u200B';
  744. }
  745. // 优先使用新的 pinyin_list 字段(与字符一一对应)
  746. if (word.pinyin_list && Array.isArray(word.pinyin_list)) {
  747. return word.pinyin_list[charIndex] || '\u200B';
  748. }
  749. // 兼容旧数据:使用 pinyin 字段
  750. const pinyinList = word.pinyin ? word.pinyin.trim().split(/\s+/) : [];
  751. return pinyinList[charIndex] || '\u200B';
  752. },
  753. // 如果汉字有字间距,拼音与汉字左对齐,如果没有则居中对齐
  754. getWordAlignItems(word, block) {
  755. const letterSpacing = block.styleObj?.letterSpacing;
  756. if (letterSpacing && letterSpacing !== '0' && letterSpacing !== '0px') {
  757. return 'flex-start';
  758. }
  759. return 'center';
  760. },
  761. // 拼音固定为拼音字体,跟随汉字的字号、颜色、粗细的样式
  762. getPinyinStyle(item, block) {
  763. const styles = {};
  764. // 固定使用 League 字体
  765. styles['font-family'] = 'League';
  766. // 只继承字号和颜色
  767. if (item.activeTextStyle) {
  768. if (item.activeTextStyle.fontSize) {
  769. styles['font-size'] = item.activeTextStyle.fontSize;
  770. }
  771. if (item.activeTextStyle.color) {
  772. styles['color'] = item.activeTextStyle.color;
  773. }
  774. }
  775. const blockColor = this.getBlockColor(block);
  776. if (blockColor) {
  777. styles['color'] = `${blockColor} !important`;
  778. }
  779. // 如果设置了全局字号,优先使用全局字号
  780. if (this.isAllSetting && this.fontSize) {
  781. styles['font-size'] = this.fontSize;
  782. this.isAllSetting = false;
  783. }
  784. // 优先取文字单独的字号
  785. let _fontSize = block.styleObj && block.styleObj.fontSize ? block.styleObj.fontSize : null;
  786. // 如果没有,取继承的字号
  787. if (!_fontSize && item.activeTextStyle && item.activeTextStyle.fontSize) {
  788. _fontSize = item.activeTextStyle.fontSize;
  789. }
  790. // 如果没有,取组件的字号
  791. if (!_fontSize && this.bodyStyles.fontSize) _fontSize = this.bodyStyles.fontSize;
  792. // 如果没有,取全局字号
  793. if (!_fontSize && this.fontSize) _fontSize = this.fontSize;
  794. if (_fontSize) {
  795. // 取出字号里面的数字,做计算处理之后,自动加上原来的单位
  796. const fontSizeMatch = _fontSize.match(/^([\d.]+)(\D*)$/);
  797. if (fontSizeMatch) {
  798. const fontSizeValue = parseFloat(fontSizeMatch[1]);
  799. const fontSizeUnit = fontSizeMatch[2] || 'px';
  800. // 根据字号大小确定比例:16号及以下75%,16号以上60%
  801. const ratio = fontSizeValue <= 16 ? 0.75 : 0.6;
  802. const calculatedSize = Math.round(fontSizeValue * ratio);
  803. // 保留原始单位
  804. styles['font-size'] = `${calculatedSize}${fontSizeUnit}`;
  805. }
  806. }
  807. // 明确重置不应该继承的样式
  808. styles['text-decoration'] = 'none';
  809. styles['font-style'] = 'normal';
  810. styles['letter-spacing'] = '0';
  811. return styles;
  812. },
  813. removeTagFromStack(tagStack, tagName) {
  814. for (let i = tagStack.length - 1; i >= 0; i--) {
  815. if (tagStack[i].tag === tagName) {
  816. tagStack.splice(i, 1);
  817. break;
  818. }
  819. }
  820. },
  821. textStyle(item) {
  822. const styles = { ...item.activeTextStyle };
  823. styles['font-size'] = styles.fontSize;
  824. styles['font-family'] = styles.fontFamily;
  825. if (this.isAllSetting) styles['font-size'] = this.fontSize;
  826. if (this.isAllSetting) styles['font-family'] = this.fontFamily;
  827. this.isAllSetting = false;
  828. return styles;
  829. },
  830. // 回填校对后的拼音
  831. fillTonePinyin(dataContent) {
  832. this.$emit('fillCorrectPinyin', {
  833. selectContent: dataContent,
  834. i: this.paragraph_index,
  835. j: this.sentence_index,
  836. k: this.word_index,
  837. newVersion: this.newVersion,
  838. });
  839. },
  840. // 如段落有拼音,则返回true ,否则不显示拼音行
  841. hasPinyinInParagraph(paragraphIndex) {
  842. if (!this.isShowPinyin) {
  843. return false;
  844. }
  845. const paragraph = this.paragraphList[paragraphIndex];
  846. return paragraph.some((sentence) => sentence.some((item) => this.checkShowPinyin(item.showPinyin)));
  847. },
  848. // 兼容历史数据,没有 showPinyin 字段的,则默认为 true
  849. checkShowPinyin(showPinyin) {
  850. if (!this.isShowPinyin) {
  851. return false;
  852. }
  853. if (showPinyin === undefined || showPinyin === null) {
  854. return true;
  855. }
  856. return this.isEnable(showPinyin);
  857. },
  858. },
  859. };
  860. </script>
  861. <style lang="scss" scoped>
  862. .pinyin-area {
  863. // 新规则的容器样式
  864. .rich-text-container {
  865. p {
  866. display: inline-flex;
  867. flex-wrap: wrap;
  868. margin: 0.5em 0;
  869. }
  870. :deep(.mathjax-container.editor-math > svg[aria-hidden='true']) {
  871. display: none !important;
  872. }
  873. .math-container.math-display {
  874. display: block !important;
  875. width: 100%;
  876. text-align: center;
  877. }
  878. .math-container.math-display :deep(mjx-container[display='true']) {
  879. display: block !important;
  880. margin: 0 auto;
  881. text-align: center;
  882. }
  883. span {
  884. display: inline-flex;
  885. }
  886. .pinyin-sentence {
  887. display: inline;
  888. white-space: normal;
  889. }
  890. .image-container {
  891. display: inline-block;
  892. .inline-image {
  893. display: inline-block;
  894. max-width: 100%;
  895. height: auto;
  896. }
  897. }
  898. .video-container {
  899. display: inline-block;
  900. margin: 26px 5px 26px 0;
  901. .inline-video {
  902. display: inline-block;
  903. max-width: 100%;
  904. height: auto;
  905. }
  906. }
  907. .audio-container {
  908. display: block;
  909. .inline-audio {
  910. display: inline-block;
  911. width: 100%;
  912. max-width: 500px;
  913. }
  914. }
  915. }
  916. .pinyin-paragraph {
  917. .pinyin-sentence {
  918. display: inline;
  919. white-space: normal;
  920. }
  921. }
  922. .pinyin-text {
  923. display: inline-flex;
  924. text-wrap: pretty;
  925. hanging-punctuation: allow-end;
  926. &.spacing {
  927. padding: 0 2px;
  928. }
  929. > span {
  930. display: inline-flex;
  931. }
  932. .py-char {
  933. ruby-align: center;
  934. line-height: 1em;
  935. }
  936. .pinyin {
  937. display: inline-block;
  938. min-height: 12px;
  939. font-family: 'League';
  940. line-height: 1em;
  941. text-decoration: none !important;
  942. // 防止继承父元素的删除线
  943. text-decoration-skip-ink: none;
  944. }
  945. }
  946. :deep(.annotation-popover) {
  947. z-index: 9999 !important; /* 确保气泡在最上层 */
  948. min-width: 200px;
  949. max-width: 400px;
  950. padding: 12px;
  951. border-radius: 8px;
  952. box-shadow: 0 4px 12px rgba(0, 0, 0, 15%);
  953. }
  954. }
  955. </style>
  956. <style lang="scss">
  957. .pinyin-area + .pinyin-area {
  958. margin-top: 4px;
  959. }
  960. </style>