CreateCanvas.vue 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763
  1. <template>
  2. <main ref="canvas" class="canvas">
  3. <div v-if="isEdit" class="edit">
  4. <div v-for="item in lineList" :key="item[0]" class="group-line" :style="computedGroupLine(item)"></div>
  5. <span class="drag-line" data-row="-1"></span>
  6. <!-- 行 -->
  7. <template v-for="(row, i) in data.row_list">
  8. <div :key="row.row_id" class="row" :style="computedRowStyle(i)">
  9. <el-checkbox
  10. v-if="row?.row_id"
  11. v-model="rowCheckList[row.row_id]"
  12. :class="['row-checkbox', `${row.row_id}`]"
  13. />
  14. <!-- 列 -->
  15. <template v-for="(col, j) in row.col_list">
  16. <span
  17. v-if="j === 0"
  18. :key="`start-${row.row_id}-${col.col_id}`"
  19. class="drag-vertical-line col-start"
  20. :data-row="i"
  21. :data-col="j"
  22. ></span>
  23. <div :key="col.col_id" :class="['col', `col-${i}-${j}`]" :style="computedColStyle(col)">
  24. <!-- 网格 -->
  25. <template v-for="(grid, k) in col.grid_list">
  26. <span
  27. v-if="k === 0"
  28. :key="`start-${grid.id}`"
  29. class="drag-line grid-line drag-row"
  30. :style="{ gridArea: 'grid-top' }"
  31. :data-row="i"
  32. :data-col="j"
  33. :data-grid="k"
  34. data-type="row"
  35. ></span>
  36. <span
  37. v-if="grid.row > 1 && grid.row !== col.grid_list[k - 1].row"
  38. :key="`middle-${grid.id}`"
  39. :style="{ gridArea: `middle-${grid.grid_area}` }"
  40. :data-row="i"
  41. :data-col="j"
  42. :data-grid="k"
  43. data-type="col-middle"
  44. class="drag-line grid-line"
  45. ></span>
  46. <span
  47. :key="`left-${grid.id}`"
  48. :style="{ gridArea: `left-${grid.grid_area}` }"
  49. :data-row="i"
  50. :data-col="j"
  51. :data-grid="k"
  52. data-type="col-left"
  53. class="drag-vertical-line grid-line grid-line-left"
  54. ></span>
  55. <component
  56. :is="componentList[grid.type]"
  57. :id="grid.id"
  58. ref="component"
  59. :key="`grid-${grid.id}`"
  60. :old-id="grid?.oldId"
  61. :class="[grid.id]"
  62. :data-row="i"
  63. :data-col="j"
  64. :data-grid="k"
  65. :data-view-order="computedGridViewOrder(grid.id)"
  66. :border-color="computedBorderColor(row.row_id)"
  67. :style="computedGridStyle(grid, row.row_id)"
  68. :component-move="componentMove(i, j, k)"
  69. @deleteComponent="deleteComponentConfirm"
  70. @showSetting="showSetting"
  71. @copyComponent="copyComponent"
  72. @changeData="changeData"
  73. />
  74. <span
  75. :key="`right-${grid.id}`"
  76. :style="{ gridArea: `right-${grid.grid_area}` }"
  77. :data-row="i"
  78. :data-col="j"
  79. :data-grid="k + 1"
  80. data-type="col-right"
  81. class="drag-vertical-line grid-line grid-line-right"
  82. ></span>
  83. <span
  84. v-if="k === col.grid_list.length - 1"
  85. :key="`end-${grid.id}`"
  86. class="drag-line grid-line drag-row"
  87. :style="{ gridArea: `grid-bottom` }"
  88. :data-row="i"
  89. :data-col="j"
  90. :data-grid="k + 1"
  91. data-type="row"
  92. ></span>
  93. </template>
  94. </div>
  95. <span
  96. :key="`end-${row.row_id}-${col.col_id}`"
  97. class="drag-vertical-line col-end"
  98. :data-row="i"
  99. :data-col="j + 1"
  100. ></span>
  101. </template>
  102. </div>
  103. <span v-if="i < data.row_list.length - 1" :key="`row-${row.row_id}`" class="drag-line" :data-row="i"></span>
  104. </template>
  105. <span class="drag-line" :data-row="data.row_list.length - 1"></span>
  106. </div>
  107. <PreviewEdit
  108. v-else
  109. ref="previewEdit"
  110. :courseware-id="courseware_id"
  111. :row-list="data.row_list"
  112. @computedMoveData="computedMoveData"
  113. @handleHeightChange="handleHeightChange"
  114. />
  115. </main>
  116. </template>
  117. <script>
  118. import { getRandomNumber } from '@/utils/index';
  119. import { componentList } from '../../data/bookType';
  120. import {
  121. ContentSaveCoursewareContent,
  122. ContentGetCoursewareContent,
  123. GetBookUnifiedAttrib,
  124. ContentSaveCoursewareComponentContent,
  125. } from '@/api/book';
  126. import _ from 'lodash';
  127. import { unified_attrib } from '@/common/data';
  128. import PreviewEdit from './PreviewEdit.vue';
  129. export default {
  130. name: 'CreateCanvas',
  131. components: {
  132. PreviewEdit,
  133. },
  134. inject: ['getCurSettingId'],
  135. provide() {
  136. return {
  137. getBookUnifiedAttr: () => this.book_unified_attrib,
  138. getTitleList: () => this.title_list,
  139. getProjectResourcePopedom: () => this.projectResourcePopedom,
  140. moveComponentDragStart: this.dragStart,
  141. };
  142. },
  143. props: {
  144. isEdit: {
  145. type: Boolean,
  146. required: true,
  147. },
  148. },
  149. data() {
  150. const { project_id } = this.$route.query;
  151. return {
  152. courseware_id: this.$route.params.courseware_id,
  153. project_id,
  154. data: {
  155. // 组件列表
  156. row_list: [],
  157. // 样式调整
  158. unified_attrib,
  159. },
  160. visibleBackground: false, // 背景设置弹窗
  161. rowCheckList: {}, // 行复选框列表
  162. content_group_row_list: [], // 行分组id列表
  163. gridBorderColorList: ['#3fc7cc', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#d863ff', '#724fff'], // 网格边框颜色列表
  164. curType: 'divider',
  165. curParams: {}, // 当前组件参数
  166. scrollInterval: null, // 滚动定时器
  167. componentList,
  168. curRow: -2,
  169. curCol: -1,
  170. curGrid: -1,
  171. gridInsertType: '', // 网格插入类型
  172. enterCanvas: false, // 是否进入画布
  173. // 拖拽状态
  174. drag: {
  175. clientX: 0,
  176. clientY: 0,
  177. dragging: false,
  178. },
  179. visibleFullTextSettings: false,
  180. book_unified_attrib: unified_attrib,
  181. title_list: [],
  182. curComponentId: '', // 当前选中组件 id
  183. projectResourcePopedom: [], // 当前编辑人员的项目资源权限
  184. };
  185. },
  186. computed: {
  187. lineList() {
  188. let arr = [];
  189. this.content_group_row_list.forEach(({ row_id, is_pre_same_group }, i) => {
  190. if (is_pre_same_group) {
  191. arr.push([this.content_group_row_list[i - 1].row_id, row_id]);
  192. }
  193. });
  194. return arr;
  195. },
  196. },
  197. watch: {
  198. drag: {
  199. handler(val) {
  200. if (val.dragging) {
  201. const dragging = document.querySelector('.canvas-dragging');
  202. dragging.style.left = `${val.clientX}px`;
  203. dragging.style.top = `${val.clientY}px`;
  204. }
  205. },
  206. deep: true,
  207. },
  208. enterCanvas: {
  209. handler(val) {
  210. if (val) return;
  211. if (!this.isEdit) return;
  212. const dragLineList = document.querySelectorAll('.drag-line');
  213. dragLineList.forEach((item) => {
  214. item.style.opacity = 0;
  215. });
  216. this.curRow = -2;
  217. const dragVerticalLineList = document.querySelectorAll('.drag-vertical-line');
  218. dragVerticalLineList.forEach((item) => {
  219. item.style.opacity = 0;
  220. });
  221. this.curCol = -1;
  222. this.curGrid = -1;
  223. this.gridInsertType = '';
  224. },
  225. },
  226. 'data.row_list': {
  227. handler(val) {
  228. // row_list 更改时判断是否有当前设置 id 的组件
  229. const curSettingId = this.getCurSettingId();
  230. const find = val.find((row) => {
  231. return row.col_list.find((col) => {
  232. return col.grid_list.find((grid) => grid.id === curSettingId);
  233. });
  234. });
  235. if (!find) {
  236. this.$emit('showSettingEmpty');
  237. }
  238. this.rowCheckList = Object.fromEntries(val.filter((row) => row?.row_id).map((row) => [row.row_id, false]));
  239. // 增加新添的行
  240. val.forEach(({ row_id }, i) => {
  241. let isHas = this.content_group_row_list.some((group) => group.row_id === row_id);
  242. if (!isHas) {
  243. this.content_group_row_list.splice(i, 0, { row_id, is_pre_same_group: false });
  244. [i - 1, i + 1].forEach((start) => {
  245. let step = start < i ? -1 : 1;
  246. for (let j = start; j >= 0 && j < this.content_group_row_list.length; j += step) {
  247. if (this.content_group_row_list[j].is_pre_same_group) {
  248. this.content_group_row_list[j].is_pre_same_group = false;
  249. } else {
  250. break;
  251. }
  252. }
  253. });
  254. }
  255. });
  256. // 过滤掉已经不存在的行,并将第一行的 is_pre_same_group 设置为 false
  257. this.content_group_row_list = this.content_group_row_list.filter((group) =>
  258. val.find((row) => row.row_id === group.row_id),
  259. );
  260. if (this.content_group_row_list[0]) {
  261. this.content_group_row_list[0].is_pre_same_group = false;
  262. }
  263. },
  264. immediate: true,
  265. },
  266. rowCheckList: {
  267. handler(val) {
  268. // 如果同时有两个选中,将选中的挑选出来,并将它们的状态变为 false
  269. let selectedRowID = [];
  270. Object.keys(val).forEach((key) => {
  271. if (val[key]) {
  272. selectedRowID.push(key);
  273. }
  274. });
  275. if (selectedRowID.length > 1) {
  276. selectedRowID.forEach((id) => {
  277. this.rowCheckList[id] = false;
  278. });
  279. } else {
  280. return false;
  281. }
  282. let selectIndex = selectedRowID
  283. .map((id) => this.content_group_row_list.findIndex(({ row_id }) => row_id === id))
  284. .sort((a, b) => a - b);
  285. // 只处理选中两行的情况
  286. if (selectIndex[1] - selectIndex[0] === 1) {
  287. // 相邻两行,切换分组状态
  288. this.content_group_row_list[selectIndex[1]].is_pre_same_group =
  289. !this.content_group_row_list[selectIndex[1]].is_pre_same_group;
  290. } else {
  291. // 非相邻,判断中间行是否都已分组
  292. const allGrouped = this.content_group_row_list
  293. .slice(selectIndex[0] + 1, selectIndex[1] + 1)
  294. .every((group) => group.is_pre_same_group);
  295. for (let i = selectIndex[0] + 1; i <= selectIndex[1]; i++) {
  296. this.content_group_row_list[i].is_pre_same_group = !allGrouped;
  297. }
  298. }
  299. },
  300. deep: true,
  301. },
  302. },
  303. created() {
  304. const loading = this.$loading({
  305. lock: true,
  306. text: '组件加载中...',
  307. spinner: 'el-icon-loading',
  308. });
  309. ContentGetCoursewareContent({ id: this.courseware_id })
  310. .then(({ content, content_group_row_list, title_list, my_project_resource_popedom }) => {
  311. if (content) {
  312. let parsedContent = JSON.parse(content);
  313. if (
  314. parsedContent &&
  315. Array.isArray(parsedContent.row_list) &&
  316. parsedContent.row_list.length > 0 &&
  317. !parsedContent.row_list[0]?.row_id
  318. ) {
  319. this.data = this.normalizeRowColIds(parsedContent);
  320. } else {
  321. this.data = parsedContent;
  322. }
  323. loading.close();
  324. }
  325. if (content_group_row_list) this.content_group_row_list = JSON.parse(content_group_row_list);
  326. if (title_list) this.title_list = title_list || [];
  327. this.$watch(
  328. 'data',
  329. () => {
  330. this.changeData();
  331. },
  332. {
  333. deep: true,
  334. },
  335. );
  336. this.projectResourcePopedom = my_project_resource_popedom || [];
  337. })
  338. .finally(() => {
  339. loading.close();
  340. });
  341. this.getBookUnifiedAttr();
  342. },
  343. mounted() {
  344. document.addEventListener('mousemove', this.dragMove);
  345. document.addEventListener('mouseup', this.dragEnd);
  346. window.addEventListener('keydown', this.handleCopy);
  347. },
  348. beforeDestroy() {
  349. document.removeEventListener('mousemove', this.dragMove);
  350. document.removeEventListener('mouseup', this.dragEnd);
  351. window.removeEventListener('keydown', this.handleCopy);
  352. },
  353. methods: {
  354. /**
  355. * 监听复制事件,触发复制组件方法
  356. * @param {KeyboardEvent} event 键盘事件
  357. */
  358. handleCopy(event) {
  359. if (event.ctrlKey && event.key === 'c' && this.curComponentId.length > 0) {
  360. this.findChildComponentByKey(`grid-${this.curComponentId}`)?.copyComponent();
  361. }
  362. },
  363. handleHeightChange(id, newHeight) {
  364. this.data.row_list.forEach((row) => {
  365. row.col_list.forEach((col) => {
  366. col.grid_list.forEach((grid) => {
  367. if (grid.id === id) {
  368. grid.height = newHeight;
  369. }
  370. });
  371. });
  372. });
  373. },
  374. changeData() {
  375. this.$emit('changeData');
  376. },
  377. fullTextSettings(data) {
  378. this.$refs.component.forEach((item) => {
  379. item.updateProperty('view_pinyin', data.view_pinyin);
  380. item.updateProperty('pinyin_position', data.pinyin_position);
  381. item.updateRichTextProperty('fontFamily', data.font);
  382. item.updateRichTextProperty('fontSize', data.font_size);
  383. item.updateRichTextProperty('lineHeight', data.line_height);
  384. item.updateRichTextProperty('color', data.text_color);
  385. item.updateRichTextProperty('align', data.align);
  386. item.setUnifiedAttr(data);
  387. });
  388. this.data.unified_attrib = data;
  389. },
  390. applyToSelectedComponents(data) {
  391. this.$refs.component.forEach((item) => {
  392. if (item.$refs.base.checked) {
  393. item.updateProperty('view_pinyin', data.view_pinyin);
  394. item.updateProperty('pinyin_position', data.pinyin_position);
  395. item.updateRichTextProperty('fontFamily', data.font);
  396. item.updateRichTextProperty('fontSize', data.font_size);
  397. item.updateRichTextProperty('lineHeight', data.line_height);
  398. item.updateRichTextProperty('color', data.text_color);
  399. item.updateRichTextProperty('align', data.align);
  400. item.setUnifiedAttr(data);
  401. }
  402. });
  403. },
  404. getBookUnifiedAttr() {
  405. GetBookUnifiedAttrib({ book_id: this.project_id }).then(({ content }) => {
  406. if (content) {
  407. this.book_unified_attrib = JSON.parse(content);
  408. }
  409. });
  410. },
  411. /**
  412. * 保存课件内容
  413. * @param {string} type 类型
  414. */
  415. async saveCoursewareContent(type) {
  416. let isAllLoader = false;
  417. if (this.$refs?.component === undefined || this.$refs?.component.length === 0) {
  418. isAllLoader = true;
  419. } else if (this.isEdit) {
  420. isAllLoader = this.$refs?.component?.every((item) => item.property.isGetContent);
  421. } else {
  422. isAllLoader = this.$refs?.previewEdit?.$refs?.preview?.every((item) => item.loader);
  423. }
  424. if (!isAllLoader) {
  425. this.$message.warning('有组件内容未加载完成,请稍后再试');
  426. return false;
  427. }
  428. const loading = this.$loading({
  429. lock: true,
  430. text: '保存中...',
  431. spinner: 'el-icon-loading',
  432. background: 'rgba(0, 0, 0, 0.7)',
  433. });
  434. try {
  435. // 先等待所有子组件内容保存完成
  436. if (this.isEdit) {
  437. const comps = Array.isArray(this.$refs?.component)
  438. ? this.$refs.component
  439. : [this.$refs?.component].filter(Boolean);
  440. await Promise.all(comps.map((item) => item.saveCoursewareComponentContent()));
  441. }
  442. // 再收集并保存页面结构
  443. let component_id_list = this.data.row_list.flatMap((row) =>
  444. row.col_list.flatMap((col) => col.grid_list.map((grid) => grid.id)),
  445. );
  446. let groupIdList = _.cloneDeep(this.content_group_row_list);
  447. let groupList = [];
  448. // 通过判断 is_pre_same_group 将组合并
  449. for (let i = 0; i < groupIdList.length; i++) {
  450. if (groupIdList[i].is_pre_same_group) {
  451. groupList[groupList.length - 1].row_id_list.push(groupIdList[i].row_id);
  452. } else {
  453. groupList.push({
  454. name: '',
  455. row_id_list: [groupIdList[i].row_id],
  456. component_id_list: [],
  457. });
  458. }
  459. }
  460. // 通过合并后的分组,获取对应的组件 id 和分组名称
  461. groupList.forEach(({ row_id_list, component_id_list }, i) => {
  462. row_id_list.forEach((row_id, j) => {
  463. let row = this.data.row_list.find((row) => {
  464. return row.row_id === row_id;
  465. });
  466. // 当前行所有组件id列表
  467. let gridIdList = row.col_list.map((col) => col.grid_list.map((grid) => grid.id)).flat();
  468. component_id_list.push(...gridIdList);
  469. // 查找每组第一行中第一个包含 describe、label 或 stem 的组件
  470. if (j === 0) {
  471. let findKey = '';
  472. let findType = '';
  473. row.col_list.some((col) => {
  474. const findItem = col.grid_list.find(({ type }) => {
  475. return ['describe', 'label', 'stem'].includes(type);
  476. });
  477. if (findItem) {
  478. findKey = findItem.id;
  479. findType = findItem.type;
  480. return true;
  481. }
  482. });
  483. let groupName = `组${i + 1}`;
  484. // 如果有标签类组件,获取对应名称
  485. if (findKey) {
  486. let item = this.isEdit
  487. ? this.findChildComponentByKey(`grid-${findKey}`)
  488. : this.$refs.previewEdit.findChildComponentByKey(`preview-${findKey}`);
  489. if (['describe', 'stem'].includes(findType)) {
  490. groupName = item.data.content.replace(/<[^>]+>/g, '');
  491. } else if (findType === 'label') {
  492. groupName = item.data.dynamicTags.map((tag) => tag.text).join(', ');
  493. }
  494. }
  495. groupList[i].name = groupName;
  496. }
  497. });
  498. });
  499. await ContentSaveCoursewareContent({
  500. id: this.courseware_id,
  501. category: 'NEW',
  502. content: JSON.stringify(this.data),
  503. component_id_list,
  504. content_group_component_list: groupList,
  505. content_group_row_list: this.content_group_row_list,
  506. });
  507. this.$message.success('保存成功');
  508. if (type === 'quit') {
  509. this.$emit('back');
  510. }
  511. if (type === 'edit') {
  512. this.$emit('changeEditStatus');
  513. }
  514. } finally {
  515. loading.close();
  516. }
  517. },
  518. /**
  519. * 显示设置
  520. * @param {object} setting 组件设置数据
  521. * @param {string} type 组件类型
  522. * @param {string} id 组件 id
  523. * @param {object} params 组件参数
  524. */
  525. showSetting(setting, type, id, params = {}) {
  526. this.curComponentId = id;
  527. this.$emit('showSetting', setting, type, id, params);
  528. },
  529. /**
  530. * 组件中添加答案或解析
  531. * @param {'answer'|'analysis'} type 类型
  532. */
  533. addAnswerAndAnalysis(type) {
  534. this.findChildComponentByKey(`grid-${this.curComponentId}`)?.addAnswerAndAnalysis(type);
  535. },
  536. /**
  537. * 计算组件移动
  538. * @param {number} i 行
  539. * @param {number} j 列
  540. * @param {number} k 格子
  541. */
  542. componentMove(i, j, k) {
  543. return ({ type, offsetX, offsetY, id }) => {
  544. this.computedMoveData({ i, j, k, type, offsetX, offsetY, id });
  545. };
  546. },
  547. /**
  548. * 计算移动数据
  549. * @param {number} i 行
  550. * @param {number} j 列
  551. * @param {number} k 格子
  552. * @param {string} type 移动类型
  553. * @param {number} offsetX x 轴偏移量
  554. * @param {number} offsetY y 轴偏移量
  555. * @param {string} id 组件 id
  556. */
  557. computedMoveData({ i, j, k, type, offsetX, offsetY, id, min_width, min_height, row_width }) {
  558. const row = this.data.row_list[i];
  559. const col = row.col_list[j];
  560. const grid = col.grid_list[k];
  561. // 上下移动
  562. if (['top', 'bottom'].includes(type)) {
  563. this.handleVerticalMove(col, grid, offsetY, id, min_height);
  564. return;
  565. }
  566. // 一行中有多个格子
  567. let gridList = col.grid_list.filter((item) => item.row === grid.row);
  568. if (gridList.length > 1) {
  569. let find = gridList.findIndex((item) => item.id === id); // 当前 id 所在格子索引
  570. // 移动类型为 left 且不是第一个格子
  571. if (type === 'left' && find > 0) {
  572. this.handleMultGridLeftMoveNotFirstGrid({ gridList, grid, col, find, k, offsetX, min_width, row_width });
  573. }
  574. // 移动类型为 right 且不是最后一个格子
  575. if (type === 'right' && find < gridList.length - 1) {
  576. this.handleMultGridRightMoveNotFirstGrid({ gridList, grid, col, find, k, offsetX, min_width, row_width });
  577. }
  578. return;
  579. }
  580. // 移动类型为 left 且不是第一个格子
  581. if (type === 'left' && j > 0) {
  582. this.handleLeftMoveNotFirstGrid(row, j, offsetX, min_width, row_width);
  583. }
  584. // 移动类型为 right 且不是最后一个格子
  585. if (type === 'right' && j < row.col_list.length - 1) {
  586. this.handleRightMoveNotLastGrid(row, j, offsetX, min_width, row_width);
  587. }
  588. this.$forceUpdate();
  589. },
  590. /**
  591. * 处理垂直移动
  592. * @param {number} col 列数据
  593. * @param {object} grid 格子数据
  594. * @param {number} offsetY y 轴偏移量
  595. * @param {string} id 组件 id
  596. * @param {number} min_height 最小高度
  597. */
  598. handleVerticalMove(col, grid, offsetY, id, min_height = 0) {
  599. let height = 0;
  600. const _h = this.isEdit ? grid?.edit_height : grid.height;
  601. // 高度为 auto 时
  602. if (_h === 'auto' || _h === undefined) {
  603. const gridHeight = document.querySelector(`.${id}`).offsetHeight;
  604. height = gridHeight + offsetY;
  605. } else {
  606. // 高度为数字时
  607. const h = this.isEdit ? grid?.edit_height : grid.height;
  608. const gridHeight = Number(h?.replace('px', ''));
  609. height = gridHeight + offsetY;
  610. }
  611. // 当高度小于最小高度时,设置为最小高度
  612. height = Math.max(height, min_height, 50);
  613. if (this.isEdit) {
  614. grid.edit_height = `${height}px`;
  615. } else {
  616. grid.height = `${height}px`;
  617. }
  618. },
  619. /**
  620. * 处理左移且不是第一个格子
  621. * @param {object} row 行数据
  622. * @param {number} j 第几列
  623. * @param {number} offsetX x 轴偏移量
  624. * @param {number} min_width 最小宽度
  625. * @param {number} row_width 行宽度
  626. */
  627. handleLeftMoveNotFirstGrid(row, j, offsetX, min_width, row_width) {
  628. const prevGrid = row.width_list[j - 1];
  629. const prevWidth = Number(prevGrid.replace('fr', ''));
  630. const width = Number(row.width_list[j].replace('fr', ''));
  631. const max = prevWidth + width - 10;
  632. if (prevWidth + offsetX < 10 || prevWidth + offsetX > max || width - offsetX > max || width - offsetX < 10) {
  633. return;
  634. }
  635. // 计算拖动的距离与总宽度的比例
  636. const ratio = (offsetX / document.querySelector('.row').offsetWidth) * 100;
  637. const _w = width - ratio;
  638. if ((_w / 100) * row_width < min_width) {
  639. return;
  640. }
  641. row.width_list[j - 1] = `${prevWidth + ratio}fr`;
  642. row.width_list[j] = `${width - ratio}fr`;
  643. },
  644. /**
  645. * 处理一行中有多个格子的左移且不是第一个格子
  646. * @param {object} gridList 格子列表
  647. * @param {object} grid 格子数据
  648. * @param {object} col 列数据
  649. * @param {number} find 当前 id 所在格子索引
  650. * @param {number} k 格子的索引
  651. * @param {number} offsetX x 轴偏移量
  652. * @param {number} min_width 最小宽度
  653. */
  654. handleMultGridLeftMoveNotFirstGrid({ gridList, grid, col, find, k, offsetX, min_width, row_width }) {
  655. const prevGrid = gridList[find - 1];
  656. const prevWidth = Number(prevGrid.width.replace('fr', ''));
  657. const width = Number(grid.width.replace('fr', ''));
  658. const max = prevWidth + width - 10;
  659. if (prevWidth + offsetX < 10 || prevWidth + offsetX > max || width - offsetX > max || width - offsetX < 10) {
  660. return;
  661. }
  662. // 计算拖动的距离与总宽度的比例
  663. const ratio = (offsetX / document.querySelector('.row').offsetWidth) * 100;
  664. const _w = width - ratio;
  665. if ((_w / 100) * row_width < min_width) {
  666. return;
  667. }
  668. col.grid_list[k - 1].width = `${prevWidth + ratio}fr`;
  669. grid.width = `${_w}fr`;
  670. },
  671. /**
  672. * 处理右移且不是最后一个格子
  673. * @param {object} row 行数据
  674. * @param {number} j 第几列
  675. * @param {number} offsetX x 轴偏移量
  676. * @param {number} min_width 最小宽度
  677. * @param {number} row_width 行宽度
  678. */
  679. handleRightMoveNotLastGrid(row, j, offsetX, min_width, row_width) {
  680. let nextGrid = row.width_list[j + 1];
  681. const nextWidth = Number(nextGrid.replace('fr', ''));
  682. const width = Number(row.width_list[j].replace('fr', ''));
  683. const max = nextWidth + width - 10;
  684. if (nextWidth - offsetX < 10 || nextWidth - offsetX > max || width + offsetX > max || width + offsetX < 10) {
  685. return;
  686. }
  687. const ratio = (offsetX / document.querySelector('.row').offsetWidth) * 100;
  688. const _w = width + ratio;
  689. if ((_w / 100) * row_width < min_width) {
  690. return;
  691. }
  692. row.width_list[j + 1] = `${nextWidth - ratio}fr`;
  693. row.width_list[j] = `${width + ratio}fr`;
  694. },
  695. /**
  696. * 处理一行中有多个格子的右移且不是最后一个格子
  697. * @param {object} gridList 格子列表
  698. * @param {object} grid 格子数据
  699. * @param {object} col 列数据
  700. * @param {number} find 当前 id 所在格子索引
  701. * @param {number} k 格子的索引
  702. * @param {number} offsetX x 轴偏移量
  703. * @param {number} min_width 最小宽度
  704. */
  705. handleMultGridRightMoveNotFirstGrid({ gridList, grid, col, find, k, offsetX, min_width, row_width }) {
  706. let nextGrid = gridList[find + 1];
  707. const nextWidth = Number(nextGrid.width.replace('fr', ''));
  708. const width = Number(grid.width.replace('fr', ''));
  709. const max = nextWidth + width - 10;
  710. if (nextWidth - offsetX < 10 || nextWidth - offsetX > max || width + offsetX > max || width + offsetX < 10) {
  711. return;
  712. }
  713. const ratio = (offsetX / document.querySelector('.row').offsetWidth) * 100;
  714. const _w = width + ratio;
  715. if ((_w / 100) * row_width < min_width) {
  716. return;
  717. }
  718. col.grid_list[k + 1].width = `${nextWidth - ratio}fr`;
  719. grid.width = `${width + ratio}fr`;
  720. },
  721. /**
  722. * 重新计算格子宽度
  723. * @param {number} i 行
  724. * @param {number} j 列
  725. */
  726. recalculateGridWidth(i, j) {
  727. let col = this.data.row_list[i].col_list[j];
  728. let grid_template_columns = '0';
  729. col.grid_list.forEach(({ width }, i) => {
  730. const w = `${width}`;
  731. if (i === col.grid_list.length - 1) {
  732. grid_template_columns += ` ${w} 0`;
  733. } else {
  734. grid_template_columns += ` ${w} `;
  735. }
  736. });
  737. col.grid_template_columns = grid_template_columns;
  738. },
  739. async deleteComponentConfirm(id) {
  740. try {
  741. await this.$confirm('确定要删除该组件吗?', '提示', {
  742. confirmButtonText: '确定',
  743. cancelButtonText: '取消',
  744. type: 'warning',
  745. });
  746. this.deleteComponent(id);
  747. } catch (err) {
  748. if (err === 'cancel') {
  749. this.$message.info('已取消删除');
  750. }
  751. }
  752. },
  753. /**
  754. * 删除组件
  755. * @param {String} id 组件 id
  756. */
  757. deleteComponent(id) {
  758. const attrs = this.findChildComponentByKey(`grid-${id}`)?.$attrs;
  759. if (!attrs) return;
  760. const i = Number(attrs['data-row']);
  761. const j = Number(attrs['data-col']);
  762. const k = Number(attrs['data-grid']);
  763. const gridList = this.data.row_list[i].col_list[j].grid_list;
  764. let delRow = gridList[k].row; // 删除的 grid 的 row
  765. let delW = gridList[k].width; // 删除的 grid 的 width
  766. gridList.splice(k, 1);
  767. // 如果删除后没有 grid 了则删除列
  768. const colList = this.data.row_list[i].col_list[j];
  769. if (colList.grid_list.length === 0) {
  770. this.data.row_list[i].col_list.splice(j, 1);
  771. let width_list = this.data.row_list[i].width_list;
  772. const delW = width_list[j];
  773. width_list.splice(j, 1);
  774. this.data.row_list[i].width_list = width_list.map((item) => {
  775. return `${Number(item.replace('fr', '')) + Number(delW.replace('fr', '') / width_list.length)}fr`;
  776. });
  777. }
  778. // 如果删除后没有列了则删除行
  779. if (this.data.row_list[i].col_list.length === 0) {
  780. this.data.row_list.splice(i, 1);
  781. }
  782. // 如果删除后还有 grid 则重新计算 grid 的 row 和 width
  783. if (gridList?.length > 0) {
  784. let delNum = gridList.filter(({ row }) => row === delRow).length;
  785. let diff = Number(delW.replace('fr', '')) / delNum;
  786. if (delNum === 0) {
  787. // 删除 grid 后面的 row 都减 1
  788. gridList.forEach((item) => {
  789. if (item.row > delRow) {
  790. item.row -= 1;
  791. }
  792. });
  793. } else {
  794. gridList.forEach((item) => {
  795. if (item.row === delRow) {
  796. item.width = `${Number(item.width.replace('fr', '')) + diff}fr`;
  797. }
  798. });
  799. }
  800. }
  801. },
  802. computedColStyle(col) {
  803. const grid = col.grid_list || [];
  804. // 只分组一次,后续复用,避免在循环中反复 filter/find。
  805. const rowMap = new Map();
  806. const rowOrder = [];
  807. let maxCol = 0;
  808. let curMaxRow = 0;
  809. grid.forEach((item) => {
  810. if (!rowMap.has(item.row)) {
  811. rowMap.set(item.row, []);
  812. rowOrder.push(item.row);
  813. }
  814. const rowItems = rowMap.get(item.row);
  815. rowItems.push(item);
  816. if (rowItems.length > maxCol) {
  817. maxCol = rowItems.length;
  818. curMaxRow = item.row;
  819. }
  820. });
  821. // 计算 grid_template_areas
  822. const areaLines = [];
  823. rowOrder.forEach((row, index) => {
  824. const rowItems = rowMap.get(row) || [];
  825. if (index > 0 && row > 1) {
  826. areaLines.push(`'${`middle-${rowItems[0].grid_area} `.repeat(maxCol * 3)}'`);
  827. }
  828. const rowAreas = [];
  829. if (row === curMaxRow) {
  830. rowItems.forEach(({ grid_area }) => {
  831. rowAreas.push(`left-${grid_area} ${grid_area} right-${grid_area}`);
  832. });
  833. } else {
  834. const needNum = (maxCol - rowItems.length) * 3;
  835. const spread = rowItems.length > 1 ? this.splitInteger(needNum, rowItems.length) : [];
  836. rowItems.forEach(({ grid_area }, i) => {
  837. const repeatNum = rowItems.length === 1 ? needNum + 1 : spread[i] + 1;
  838. const inner = ` ${grid_area} `.repeat(repeatNum);
  839. rowAreas.push(`left-${grid_area} ${inner} right-${grid_area}`);
  840. });
  841. }
  842. areaLines.push(`'${rowAreas.join(' ')}'`);
  843. });
  844. // 计算 grid_template_columns(使用列数最多的一行作为基准)
  845. const maxRowItems = rowMap.get(curMaxRow) || [];
  846. const gridTemCols = maxRowItems.map(({ width }) => width).join(' 4px 4px ');
  847. // 计算 grid_template_rows
  848. const rowHeights = rowOrder.map((row) => {
  849. const heights = (rowMap.get(row) || []).map((item) => item?.edit_height || item.height);
  850. if (heights.length <= 1) return heights[0] || 'auto';
  851. const isAllAuto = heights.every((item) => item === 'auto');
  852. return isAllAuto ? 'auto' : `max(${heights.join(', ')})`;
  853. });
  854. return {
  855. width: col.width,
  856. gridTemplateAreas: `'${'grid-top '.repeat(maxCol * 3)}' ${areaLines.join(' ')} '${'grid-bottom '.repeat(maxCol * 3)}'`,
  857. gridTemplateColumns: `0 ${gridTemCols} 0`,
  858. gridTemplateRows: `0 ${rowHeights.join(' 4px ')} 0`,
  859. };
  860. },
  861. /**
  862. * 分割整数为多个 3 的倍数
  863. * @param {number} num
  864. * @param {number} parts
  865. */
  866. splitInteger(num, parts) {
  867. let base = Math.floor(num / parts / 3) * 3;
  868. let arr = Array(parts).fill(base);
  869. let remainder = num - base * parts;
  870. for (let i = 0; remainder > 0; i = (i + 1) % parts) {
  871. arr[i] += 3;
  872. remainder -= 3;
  873. }
  874. return arr;
  875. },
  876. /**
  877. * 拖拽开始
  878. * 用点击模拟拖拽
  879. * @param {MouseEvent} event 鼠标事件
  880. * @param {string} type 组件类型
  881. * @param {object} params 组件参数
  882. */
  883. dragStart(event, type, params = {}) {
  884. // 获取鼠标位置
  885. const { clientX, clientY } = event;
  886. document.body.style.userSelect = 'none'; // 禁止选中文本
  887. this.drag.dragging = true;
  888. this.curType = type;
  889. this.curParams = params;
  890. // 在鼠标位置创建一个拖拽元素
  891. const dragging = document.createElement('div');
  892. dragging.className = `canvas-dragging${type === 'component' ? ' component-dragging' : ''}`;
  893. this.drag.clientX = clientX;
  894. this.drag.clientY = clientY;
  895. document.body.appendChild(dragging);
  896. },
  897. /**
  898. * 鼠标移动
  899. */
  900. dragMove(event) {
  901. if (!this.drag.dragging) return;
  902. const { clientX, clientY } = event;
  903. this.drag.clientX = clientX;
  904. this.drag.clientY = clientY;
  905. if (!this.isEdit) return; // 非编辑状态不允许显隐线
  906. let { isInsideCanvas } = this.getMarginDifferences();
  907. this.enterCanvas = isInsideCanvas;
  908. if (!isInsideCanvas) return;
  909. // 当移动组件时,如果鼠标位置距离画布上下边距小于 20px,则自动滚动画布,做一个定时器每隔 100ms 判断一次,直到鼠标位置距离边距大于 20px 或者离开画布
  910. if (this.curType === 'component') {
  911. const middleDom = document.querySelector('.create-middle');
  912. // 获取 middleDom 相对于 event 的位置
  913. const middleRect = middleDom.getBoundingClientRect();
  914. const middleHeight = middleRect.height;
  915. const offsetTop = clientY - middleRect.top;
  916. const offsetBottom = middleRect.bottom - clientY;
  917. if (this.scrollInterval) {
  918. clearInterval(this.scrollInterval);
  919. }
  920. if (offsetTop < 20) {
  921. this.scrollInterval = setInterval(() => {
  922. middleDom.scrollTop = Math.max(0, middleDom.scrollTop - 10);
  923. }, 10);
  924. } else if (offsetBottom < 20) {
  925. this.scrollInterval = setInterval(() => {
  926. middleDom.scrollTop = Math.min(middleDom.scrollHeight - middleHeight, middleDom.scrollTop + 10);
  927. }, 10);
  928. } else {
  929. clearInterval(this.scrollInterval);
  930. this.scrollInterval = null;
  931. }
  932. }
  933. this.showRecentLine(clientX, clientY);
  934. },
  935. /**
  936. * 显示最近的线
  937. * @param {number} clientX
  938. * @param {number} clientY
  939. */
  940. showRecentLine(clientX, clientY) {
  941. const dragLineList = document.querySelectorAll('.drag-line'); // 获取所有的横线
  942. const dragVerticalLineList = document.querySelectorAll('.drag-vertical-line'); // 获取所有的竖线
  943. let minDistance = Infinity;
  944. let minIndex = -1;
  945. const list = [...dragLineList, ...dragVerticalLineList];
  946. list.forEach((item, index) => {
  947. const rect = item.getBoundingClientRect();
  948. const distance = Math.sqrt(
  949. Math.pow(clientX - rect.left - rect.width / 2, 2) + Math.pow(clientY - rect.top - rect.height / 2, 2),
  950. );
  951. if (distance < minDistance) {
  952. minDistance = distance;
  953. minIndex = index;
  954. }
  955. });
  956. list.forEach((item, index) => {
  957. if (index === minIndex) {
  958. this.curRow = Number(item.getAttribute('data-row'));
  959. this.curCol = Number(item.getAttribute('data-col') || -1);
  960. this.curGrid = Number(item.getAttribute('data-grid') || -1);
  961. this.gridInsertType = item.getAttribute('data-type') || '';
  962. item.style.opacity = 1;
  963. } else {
  964. item.style.opacity = 0;
  965. }
  966. });
  967. },
  968. /**
  969. * 鼠标松开
  970. */
  971. dragEnd() {
  972. document.body.style.userSelect = 'auto';
  973. const dragging = document.querySelector('.canvas-dragging');
  974. if (dragging) {
  975. document.body.removeChild(dragging);
  976. this.drag.dragging = false;
  977. }
  978. if (this.scrollInterval) {
  979. clearInterval(this.scrollInterval);
  980. this.scrollInterval = null;
  981. }
  982. if (!this.isEdit) return;
  983. if (this.enterCanvas) {
  984. if (this.curType === 'component') {
  985. this.handleComponentMove();
  986. return;
  987. }
  988. if (this.curRow >= -1 && this.curCol <= -1) {
  989. this.calculateRowInsertedObject();
  990. }
  991. if (this.curRow >= -1 && this.curCol > -1 && this.curGrid <= -1) {
  992. this.calculateColObject();
  993. }
  994. if (this.curRow >= -1 && this.curCol > -1 && this.curGrid > -1) {
  995. this.calculateGridObject();
  996. }
  997. }
  998. this.curType = '';
  999. this.curParams = {};
  1000. this.enterCanvas = false;
  1001. },
  1002. /**
  1003. * 处理组件移动
  1004. * 组件拖拽移动后,先删除组件,再根据拖拽位置计算插入行、列、格子
  1005. */
  1006. async handleComponentMove() {
  1007. const component = this.findChildComponentByKey(`grid-${this.curParams.id}`);
  1008. // 获取组件内容,保存后再插入到新的位置
  1009. const requestData = component.getComponentRequestContent();
  1010. const data = component?.data;
  1011. this.curType = data?.type || 'select';
  1012. let col = component?.$attrs['data-col'];
  1013. let row = component?.$attrs['data-row'];
  1014. let grid = component?.$attrs['data-grid'];
  1015. let rowNum = 0; // 当前行组件数量
  1016. this.data.row_list[row].col_list.forEach((item) => {
  1017. rowNum += item.grid_list.length;
  1018. });
  1019. this.curParams = {
  1020. ...this.curParams,
  1021. col,
  1022. row,
  1023. grid,
  1024. rowNum,
  1025. };
  1026. this.deleteComponent(this.curParams.id);
  1027. await ContentSaveCoursewareComponentContent(requestData);
  1028. if (this.curRow >= -1 && this.curCol <= -1) {
  1029. this.calculateRowInsertedObject();
  1030. }
  1031. if (this.curRow >= -1 && this.curCol > -1 && this.curGrid <= -1) {
  1032. // 当拖拽组件和放置位置在同一列内,且行内组件数量为 1,将 curRow 减 1,才能正确插入
  1033. if ('col' in this.curParams) {
  1034. const { row, rowNum } = this.curParams;
  1035. if (row === this.curRow && rowNum === 1) {
  1036. this.curRow = Math.max(0, this.curRow - 1);
  1037. this.calculateRowInsertedObject();
  1038. return;
  1039. }
  1040. }
  1041. this.calculateColObject();
  1042. }
  1043. if (this.curRow >= -1 && this.curCol > -1 && this.curGrid > -1) {
  1044. if ('col' in this.curParams) {
  1045. const { col, row, grid } = this.curParams;
  1046. // 当拖拽组件和放置位置在同一列内,将 curGrid 减 1,对应上面的删除组件,才能正确插入
  1047. if (col === this.curCol && row === this.curRow && grid < this.curGrid) {
  1048. this.curGrid = Math.max(0, this.curGrid - 1);
  1049. }
  1050. // 当拖拽组件和放置位置在同一列内,且行内组件数量为 1,将 curRow 减 1,才能正确插入
  1051. if (col === this.curCol && row === this.curRow && grid === this.curGrid) {
  1052. this.curRow = Math.max(0, this.curRow - 1);
  1053. this.calculateRowInsertedObject();
  1054. return;
  1055. }
  1056. }
  1057. this.calculateGridObject();
  1058. }
  1059. this.curType = '';
  1060. this.curParams = {};
  1061. this.enterCanvas = false;
  1062. },
  1063. /**
  1064. * 计算行样式
  1065. * @param {number} i 行索引
  1066. */
  1067. computedRowStyle(i) {
  1068. let row = this.data.row_list[i];
  1069. let col = row.col_list;
  1070. if (col.length <= 1) {
  1071. return {
  1072. gridTemplateColumns: '0 100fr 0',
  1073. };
  1074. }
  1075. let str = row.width_list
  1076. .map((item) => {
  1077. return `${item}`;
  1078. })
  1079. .join(' 6px ');
  1080. let gridTemplateColumns = `0 ${str} 0`;
  1081. return {
  1082. gridAutoFlow: 'column',
  1083. gridTemplateColumns,
  1084. gridTemplateRows: 'auto',
  1085. };
  1086. },
  1087. /**
  1088. * 计算网格插入的对象
  1089. */
  1090. calculateGridObject() {
  1091. const id = this.curParams?.id || `ID-${getRandomNumber(12, true)}`;
  1092. const letter = `L${getRandomNumber(6, true)}`;
  1093. let row = this.data.row_list[this.curRow];
  1094. let col = row.col_list[this.curCol];
  1095. let grid = col.grid_list;
  1096. let type = this.gridInsertType;
  1097. if (['row', 'col-middle'].includes(type)) {
  1098. let rowNum = this.curGrid === 0 ? 1 : grid[this.curGrid - 1].row + 1;
  1099. grid.splice(this.curGrid, 0, {
  1100. id,
  1101. grid_area: letter,
  1102. width: '100fr',
  1103. height: 'auto',
  1104. edit_height: 'auto',
  1105. row: rowNum,
  1106. type: this.curType,
  1107. });
  1108. // 在新加入的 grid 后面的 row 都加 1
  1109. grid.forEach((item, i) => {
  1110. if (i > this.curGrid) {
  1111. item.row += 1;
  1112. }
  1113. });
  1114. }
  1115. if (['col-left', 'col-right'].includes(type)) {
  1116. let rowNum = grid[type === 'col-left' ? this.curGrid : this.curGrid - 1].row;
  1117. grid.splice(this.curGrid, 0, {
  1118. id,
  1119. grid_area: letter,
  1120. width: '100fr',
  1121. height: 'auto',
  1122. edit_height: 'auto',
  1123. row: rowNum,
  1124. type: this.curType,
  1125. });
  1126. let allRowNum = grid.filter(({ row }) => row === rowNum).length;
  1127. let w = 0;
  1128. grid.forEach((item, i) => {
  1129. if (item.row === rowNum && i !== this.curGrid) {
  1130. let width = Number(item.width.replace('fr', ''));
  1131. let diff = width / allRowNum;
  1132. item.width = `${width - diff}fr`;
  1133. w += diff;
  1134. }
  1135. });
  1136. grid[this.curGrid].width = `${w}fr`;
  1137. }
  1138. },
  1139. /**
  1140. * 计算列插入的对象
  1141. */
  1142. calculateColObject() {
  1143. const id = this.curParams?.id || `ID-${getRandomNumber(12, true)}`;
  1144. const letter = `L${getRandomNumber(6, true)}`;
  1145. const col_id = `C${getRandomNumber(8, true)}`;
  1146. let row = this.data.row_list[this.curRow];
  1147. let col = row.col_list;
  1148. let w = 0;
  1149. row.width_list.forEach((item, i) => {
  1150. let itemW = Number(item.replace('fr', ''));
  1151. let rowW = itemW / (row.width_list.length + 1);
  1152. w += rowW;
  1153. row.width_list[i] = `${itemW - rowW}fr`;
  1154. });
  1155. row.width_list.splice(this.curCol, 0, `${w}fr`);
  1156. col.splice(this.curCol, 0, {
  1157. col_id,
  1158. width: '100fr',
  1159. height: 'auto',
  1160. grid_list: [
  1161. {
  1162. id,
  1163. grid_area: letter,
  1164. row: 1,
  1165. width: '100fr',
  1166. height: 'auto',
  1167. edit_height: 'auto',
  1168. type: this.curType,
  1169. },
  1170. ],
  1171. });
  1172. },
  1173. /**
  1174. * 计算行插入的对象
  1175. */
  1176. calculateRowInsertedObject() {
  1177. const id = this.curParams?.id || `ID-${getRandomNumber(12, true)}`;
  1178. const letter = `L${getRandomNumber(6, true)}`;
  1179. const row_id = `R${getRandomNumber(6, true)}`;
  1180. const col_id = `C${getRandomNumber(8, true)}`;
  1181. this.data.row_list.splice(this.curRow + 1, 0, {
  1182. width_list: ['100fr'],
  1183. row_id,
  1184. col_list: [
  1185. {
  1186. col_id,
  1187. width: '100fr',
  1188. height: 'auto',
  1189. grid_list: [
  1190. {
  1191. id,
  1192. grid_area: letter,
  1193. width: '100fr',
  1194. height: 'auto',
  1195. edit_height: 'auto',
  1196. row: 1,
  1197. type: this.curType,
  1198. },
  1199. ],
  1200. },
  1201. ],
  1202. });
  1203. },
  1204. /**
  1205. * 获取拖拽元素和画布的边距差值
  1206. * @returns {object} { leftMarginDifference, topMarginDifference, isInsideCanvas }
  1207. * leftMarginDifference: 拖拽元素和画布左边距差值
  1208. * topMarginDifference: 拖拽元素和画布上边距差值
  1209. * isInsideCanvas: 是否在画布内
  1210. */
  1211. getMarginDifferences() {
  1212. const rect1 = document.querySelector('.canvas-dragging').getBoundingClientRect();
  1213. const rect2 = this.$refs.canvas.getBoundingClientRect();
  1214. const leftMarginDifference = rect1.left - rect2.left + 128;
  1215. const topMarginDifference = rect1.top - rect2.top + 72;
  1216. let isInsideCanvas =
  1217. leftMarginDifference > 0 &&
  1218. leftMarginDifference < rect2.width &&
  1219. topMarginDifference > 0 &&
  1220. topMarginDifference < rect2.height;
  1221. return { leftMarginDifference, topMarginDifference, isInsideCanvas };
  1222. },
  1223. // 获取子组件
  1224. findChildComponentByKey(key) {
  1225. return this.$refs.component.find((child) => child.$vnode.key === key);
  1226. },
  1227. /**
  1228. * 计算分组线样式
  1229. * @param {Array} rowIdList 行 ID 列表
  1230. * @returns {Object} 样式对象
  1231. */
  1232. computedGroupLine(rowIdList) {
  1233. // 获取画布顶部位置
  1234. const canvas = this.$refs.canvas;
  1235. const firstCheckbox = this.$el.querySelector(`.row-checkbox.${rowIdList[0]}`);
  1236. const secCheckbox = this.$el.querySelector(`.row-checkbox.${rowIdList[1]}`);
  1237. // DOM 未渲染,返回默认样式或空对象
  1238. if (!canvas || !firstCheckbox || !secCheckbox) {
  1239. return {};
  1240. }
  1241. const canvasTop = canvas.getBoundingClientRect().top;
  1242. const firstRowTop = firstCheckbox.getBoundingClientRect().top;
  1243. const secRowTop = secCheckbox.getBoundingClientRect().top;
  1244. return {
  1245. top: `${firstRowTop - canvasTop + 22}px`,
  1246. height: `${secRowTop - firstRowTop - 24}px`,
  1247. };
  1248. },
  1249. computedBorderColor(rowId) {
  1250. const groupList = [];
  1251. this.content_group_row_list.forEach(({ row_id, is_pre_same_group }) => {
  1252. if (is_pre_same_group && groupList.length) {
  1253. groupList[groupList.length - 1].push(row_id);
  1254. } else {
  1255. groupList.push([row_id]);
  1256. }
  1257. });
  1258. const index = groupList.findIndex((g) => g.includes(rowId));
  1259. return this.gridBorderColorList[index % this.gridBorderColorList.length];
  1260. },
  1261. /**
  1262. * 计算网格样式
  1263. * @param {Object} grid 网格对象
  1264. * @returns {Object} 样式对象
  1265. */
  1266. computedGridStyle(grid) {
  1267. let marginTop = grid.row === 1 ? '0' : '6px';
  1268. return {
  1269. gridArea: grid.grid_area,
  1270. height: grid?.edit_height || grid.height,
  1271. marginTop,
  1272. };
  1273. },
  1274. /**
  1275. * 计算网格视图顺序
  1276. * @param {String} id 网格 ID
  1277. * @returns {Number} 顺序值
  1278. */
  1279. computedGridViewOrder(id) {
  1280. // 获取网格 id,是第几行第几列第几个网格,通过 data.row_list 计算
  1281. let rowIndex = -1;
  1282. let colIndex = -1;
  1283. let gridIndex = -1;
  1284. this.data.row_list.forEach((row, i) => {
  1285. row.col_list.forEach((col, j) => {
  1286. col.grid_list.forEach((grid, k) => {
  1287. if (grid.id === id) {
  1288. rowIndex = i;
  1289. colIndex = j;
  1290. gridIndex = k;
  1291. }
  1292. });
  1293. });
  1294. });
  1295. let order = 0;
  1296. // 计算前几行的网格数量
  1297. if (rowIndex > 0) {
  1298. for (let i = 0; i < rowIndex; i++) {
  1299. this.data.row_list[i].col_list.forEach((col) => {
  1300. order += col.grid_list.length;
  1301. });
  1302. }
  1303. }
  1304. // 计算当前行前几列的网格数量
  1305. if (colIndex > 0) {
  1306. for (let j = 0; j < colIndex; j++) {
  1307. order += this.data.row_list[rowIndex].col_list[j].grid_list.length;
  1308. }
  1309. }
  1310. // 加上当前列前面的网格数量
  1311. order += gridIndex + 1;
  1312. return order;
  1313. },
  1314. /**
  1315. * 归一化 row_list 中的 row_id / col_id(为后端旧数据补 id)
  1316. */
  1317. normalizeRowColIds(data) {
  1318. if (!data || !Array.isArray(data.row_list)) return data;
  1319. data.row_list = data.row_list.map((row) => {
  1320. if (!row.row_id) row.row_id = `R${getRandomNumber(6, true)}`;
  1321. if (!Array.isArray(row.col_list)) row.col_list = [];
  1322. row.col_list = row.col_list.map((col) => {
  1323. if (!col.col_id) col.col_id = `C${getRandomNumber(8, true)}`;
  1324. return col;
  1325. });
  1326. return row;
  1327. });
  1328. return data;
  1329. },
  1330. /**
  1331. * 加载模板数据
  1332. * @param {Object} param
  1333. * @param {Object} param.data - 模板数据
  1334. * @param {Array} param.content_group_row_list - 内容分组行列表
  1335. */
  1336. loadTemplateData_CreateCanvas({ data, content_group_row_list }) {
  1337. this.data = data || {
  1338. row_list: [],
  1339. };
  1340. this.content_group_row_list = content_group_row_list || [];
  1341. },
  1342. /**
  1343. * 插入模板数据
  1344. * @param {Object} param
  1345. * @param {Object} param.row_list - 模板组件列表
  1346. * @param {Array} param.content_group_row_list - 内容分组行列表
  1347. */
  1348. insertTemplateData_CreateCanvas({ row_list = [], content_group_row_list = [] }) {
  1349. let contentGroupRowList = JSON.parse(JSON.stringify(content_group_row_list));
  1350. let rowList = row_list.map((row) => {
  1351. const oldRowID = row.row_id;
  1352. const newRowID = `R${getRandomNumber(6, true)}`;
  1353. row.row_id = newRowID;
  1354. // 更新内容分组行列表中的 row_id
  1355. for (let idx = 0; idx < contentGroupRowList.length; idx++) {
  1356. if (contentGroupRowList[idx].row_id === oldRowID) {
  1357. contentGroupRowList[idx] = { ...contentGroupRowList[idx], row_id: newRowID };
  1358. }
  1359. }
  1360. row.col_list = row.col_list.map((col) => {
  1361. col.col_id = `C${getRandomNumber(8, true)}`;
  1362. col.grid_list = col.grid_list.map((grid) => {
  1363. grid.oldId = grid.id;
  1364. grid.id = `ID-${getRandomNumber(12, true)}`;
  1365. grid.grid_area = `L${getRandomNumber(6, true)}`;
  1366. return grid;
  1367. });
  1368. return col;
  1369. });
  1370. return row;
  1371. });
  1372. const curId = this.getCurSettingId();
  1373. // 如果无选中组件,则插入到最后
  1374. if (!curId) {
  1375. this.data.row_list.push(...rowList);
  1376. this.content_group_row_list.push(...contentGroupRowList);
  1377. return;
  1378. }
  1379. // 插入到当前选中组件后面
  1380. const attrs = this.findChildComponentByKey(`grid-${curId}`)?.$attrs;
  1381. if (!attrs) return;
  1382. const i = Number(attrs['data-row']);
  1383. this.data.row_list.splice(i + 1, 0, ...rowList);
  1384. this.content_group_row_list.splice(i + 1, 0, ...contentGroupRowList);
  1385. },
  1386. /**
  1387. * @description 复制组件
  1388. * @param {object} data 组件数据
  1389. */
  1390. copyComponent(data) {
  1391. this.$emit('copyComponent', data);
  1392. },
  1393. /**
  1394. * @description 粘贴组件
  1395. * @param {Object} componentData 组件数据
  1396. * @param {String} position 放入位置类型
  1397. */
  1398. pasteComponent(componentData, position) {
  1399. if (!componentData) return;
  1400. let _data = JSON.parse(JSON.stringify(componentData));
  1401. const curId = this.getCurSettingId();
  1402. const attrs = this.findChildComponentByKey(`grid-${curId}`)?.$attrs;
  1403. if (!attrs) return;
  1404. const i = Number(attrs['data-row']);
  1405. const j = Number(attrs['data-col']);
  1406. let k = Number(attrs['data-grid']);
  1407. let type = _data.type;
  1408. let row = this.data.row_list[i];
  1409. let col = row.col_list[j];
  1410. let grid = col.grid_list;
  1411. const id = `ID-${getRandomNumber(12, true)}`;
  1412. const letter = `L${getRandomNumber(6, true)}`;
  1413. if (['top', 'bottom'].includes(position)) {
  1414. let rowNum = k === 0 ? 1 : grid[k - 1].row + 1;
  1415. if (position === 'bottom') {
  1416. rowNum = grid[k].row + 1;
  1417. }
  1418. k = position === 'top' ? k : k + 1;
  1419. grid.splice(k, 0, {
  1420. id,
  1421. grid_area: letter,
  1422. width: '100fr',
  1423. height: 'auto',
  1424. edit_height: 'auto',
  1425. row: rowNum,
  1426. type,
  1427. });
  1428. grid.forEach((item, i) => {
  1429. if (i > k) {
  1430. item.row += 1;
  1431. }
  1432. });
  1433. }
  1434. if (['left', 'right'].includes(position)) {
  1435. let rowNum = grid[k].row;
  1436. let _k = position === 'left' ? k : k + 1;
  1437. grid.splice(_k, 0, {
  1438. id,
  1439. grid_area: letter,
  1440. width: '100fr',
  1441. height: 'auto',
  1442. edit_height: 'auto',
  1443. row: rowNum,
  1444. type,
  1445. });
  1446. let allRowNum = grid.filter(({ row }) => row === rowNum).length;
  1447. let w = 0;
  1448. grid.forEach((item, i) => {
  1449. if (item.row === rowNum && i !== k) {
  1450. let width = Number(item.width.replace('fr', ''));
  1451. let diff = width / allRowNum;
  1452. item.width = `${width - diff}fr`;
  1453. w += diff;
  1454. }
  1455. });
  1456. grid[_k].width = `${w}fr`;
  1457. }
  1458. this.$nextTick(() => {
  1459. let newComponent = this.findChildComponentByKey(`grid-${id}`); // 获取新添加的组件实例
  1460. newComponent?.setData(_data); // 设置新添加的组件数据
  1461. });
  1462. },
  1463. // 交换组件位置
  1464. switchComponent() {
  1465. let checkedNum = 0;
  1466. let components = [];
  1467. this.$refs.component.forEach((child) => {
  1468. if (child.$refs.base.checked) {
  1469. checkedNum += 1;
  1470. components.push(child.id);
  1471. }
  1472. });
  1473. if (checkedNum !== 2) {
  1474. this.$message.error('请选择两个组件进行交换');
  1475. return;
  1476. }
  1477. this.$confirm('组件未保存的改动将丢失。确定要交换这两个组件的位置吗?', '提示', {
  1478. confirmButtonText: '确定',
  1479. cancelButtonText: '取消',
  1480. type: 'warning',
  1481. })
  1482. .then(() => {
  1483. this.switchComponentData(components);
  1484. })
  1485. .catch(() => {
  1486. // 取消交换
  1487. });
  1488. },
  1489. /**
  1490. * 合并遍历 data.row_list,找到两个网格对象并直接交换它们的属性
  1491. * @param {Array} components 组件 ID 列表
  1492. */
  1493. switchComponentData(components) {
  1494. const [id1, id2] = components;
  1495. let g1 = null;
  1496. let g2 = null;
  1497. for (const row of this.data.row_list) {
  1498. for (const col of row.col_list) {
  1499. for (const grid of col.grid_list) {
  1500. if (grid.id === id1) g1 = grid;
  1501. else if (grid.id === id2) g2 = grid;
  1502. if (g1 && g2) break;
  1503. }
  1504. if (g1 && g2) break;
  1505. }
  1506. if (g1 && g2) break;
  1507. }
  1508. if (!g1 || !g2) return;
  1509. const tmp = { grid_area: g1.grid_area, id: g1.id, type: g1.type }; // 临时存储 g1 的属性
  1510. g1.grid_area = g2.grid_area;
  1511. g1.type = g2.type;
  1512. g1.id = g2.id;
  1513. g2.grid_area = tmp.grid_area;
  1514. g2.type = tmp.type;
  1515. g2.id = tmp.id;
  1516. },
  1517. clearContent() {
  1518. this.data.row_list = [];
  1519. this.content_group_row_list = [];
  1520. },
  1521. },
  1522. };
  1523. </script>
  1524. <style lang="scss" scoped>
  1525. .canvas {
  1526. .edit {
  1527. position: relative;
  1528. display: flex;
  1529. flex-direction: column;
  1530. row-gap: 8px;
  1531. width: $courseware-width;
  1532. min-height: calc(100vh - 240px);
  1533. padding: 24px;
  1534. margin: 0 auto;
  1535. background-color: #fff;
  1536. .group-line {
  1537. position: absolute;
  1538. left: 11px;
  1539. width: 1px;
  1540. background-color: #165dff;
  1541. }
  1542. .row {
  1543. display: grid;
  1544. row-gap: 16px;
  1545. .row-checkbox {
  1546. position: absolute;
  1547. left: 4px;
  1548. }
  1549. > .drag-vertical-line:not(:first-child, :last-child, .grid-line) {
  1550. left: 6px;
  1551. }
  1552. .drag-vertical-line.grid-line-right,
  1553. .drag-vertical-line.grid-line-left {
  1554. top: 25%;
  1555. height: 50%;
  1556. }
  1557. .drag-vertical-line.col-start {
  1558. left: -12px;
  1559. }
  1560. .drag-vertical-line.col-end {
  1561. right: -8px;
  1562. }
  1563. .col {
  1564. display: grid;
  1565. .drag-vertical-line:first-child {
  1566. left: -8px;
  1567. }
  1568. .drag-vertical-line:not(:first-child, :last-child, .grid-line) {
  1569. left: 6px;
  1570. }
  1571. .drag-vertical-line:last-child {
  1572. right: -4px;
  1573. }
  1574. }
  1575. }
  1576. .drag-line {
  1577. z-index: 2;
  1578. width: calc(100% - 16px);
  1579. height: 4px;
  1580. margin: 0 8px;
  1581. background-color: #379fff;
  1582. border-radius: 4px;
  1583. opacity: 0;
  1584. &.drag-row {
  1585. width: 50%;
  1586. margin-left: 25%;
  1587. background-color: $right-color;
  1588. }
  1589. &.grid-line:not(:first-child, :last-child) {
  1590. position: relative;
  1591. top: 6px;
  1592. }
  1593. &.grid-line {
  1594. background-color: #f43;
  1595. }
  1596. }
  1597. .drag-vertical-line {
  1598. position: relative;
  1599. z-index: 2;
  1600. width: 4px;
  1601. height: 100%;
  1602. background-color: #f43;
  1603. border-radius: 4px;
  1604. opacity: 0;
  1605. &.grid-line {
  1606. background-color: #f43;
  1607. }
  1608. }
  1609. }
  1610. }
  1611. </style>
  1612. <style lang="scss">
  1613. .canvas-dragging {
  1614. position: fixed;
  1615. z-index: 999;
  1616. width: 320px;
  1617. height: 180px;
  1618. background-color: #eaf5ff;
  1619. border: 1px solid #b5dbff;
  1620. border-radius: 4px;
  1621. opacity: 0.5;
  1622. transform: translate(-40%, -40%);
  1623. &.component-dragging {
  1624. background-color: #f9ffe0;
  1625. border-color: #f9ffe0;
  1626. }
  1627. }
  1628. </style>