CreateCanvas.vue 65 KB

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