CreateCanvas.vue 56 KB

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