CoursewarePreview.vue 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. <template>
  2. <div ref="courseware" class="courseware preview" :style="computedCoursewareStyle" @mouseup="handleTextSelection">
  3. <template v-for="(row, i) in data.row_list">
  4. <div v-show="computedRowVisibility(row.row_id)" :key="i" class="row" :style="getMultipleColStyle(i)">
  5. <el-checkbox
  6. v-if="
  7. isShowGroup &&
  8. groupRowList.find(({ row_id, is_pre_same_group }) => row.row_id === row_id && !is_pre_same_group)
  9. "
  10. v-model="rowCheckList[row.row_id]"
  11. :class="['row-checkbox', `${row.row_id}`]"
  12. />
  13. <!-- 列 -->
  14. <template v-for="(col, j) in row.col_list">
  15. <div :key="j" :class="['col', `col-${i}-${j}`]" :style="computedColStyle(col)">
  16. <!-- 网格 -->
  17. <template v-for="(grid, k) in col.grid_list">
  18. <component
  19. :is="previewComponentList[grid.type]"
  20. :id="grid.id"
  21. :key="k"
  22. ref="preview"
  23. :content="computedColContent(grid.id)"
  24. :background="computedColBackground(grid.id)"
  25. :class="[grid.id]"
  26. :data-id="grid.id"
  27. :style="{
  28. gridArea: grid.grid_area,
  29. height: grid.height,
  30. }"
  31. @contextmenu.native.prevent="handleContextMenu($event, grid.id)"
  32. @handleHeightChange="handleHeightChange"
  33. />
  34. <div
  35. v-if="showMenu && componentId === grid.id"
  36. :key="'menu' + grid.id + k"
  37. class="custom-context-menu"
  38. :style="{ left: menuPosition.x + 'px', top: menuPosition.y + 'px' }"
  39. @click="handleMenuItemClick"
  40. >
  41. 添加批注
  42. </div>
  43. <div
  44. v-if="showRemark && Object.keys(componentRemarkObj).length !== 0 && componentRemarkObj[grid.id]"
  45. :key="'show' + grid.id + k"
  46. >
  47. <el-popover
  48. v-for="(items, indexs) in componentRemarkObj[grid.id]"
  49. :key="indexs"
  50. placement="bottom"
  51. width="200"
  52. trigger="click"
  53. >
  54. <div v-html="items.content"></div>
  55. <template #reference>
  56. <SvgIcon
  57. slot="reference"
  58. icon-class="icon-info"
  59. size="24"
  60. class="remark-info"
  61. :style="{ left: items.position_x - 12 + 'px', top: items.position_y - 12 + 'px' }"
  62. />
  63. </template>
  64. </el-popover>
  65. </div>
  66. </template>
  67. </div>
  68. </template>
  69. </div>
  70. </template>
  71. <!-- 选中文本的工具栏 -->
  72. <div v-show="showToolbar" class="contentmenu" :style="contentmenu">
  73. <span class="button" @click="setNote"><SvgIcon icon-class="sidebar-text" size="14" /> 笔记</span>
  74. <span class="line"></span>
  75. <span class="button" @click="setCollect"><SvgIcon icon-class="sidebar-collect" size="14" /> 收藏 </span>
  76. <span class="line"></span>
  77. <span class="button" @click="setTranslate"> <SvgIcon icon-class="sidebar-translate" size="14" /> 翻译</span>
  78. <span class="line"></span>
  79. <span class="button" @click="setFeedback"> <SvgIcon icon-class="sidebar-feedback" size="14" /> 用户反馈</span>
  80. </div>
  81. </div>
  82. </template>
  83. <script>
  84. import { previewComponentList } from '@/views/book/courseware/data/bookType';
  85. import { SaveAnswer, GetAnswer, SaveAnswerMarking, GetAnswerMarking } from '@/api/book';
  86. import { buildCoursewareStyle } from '@/views/book/courseware/preview/common/utils/coursewareStyle';
  87. export default {
  88. name: 'CoursewarePreview',
  89. provide() {
  90. return {
  91. getDragStatus: () => false,
  92. bookInfo: this.bookInfo,
  93. };
  94. },
  95. props: {
  96. data: {
  97. type: Object,
  98. default: () => ({}),
  99. },
  100. coursewareId: {
  101. type: String,
  102. default: '',
  103. },
  104. background: {
  105. type: Object,
  106. default: () => ({}),
  107. },
  108. componentList: {
  109. type: Array,
  110. required: true,
  111. },
  112. canRemark: {
  113. type: Boolean,
  114. default: false,
  115. },
  116. showRemark: {
  117. type: Boolean,
  118. default: false,
  119. },
  120. componentRemarkObj: {
  121. type: Object,
  122. default: () => ({}),
  123. },
  124. groupRowList: {
  125. type: Array,
  126. default: () => [],
  127. },
  128. isShowGroup: {
  129. type: Boolean,
  130. default: false,
  131. },
  132. groupShowAll: {
  133. type: Boolean,
  134. default: true,
  135. },
  136. project: {
  137. type: Object,
  138. default: () => ({}),
  139. },
  140. // 是否启用选中文本工具
  141. enableTextSelection: {
  142. type: Boolean,
  143. default: true,
  144. },
  145. },
  146. data() {
  147. return {
  148. previewComponentList,
  149. courseware_id: this.coursewareId,
  150. bookInfo: {
  151. theme_color: '',
  152. },
  153. showMenu: false,
  154. divPosition: {
  155. left: 0,
  156. top: 0,
  157. }, // courseware盒子原始距离页面顶部和左边的距离
  158. menuPosition: { x: 0, y: 0, select_node: '' }, // 用于存储菜单的位置
  159. componentId: '', // 添加批注的组件id
  160. rowCheckList: {},
  161. showToolbar: false,
  162. contentmenu: {
  163. left: 0,
  164. top: 0,
  165. },
  166. selectedInfo: null,
  167. selectHandleInfo: null,
  168. getAnswerLoading: false, // 是否正在加载答案
  169. };
  170. },
  171. computed: {
  172. // 计算课件背景样式
  173. computedCoursewareStyle() {
  174. return buildCoursewareStyle(this.background, 'courseware');
  175. },
  176. },
  177. watch: {
  178. groupRowList: {
  179. handler(val) {
  180. if (!val) return;
  181. this.rowCheckList = val
  182. .filter(({ is_pre_same_group }) => !is_pre_same_group)
  183. .reduce((acc, row) => {
  184. acc[row.row_id] = false;
  185. return acc;
  186. }, {});
  187. },
  188. },
  189. coursewareId: {
  190. handler(val) {
  191. this.courseware_id = val;
  192. },
  193. },
  194. },
  195. mounted() {
  196. const element = this.$refs.courseware;
  197. const rect = element.getBoundingClientRect();
  198. this.divPosition = {
  199. left: rect.left,
  200. top: rect.top,
  201. };
  202. window.addEventListener('mousedown', this.handleMouseDown);
  203. },
  204. beforeDestroy() {
  205. window.removeEventListener('mousedown', this.handleMouseDown);
  206. },
  207. methods: {
  208. /**
  209. * 计算组件内容
  210. * @param {string} id 组件id
  211. * @returns {string} 组件内容
  212. */
  213. computedColContent(id) {
  214. if (!id) return '';
  215. return this.componentList.find((item) => item.component_id === id)?.content || '';
  216. },
  217. /**
  218. * 计算组件背景
  219. * @param {string} id 组件id
  220. * @returns {object} 组件背景样式
  221. */
  222. computedColBackground(id) {
  223. if (!id) return {};
  224. const background = this.componentList.find((item) => item.component_id === id)?.background;
  225. return background ? JSON.parse(background) : {};
  226. },
  227. getMultipleColStyle(i) {
  228. let row = this.data.row_list[i];
  229. let col = row.col_list;
  230. if (col.length <= 1) {
  231. return {
  232. gridTemplateColumns: '100fr',
  233. };
  234. }
  235. let gridTemplateColumns = row.width_list.join(' ');
  236. return {
  237. gridAutoFlow: 'column',
  238. gridTemplateColumns,
  239. gridTemplateRows: 'auto',
  240. };
  241. },
  242. /**
  243. * 计算行的可见性
  244. * @params {string} rowId 行的ID
  245. */
  246. computedRowVisibility(rowId) {
  247. if (this.groupShowAll) return true;
  248. let { row_id, is_pre_same_group } = this.groupRowList.find(({ row_id }) => row_id === rowId);
  249. if (is_pre_same_group) {
  250. const index = this.groupRowList.findIndex(({ row_id }) => row_id === rowId);
  251. if (index === -1) return false;
  252. for (let i = index - 1; i >= 0; i--) {
  253. if (!this.groupRowList[i].is_pre_same_group) {
  254. return this.rowCheckList[this.groupRowList[i].row_id];
  255. }
  256. }
  257. return false;
  258. }
  259. return this.rowCheckList[row_id];
  260. },
  261. /**
  262. * 分割整数为多个 1的倍数
  263. * @param {number} num
  264. * @param {number} parts
  265. */
  266. splitInteger(num, parts) {
  267. let base = Math.floor(num / parts);
  268. let arr = Array(parts).fill(base);
  269. let remainder = num - base * parts;
  270. for (let i = 0; remainder > 0; i = (i + 1) % parts) {
  271. arr[i] += 1;
  272. remainder -= 1;
  273. }
  274. return arr;
  275. },
  276. /**
  277. * 计算列的样式
  278. * @param {Object} col 列对象
  279. * @returns {Object} 列的样式对象
  280. */
  281. computedColStyle(col) {
  282. const grid = col.grid_list || [];
  283. if (!grid.length) {
  284. return {
  285. width: col.width,
  286. gridTemplateAreas: '',
  287. gridTemplateColumns: '',
  288. gridTemplateRows: '',
  289. };
  290. }
  291. // 一次遍历完成按行分组,并记录最大列数所在行
  292. let maxCol = 0;
  293. let curMaxRow = 0;
  294. const rowMap = new Map();
  295. grid.forEach((item) => {
  296. if (!rowMap.has(item.row)) {
  297. rowMap.set(item.row, []);
  298. }
  299. const rowItems = rowMap.get(item.row);
  300. rowItems.push(item);
  301. if (rowItems.length > maxCol) {
  302. maxCol = rowItems.length;
  303. curMaxRow = item.row;
  304. }
  305. });
  306. // 计算 grid_template_areas
  307. let gridTemplateAreas = '';
  308. const sortedRows = Array.from(rowMap.keys()).sort((a, b) => a - b);
  309. sortedRows.forEach((row) => {
  310. const rowItems = rowMap.get(row);
  311. const rowAreas = [];
  312. if (row === curMaxRow) {
  313. rowItems.forEach(({ grid_area }) => {
  314. rowAreas.push(`${grid_area}`);
  315. });
  316. } else {
  317. const needNum = maxCol - rowItems.length;
  318. const splitList = rowItems.length > 1 ? this.splitInteger(needNum, rowItems.length) : [];
  319. rowItems.forEach(({ grid_area }, index) => {
  320. if (rowItems.length === 1) {
  321. rowAreas.push(` ${grid_area} `.repeat(needNum + 1));
  322. return;
  323. }
  324. const repeatNum = splitList[index] + 1;
  325. rowAreas.push(splitList[index] === 0 ? ` ${grid_area} ` : ` ${grid_area} `.repeat(repeatNum));
  326. });
  327. }
  328. gridTemplateAreas += `'${rowAreas.join(' ')}' `;
  329. });
  330. // 计算 grid_template_columns
  331. const maxRowItems = rowMap.get(curMaxRow) || [];
  332. const gridTemplateColumns = maxRowItems.map(({ width }) => width).join(' ');
  333. // 计算 grid_template_rows
  334. let gridTemplateRows = '';
  335. const previewMap = new Map();
  336. (this.$refs.preview || []).forEach((child) => {
  337. const childId = child?.$el?.dataset?.id;
  338. if (childId) {
  339. previewMap.set(childId, child);
  340. }
  341. });
  342. rowMap.forEach((rowItems) => {
  343. if (rowItems.length === 1) {
  344. const onlyItem = rowItems[0];
  345. const component = previewMap.get(onlyItem.id);
  346. const hasOperation = component && component.$el.querySelector('.operation') !== null;
  347. const height = hasOperation ? `${Number(onlyItem.height.replace('px', '')) + 48}px` : onlyItem.height;
  348. gridTemplateRows += `${height} `;
  349. return;
  350. }
  351. const heightItems = rowItems.map(({ id, height }) => ({ id, height }));
  352. const isAllAuto = heightItems.every((item) => item.height === 'auto');
  353. if (isAllAuto) {
  354. gridTemplateRows += 'auto ';
  355. return;
  356. }
  357. let maxHeight = 0;
  358. let maxId = '';
  359. heightItems.forEach((item) => {
  360. if (item.height !== 'auto') {
  361. const heightNum = Number(item.height.replace('px', ''));
  362. if (heightNum > maxHeight) {
  363. maxHeight = heightNum;
  364. maxId = item.id;
  365. }
  366. }
  367. });
  368. const component = previewMap.get(maxId);
  369. const hasOperation = component && component.$el.querySelector('.operation') !== null;
  370. if (hasOperation) {
  371. maxHeight += 48;
  372. }
  373. const finalHeight = Math.max(
  374. ...heightItems.map((item) => {
  375. if (item.height === 'auto') return 0;
  376. if (item.id === maxId) return maxHeight;
  377. return Number(item.height.replace('px', ''));
  378. }),
  379. );
  380. gridTemplateRows += `${finalHeight}px `;
  381. });
  382. return {
  383. width: col.width,
  384. gridTemplateAreas,
  385. gridTemplateColumns,
  386. gridTemplateRows,
  387. };
  388. },
  389. handleContextMenu(event, id) {
  390. if (this.canRemark) {
  391. event.preventDefault(); // 阻止默认的上下文菜单显示
  392. this.menuPosition = {
  393. x: event.clientX - this.divPosition.left,
  394. y: event.clientY - this.divPosition.top,
  395. }; // 设置菜单位置
  396. this.componentId = id;
  397. this.$emit('computeScroll');
  398. }
  399. },
  400. handleResult(top, left, select_node) {
  401. this.menuPosition = {
  402. x: this.menuPosition.x + left,
  403. y: this.menuPosition.y + top,
  404. select_node,
  405. }; // 设置菜单位置
  406. this.showMenu = true; // 显示菜单
  407. },
  408. handleMenuItemClick() {
  409. this.showMenu = false; // 隐藏菜单
  410. this.$emit(
  411. 'addRemark',
  412. this.menuPosition.select_node,
  413. this.menuPosition.x,
  414. this.menuPosition.y,
  415. this.componentId,
  416. );
  417. },
  418. handleMouseDown(event) {
  419. if (event.button === 0 && event.target.className !== 'custom-context-menu') {
  420. // 0 表示左键
  421. this.showMenu = false;
  422. }
  423. },
  424. async findChildComponentByKey(id) {
  425. await this.$nextTick();
  426. if (!this.$refs.preview) {
  427. // 最多等待 1000ms
  428. for (let i = 0; i < 20; i++) {
  429. await this.$nextTick();
  430. await new Promise((resolve) => setTimeout(resolve, 50));
  431. if (this.$refs.preview) break;
  432. }
  433. }
  434. // 如果等待后还是不存在,那就返回null
  435. if (!this.$refs.preview) {
  436. console.error('$refs.preview 不存在');
  437. return null;
  438. }
  439. return this.$refs.preview.find((child) => child.$el && child.$el.dataset && child.$el.dataset.id === id);
  440. },
  441. /**
  442. * 模拟回答
  443. * @param {boolean} isJudgingRightWrong 是否判断对错
  444. * @param {boolean} isShowRightAnswer 是否显示正确答案
  445. * @param {boolean} disabled 是否禁用
  446. */
  447. simulateAnswer(isJudgingRightWrong, isShowRightAnswer, disabled = true, answer = null) {
  448. if (this.getAnswerLoading) return;
  449. this.$refs.preview.forEach((item) => {
  450. item.showAnswer(isJudgingRightWrong, isShowRightAnswer, answer, disabled);
  451. });
  452. },
  453. /**
  454. * 处理组件高度变化事件
  455. * @param {string} id 组件id
  456. * @param {string} newHeight 组件的新高度
  457. */
  458. handleHeightChange(id, newHeight) {
  459. this.data.row_list.forEach((row) => {
  460. row.col_list.forEach((col) => {
  461. col.grid_list.forEach((grid) => {
  462. if (grid.id === id) {
  463. grid.height = newHeight;
  464. }
  465. });
  466. });
  467. });
  468. },
  469. // 处理选中文本
  470. handleTextSelection() {
  471. // 如果禁用了文本选择工具栏,直接返回
  472. if (!this.enableTextSelection) {
  473. return;
  474. }
  475. this.showToolbar = false;
  476. // 延迟处理,确保选择已完成
  477. setTimeout(() => {
  478. const selection = window.getSelection();
  479. if (selection.toString().trim() === '') return null;
  480. const selectedText = selection.toString().trim();
  481. const range = selection.getRangeAt(0);
  482. this.selectedInfo = {
  483. text: selectedText,
  484. range,
  485. };
  486. let selectHandleInfo = this.getSelectionInfo();
  487. if (!selectHandleInfo || !selectHandleInfo.text) return;
  488. this.selectHandleInfo = selectHandleInfo;
  489. this.showToolbar = true;
  490. const container = document.querySelector('.courseware');
  491. const boxRect = container.getBoundingClientRect();
  492. const selectRect = range.getBoundingClientRect();
  493. this.contentmenu = {
  494. left: `${Math.round(selectRect.left - boxRect.left + selectRect.width / 2 - 63)}px`,
  495. top: `${Math.round(selectRect.top - boxRect.top + selectRect.height)}px`, // 向上偏移10px
  496. };
  497. }, 100);
  498. },
  499. // 笔记
  500. setNote() {
  501. this.showToolbar = false;
  502. this.oldRichData = {};
  503. let info = this.selectHandleInfo;
  504. if (!info) return;
  505. info.coursewareId = this.courseware_id;
  506. this.$emit('editNote', info);
  507. this.selectedInfo = null;
  508. },
  509. // 加入收藏
  510. setCollect() {
  511. this.showToolbar = false;
  512. let info = this.selectHandleInfo;
  513. if (!info) return;
  514. info.coursewareId = this.courseware_id;
  515. this.$emit('saveCollect', info);
  516. this.selectedInfo = null;
  517. },
  518. // 翻译
  519. setTranslate() {
  520. this.showToolbar = false;
  521. let info = this.selectHandleInfo;
  522. if (!info) return;
  523. info.coursewareId = this.courseware_id;
  524. this.$emit('getTranslate', info);
  525. this.selectedInfo = null;
  526. },
  527. // 反馈
  528. setFeedback() {
  529. this.showToolbar = false;
  530. this.oldRichData = {};
  531. let info = this.selectHandleInfo;
  532. if (!info) return;
  533. info.coursewareId = this.courseware_id;
  534. this.$emit('editFeedback', info);
  535. this.selectedInfo = null;
  536. },
  537. // 定位
  538. handleLocation(item) {
  539. this.scrollToDataId(item.blockId);
  540. },
  541. getSelectionInfo() {
  542. if (!this.selectedInfo) return;
  543. const range = this.selectedInfo.range;
  544. let selectedText = this.selectedInfo.text;
  545. if (!selectedText) return null;
  546. let commonAncestor = range.commonAncestorContainer;
  547. if (commonAncestor.nodeType === Node.TEXT_NODE) {
  548. commonAncestor = commonAncestor.parentNode;
  549. }
  550. const blockElement = commonAncestor.closest('[data-id]');
  551. if (!blockElement) return null;
  552. const blockId = blockElement.dataset.id;
  553. // 获取所有汉字元素
  554. const charElements = blockElement.querySelectorAll('.py-char,.rich-text,.NNPE-chs');
  555. // 构建包含位置信息的文本数组
  556. const textFragments = Array.from(charElements)
  557. .map((el, index) => {
  558. let text = '';
  559. if (el.classList.contains('rich-text')) {
  560. const pElements = Array.from(el.querySelectorAll('p'));
  561. text = pElements.map((p) => p.textContent.trim()).join('');
  562. } else if (el.classList.contains('NNPE-chs')) {
  563. const spanElements = Array.from(el.querySelectorAll('span'));
  564. spanElements.push(el);
  565. text = spanElements.map((span) => span.textContent.trim()).join('');
  566. } else {
  567. text = el.textContent.trim();
  568. }
  569. // 过滤掉拼音和空文本
  570. if (!text || /^[a-zāáǎàōóǒòēéěèīíǐìūúǔùǖǘǚǜü]+$/i.test(text)) {
  571. return { text: '', element: el, index };
  572. }
  573. return { text, element: el, index };
  574. })
  575. .filter((fragment) => fragment.text);
  576. // 获取完整的纯文本
  577. const fullText = textFragments.map((f) => f.text).join('');
  578. // 清理选中文本
  579. let cleanSelectedText = selectedText.replace(/\n/g, '').trim();
  580. cleanSelectedText = cleanSelectedText.replace(/[a-zāáǎàōóǒòēéěèīíǐìūúǔùǖǘǚǜü]/gi, '').trim();
  581. if (!cleanSelectedText) return null;
  582. // 方案1A:使用Range的边界点精确定位
  583. try {
  584. const startContainer = range.startContainer;
  585. const startOffset = range.startOffset;
  586. // 找到选择开始的元素在textFragments中的位置
  587. let startFragmentIndex = -1;
  588. let cumulativeLength = 0;
  589. let startIndexInFullText = -1;
  590. for (let i = 0; i < textFragments.length; i++) {
  591. const fragment = textFragments[i];
  592. // 检查这个元素是否包含选择起点
  593. if (fragment.element.contains(startContainer) || fragment.element === startContainer) {
  594. // 计算在这个元素内的起始位置
  595. if (startContainer.nodeType === Node.TEXT_NODE) {
  596. // 如果是文本节点,需要计算在父元素中的偏移
  597. const elementText = fragment.text;
  598. startFragmentIndex = i;
  599. startIndexInFullText = cumulativeLength + Math.min(startOffset, elementText.length);
  600. break;
  601. } else {
  602. // 如果是元素节点,从0开始
  603. startFragmentIndex = i;
  604. startIndexInFullText = cumulativeLength;
  605. break;
  606. }
  607. }
  608. cumulativeLength += fragment.text.length;
  609. }
  610. if (startIndexInFullText === -1) {
  611. // 如果精确定位失败,回退到文本匹配(但使用更智能的匹配)
  612. return this.fallbackToTextMatch(fullText, cleanSelectedText, range, textFragments);
  613. }
  614. const endIndexInFullText = startIndexInFullText + cleanSelectedText.length;
  615. return {
  616. blockId,
  617. text: cleanSelectedText,
  618. startIndex: startIndexInFullText,
  619. endIndex: endIndexInFullText,
  620. fullText,
  621. };
  622. } catch (error) {
  623. console.warn('精确位置计算失败,使用备选方案:', error);
  624. return this.fallbackToTextMatch(fullText, cleanSelectedText, range, textFragments);
  625. }
  626. },
  627. // 备选方案:基于DOM位置的智能匹配
  628. fallbackToTextMatch(fullText, selectedText, range, textFragments) {
  629. // 获取选择范围的近似位置
  630. const rangeRect = range.getBoundingClientRect();
  631. // 找到最接近选择中心的文本片段
  632. let closestFragment = null;
  633. let minDistance = Infinity;
  634. textFragments.forEach((fragment) => {
  635. const rect = fragment.element.getBoundingClientRect();
  636. if (rect.width > 0 && rect.height > 0) {
  637. // 确保元素可见
  638. const centerX = rect.left + rect.width / 2;
  639. const centerY = rect.top + rect.height / 2;
  640. const rangeCenterX = rangeRect.left + rangeRect.width / 2;
  641. const rangeCenterY = rangeRect.top + rangeRect.height / 2;
  642. const distance = Math.sqrt(Math.pow(centerX - rangeCenterX, 2) + Math.pow(centerY - rangeCenterY, 2));
  643. if (distance < minDistance) {
  644. minDistance = distance;
  645. closestFragment = fragment;
  646. }
  647. }
  648. });
  649. if (closestFragment) {
  650. // 从最近的片段开始向前后搜索匹配
  651. const fragmentIndex = textFragments.indexOf(closestFragment);
  652. let cumulativeLength = 0;
  653. // 计算到当前片段的累计长度
  654. for (let i = 0; i < fragmentIndex; i++) {
  655. cumulativeLength += textFragments[i].text.length;
  656. }
  657. // 在当前片段附近搜索匹配
  658. const searchStart = Math.max(0, cumulativeLength - selectedText.length * 3);
  659. const searchEnd = Math.min(
  660. fullText.length,
  661. cumulativeLength + closestFragment.text.length + selectedText.length * 3,
  662. );
  663. const searchArea = fullText.substring(searchStart, searchEnd);
  664. const localIndex = searchArea.indexOf(selectedText);
  665. if (localIndex !== -1) {
  666. return {
  667. startIndex: searchStart + localIndex,
  668. endIndex: searchStart + localIndex + selectedText.length,
  669. text: selectedText,
  670. fullText,
  671. };
  672. }
  673. }
  674. // 最终回退:使用所有匹配位置,选择最合理的一个
  675. const allMatches = [];
  676. let searchIndex = 0;
  677. while ((searchIndex = fullText.indexOf(selectedText, searchIndex)) !== -1) {
  678. allMatches.push(searchIndex);
  679. searchIndex += selectedText.length;
  680. }
  681. if (allMatches.length === 1) {
  682. return {
  683. startIndex: allMatches[0],
  684. endIndex: allMatches[0] + selectedText.length,
  685. text: selectedText,
  686. fullText,
  687. };
  688. } else if (allMatches.length > 1) {
  689. // 如果有多个匹配,选择位置最接近选择中心的
  690. if (closestFragment) {
  691. let cumulativeLength = 0;
  692. let fragmentStartIndex = 0;
  693. for (let i = 0; i < textFragments.length; i++) {
  694. if (textFragments[i] === closestFragment) {
  695. fragmentStartIndex = cumulativeLength;
  696. break;
  697. }
  698. cumulativeLength += textFragments[i].text.length;
  699. }
  700. // 选择最接近当前片段起始位置的匹配
  701. const bestMatch = allMatches.reduce((best, current) => {
  702. return Math.abs(current - fragmentStartIndex) < Math.abs(best - fragmentStartIndex) ? current : best;
  703. });
  704. return {
  705. startIndex: bestMatch,
  706. endIndex: bestMatch + selectedText.length,
  707. text: selectedText,
  708. fullText,
  709. };
  710. }
  711. }
  712. return null;
  713. },
  714. /**
  715. * 滚动到指定data-id的元素
  716. * @param {string} dataId 元素的data-id属性值
  717. * @param {number} offset 偏移量
  718. */
  719. scrollToDataId(dataId, offset) {
  720. let _offset = offset;
  721. if (!_offset) _offset = 0;
  722. const element = document.querySelector(`div[data-id="${dataId}"]`);
  723. if (element) {
  724. element.scrollIntoView({
  725. behavior: 'smooth', // 滚动行为:'auto' | 'smooth'
  726. block: 'center', // 垂直对齐:'start' | 'center' | 'end' | 'nearest'
  727. inline: 'nearest', // 水平对齐:'start' | 'center' | 'end' | 'nearest'
  728. });
  729. }
  730. },
  731. /**
  732. * 保存用户答案
  733. * @param {string} task_id 任务ID
  734. * @param {string} user_id 用户ID
  735. * @param {string} courseware_id 课件ID
  736. */
  737. saveAnswer({ task_id, user_id, courseware_id }) {
  738. let answer = {};
  739. this.$refs.preview.forEach((item) => {
  740. answer[item.id] = JSON.stringify(item.getAnswer());
  741. });
  742. SaveAnswer({
  743. task_id,
  744. user_id,
  745. courseware_id,
  746. answer: JSON.stringify(answer),
  747. }).then(() => {
  748. this.$message.success('答案保存成功');
  749. });
  750. },
  751. /**
  752. * 获取用户答案
  753. * @param {string} task_id 任务ID
  754. * @param {string} user_id 用户ID
  755. * @param {string} courseware_id 课件ID
  756. */
  757. getAnswer({ task_id, user_id, courseware_id }) {
  758. this.getAnswerLoading = true;
  759. GetAnswer({
  760. task_id,
  761. user_id,
  762. courseware_id,
  763. }).then(({ answer }) => {
  764. if (answer) {
  765. let _answer = JSON.parse(answer);
  766. this.$refs.preview.forEach((item) => {
  767. let answerItem = _answer[item.id];
  768. if (answerItem) {
  769. item.showAnswer(true, false, JSON.parse(answerItem), true);
  770. }
  771. });
  772. this.getAnswerLoading = false;
  773. }
  774. });
  775. },
  776. /**
  777. * 保存答案批改
  778. * @param {string} task_id 任务ID
  779. * @param {string} user_id 用户ID
  780. * @param {string} courseware_id 课件ID
  781. */
  782. saveAnswerMarking({ task_id, user_id, courseware_id }) {
  783. let answer_marking = {};
  784. this.$refs.preview.forEach((item) => {
  785. answer_marking[item.id] = JSON.stringify(item.getAnswerCorrect());
  786. });
  787. SaveAnswerMarking({
  788. task_id,
  789. user_id,
  790. courseware_id,
  791. answer_marking: JSON.stringify(answer_marking),
  792. }).then(() => {
  793. this.$message.success('批改保存成功');
  794. });
  795. },
  796. /**
  797. * 获取答案批改
  798. * @param {string} task_id 任务ID
  799. * @param {string} user_id 用户ID
  800. * @param {string} courseware_id 课件ID
  801. */
  802. getAnswerMarking({ task_id, user_id, courseware_id }) {
  803. GetAnswerMarking({
  804. task_id,
  805. user_id,
  806. courseware_id,
  807. }).then(({ answer_marking }) => {
  808. if (answer_marking) {
  809. let _answer_marking = JSON.parse(answer_marking);
  810. this.$refs.preview.forEach((item) => {
  811. let answerMarkingItem = _answer_marking[item.id];
  812. if (answerMarkingItem) {
  813. item.setAnswerCorrect(JSON.parse(answerMarkingItem));
  814. }
  815. });
  816. }
  817. });
  818. },
  819. },
  820. };
  821. </script>
  822. <style lang="scss" scoped>
  823. .courseware {
  824. position: relative;
  825. display: flex;
  826. flex-direction: column;
  827. row-gap: $component-spacing;
  828. width: 100%;
  829. max-width: $courseware-width;
  830. height: 100%;
  831. min-height: calc(100vh - 106px);
  832. padding-top: $courseware-top-padding;
  833. padding-bottom: $courseware-bottom-padding;
  834. margin: 15px 0;
  835. background-repeat: no-repeat;
  836. border-bottom-right-radius: 12px;
  837. border-bottom-left-radius: 12px;
  838. &::before {
  839. top: -15px;
  840. }
  841. &::after {
  842. bottom: -15px;
  843. }
  844. .row {
  845. display: grid;
  846. gap: $component-spacing;
  847. .col {
  848. display: grid;
  849. gap: $component-spacing;
  850. overflow: hidden;
  851. }
  852. .row-checkbox {
  853. position: absolute;
  854. left: 4px;
  855. }
  856. }
  857. .custom-context-menu,
  858. .remark-info {
  859. position: absolute;
  860. z-index: 999;
  861. display: flex;
  862. gap: 3px;
  863. align-items: center;
  864. font-size: 14px;
  865. cursor: pointer;
  866. }
  867. .custom-context-menu {
  868. padding-left: 30px;
  869. background: url('../../../../assets/icon-publish.png') left center no-repeat;
  870. background-size: 24px;
  871. }
  872. .contentmenu {
  873. position: absolute;
  874. z-index: 999;
  875. display: flex;
  876. column-gap: 4px;
  877. align-items: center;
  878. padding: 8px;
  879. font-size: 14px;
  880. color: #000;
  881. background-color: #e7e7e7;
  882. border-radius: 4px;
  883. box-shadow: 0 1px 10px 0 rgba(0, 0, 0, 30%);
  884. .svg-icon,
  885. .button {
  886. cursor: pointer;
  887. }
  888. .line {
  889. min-height: 16px;
  890. margin: 0 4px;
  891. }
  892. }
  893. }
  894. </style>