1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240 |
- <template>
- <main
- ref="canvas"
- class="canvas"
- :style="[
- {
- backgroundImage: data.background_image_url ? `url(${data.background_image_url})` : '',
- backgroundSize: data.background_image_url
- ? `${data.background_position.width}% ${data.background_position.height}%`
- : '',
- backgroundPosition: data.background_image_url
- ? `${data.background_position.left}% ${data.background_position.top}%`
- : '',
- },
- ]"
- >
- <template v-if="isEdit">
- <div v-for="item in lineList" :key="item[0]" class="group-line" :style="computedGroupLine(item)"></div>
- <span class="drag-line" data-row="-1"></span>
- <!-- 行 -->
- <template v-for="(row, i) in data.row_list">
- <div :key="i" class="row" :style="computedRowStyle(i)">
- <el-checkbox
- v-if="row?.row_id"
- v-model="rowCheckList[row.row_id]"
- :class="['row-checkbox', `${row.row_id}`]"
- />
- <!-- 列 -->
- <template v-for="(col, j) in row.col_list">
- <span
- v-if="j === 0"
- :key="`start-${i}-${j}`"
- class="drag-vertical-line col-start"
- :data-row="i"
- :data-col="j"
- ></span>
- <div :key="j" :class="['col', `col-${i}-${j}`]" :style="computedColStyle(col)">
- <!-- 网格 -->
- <template v-for="(grid, k) in col.grid_list">
- <span
- v-if="k === 0"
- :key="`start-${i}-${j}-${k}`"
- class="drag-line grid-line drag-row"
- :style="{ gridArea: 'grid-top' }"
- :data-row="i"
- :data-col="j"
- :data-grid="k"
- data-type="row"
- ></span>
- <span
- v-if="grid.row > 1 && grid.row !== col.grid_list[k - 1].row"
- :key="`middle-${i}-${j}-${k}`"
- :style="{ gridArea: `middle-${grid.grid_area}` }"
- :data-row="i"
- :data-col="j"
- :data-grid="k"
- data-type="col-middle"
- class="drag-line grid-line"
- ></span>
- <span
- :key="`left-${i}-${j}-${k}`"
- :style="{ gridArea: `left-${grid.grid_area}` }"
- :data-row="i"
- :data-col="j"
- :data-grid="k"
- data-type="col-left"
- class="drag-vertical-line grid-line grid-line-left"
- ></span>
- <component
- :is="componentList[grid.type]"
- :id="grid.id"
- ref="component"
- :key="`grid-${grid.id}`"
- :class="[grid.id]"
- :border-color="computedBorderColor(row.row_id)"
- :style="computedGridStyle(grid, row.row_id)"
- :delete-component="deleteComponent(i, j, k)"
- :component-move="componentMove(i, j, k)"
- @showSetting="showSetting"
- @changeData="changeData"
- />
- <span
- :key="`right-${i}-${j}-${k}`"
- :style="{ gridArea: `right-${grid.grid_area}` }"
- :data-row="i"
- :data-col="j"
- :data-grid="k + 1"
- data-type="col-right"
- class="drag-vertical-line grid-line grid-line-right"
- ></span>
- <span
- v-if="k === col.grid_list.length - 1"
- :key="`end-${i}-${j}-${k}`"
- class="drag-line grid-line drag-row"
- :style="{ gridArea: `grid-bottom` }"
- :data-row="i"
- :data-col="j"
- :data-grid="k + 1"
- data-type="row"
- ></span>
- </template>
- </div>
- <span :key="`end-${i}-${j}`" class="drag-vertical-line col-end" :data-row="i" :data-col="j + 1"></span>
- </template>
- </div>
- <span v-if="i < data.row_list.length - 1" :key="`row-${i}`" class="drag-line" :data-row="i"></span>
- </template>
- <span class="drag-line" :data-row="data.row_list.length - 1"></span>
- </template>
- <PreviewEdit v-else :courseware-id="courseware_id" :row-list="data.row_list" @computedMoveData="computedMoveData" />
- </main>
- </template>
- <script>
- import { getRandomNumber } from '@/utils/index';
- import { componentList } from '../../data/bookType';
- import { ContentSaveCoursewareContent, ContentGetCoursewareContent } from '@/api/book';
- import _ from 'lodash';
- import PreviewEdit from './PreviewEdit.vue';
- export default {
- name: 'CreateCanvas',
- components: {
- PreviewEdit,
- },
- inject: ['getCurSettingId'],
- props: {
- isEdit: {
- type: Boolean,
- required: true,
- },
- },
- data() {
- const { project_id } = this.$route.query;
- return {
- courseware_id: this.$route.params.courseware_id,
- project_id,
- data: {
- background_image_url: '',
- background_position: {
- width: 100,
- height: 100,
- top: 0,
- left: 0,
- },
- // 组件列表
- row_list: [],
- },
- rowCheckList: {}, // 行复选框列表
- content_group_row_list: [], // 行分组id列表
- gridBorderColorList: ['#3fc7cc', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#d863ff', '#724fff'], // 网格边框颜色列表
- curType: 'divider',
- componentList,
- curRow: -2,
- curCol: -1,
- curGrid: -1,
- gridInsertType: '', // 网格插入类型
- enterCanvas: false, // 是否进入画布
- // 拖拽状态
- drag: {
- clientX: 0,
- clientY: 0,
- dragging: false,
- },
- };
- },
- computed: {
- lineList() {
- let arr = [];
- this.content_group_row_list.forEach(({ row_id, is_pre_same_group }, i) => {
- if (is_pre_same_group) {
- arr.push([this.content_group_row_list[i - 1].row_id, row_id]);
- }
- });
- return arr;
- },
- },
- watch: {
- drag: {
- handler(val) {
- if (val.dragging) {
- const dragging = document.querySelector('.canvas-dragging');
- dragging.style.left = `${val.clientX}px`;
- dragging.style.top = `${val.clientY}px`;
- }
- },
- deep: true,
- },
- enterCanvas: {
- handler(val) {
- if (val) return;
- if (!this.isEdit) return;
- const dragLineList = document.querySelectorAll('.drag-line');
- dragLineList.forEach((item) => {
- item.style.opacity = 0;
- });
- this.curRow = -2;
- const dragVerticalLineList = document.querySelectorAll('.drag-vertical-line');
- dragVerticalLineList.forEach((item) => {
- item.style.opacity = 0;
- });
- this.curCol = -1;
- this.curGrid = -1;
- this.gridInsertType = '';
- },
- },
- 'data.row_list': {
- handler(val) {
- // row_list 更改时判断是否有当前设置 id 的组件
- const curSettingId = this.getCurSettingId();
- const find = val.find((row) => {
- return row.col_list.find((col) => {
- return col.grid_list.find((grid) => grid.id === curSettingId);
- });
- });
- if (!find) {
- this.$emit('showSettingEmpty');
- }
- this.rowCheckList = Object.fromEntries(val.filter((row) => row?.row_id).map((row) => [row.row_id, false]));
- // 增加新添的行
- val.forEach(({ row_id }, i) => {
- let isHas = this.content_group_row_list.some((group) => group.row_id === row_id);
- if (!isHas) {
- this.content_group_row_list.splice(i, 0, { row_id, is_pre_same_group: false });
- }
- });
- // 过滤掉已经不存在的行
- this.content_group_row_list = this.content_group_row_list.filter((group) => {
- return val.find((row) => row.row_id === group.row_id);
- });
- },
- immediate: true,
- },
- rowCheckList: {
- handler(val) {
- // 如果同时有两个选中,将选中的挑选出来,并将它们的状态变为 false
- let selectedRowID = [];
- Object.keys(val).forEach((key) => {
- if (val[key]) {
- selectedRowID.push(key);
- }
- });
- if (selectedRowID.length > 1) {
- selectedRowID.forEach((id) => {
- this.rowCheckList[id] = false;
- });
- } else {
- return false;
- }
- let selectIndex = selectedRowID
- .map((id) => this.content_group_row_list.findIndex(({ row_id }) => row_id === id))
- .sort((a, b) => a - b);
- // 只处理选中两行的情况
- if (selectIndex[1] - selectIndex[0] === 1) {
- // 相邻两行,切换分组状态
- this.content_group_row_list[selectIndex[1]].is_pre_same_group =
- !this.content_group_row_list[selectIndex[1]].is_pre_same_group;
- } else {
- // 非相邻,判断中间行是否都已分组
- const allGrouped = this.content_group_row_list
- .slice(selectIndex[0] + 1, selectIndex[1] + 1)
- .every((group) => group.is_pre_same_group);
- for (let i = selectIndex[0] + 1; i <= selectIndex[1]; i++) {
- this.content_group_row_list[i].is_pre_same_group = !allGrouped;
- }
- }
- },
- deep: true,
- },
- },
- created() {
- ContentGetCoursewareContent({ id: this.courseware_id }).then(({ content, content_group_row_list }) => {
- if (content) {
- this.data = JSON.parse(content);
- }
- if (content_group_row_list) this.content_group_row_list = JSON.parse(content_group_row_list);
- this.$watch(
- 'data',
- () => {
- this.changeData();
- },
- {
- deep: true,
- },
- );
- });
- },
- mounted() {
- document.addEventListener('mousemove', this.dragMove);
- document.addEventListener('mouseup', this.dragEnd);
- },
- beforeDestroy() {
- document.removeEventListener('mousemove', this.dragMove);
- document.removeEventListener('mouseup', this.dragEnd);
- },
- methods: {
- changeData() {
- this.$emit('changeData');
- },
- /**
- * 保存课件内容
- * @param {string} type 类型
- */
- saveCoursewareContent(type) {
- let component_id_list = this.data.row_list.flatMap((row) =>
- row.col_list.flatMap((col) => col.grid_list.map((grid) => grid.id)),
- );
- this.$refs?.component.forEach((item) => {
- item.saveCoursewareComponentContent();
- });
- const loading = this.$loading({
- lock: true,
- text: '保存中...',
- spinner: 'el-icon-loading',
- background: 'rgba(0, 0, 0, 0.7)',
- });
- let groupIdList = _.cloneDeep(this.content_group_row_list);
- let groupList = [];
- // 通过判断 is_pre_same_group 将组合并
- for (let i = 0; i < groupIdList.length; i++) {
- if (groupIdList[i].is_pre_same_group) {
- groupList[groupList.length - 1].row_id_list.push(groupIdList[i].row_id);
- } else {
- groupList.push({
- name: '',
- row_id_list: [groupIdList[i].row_id],
- component_id_list: [],
- });
- }
- }
- // 通过合并后的分组,获取对应的组件 id 和分组名称
- groupList.forEach(({ row_id_list, component_id_list }, i) => {
- row_id_list.forEach((row_id, j) => {
- let row = this.data.row_list.find((row) => {
- return row.row_id === row_id;
- });
- // 当前行所有组件id列表
- let gridIdList = row.col_list.map((col) => col.grid_list.map((grid) => grid.id)).flat();
- component_id_list.push(...gridIdList);
- // 查找每组第一行中第一个包含 describe、label 或 stem 的组件
- if (j === 0) {
- let findKey = '';
- let findType = '';
- row.col_list.some((col) => {
- const findItem = col.grid_list.find(({ type }) => {
- return ['describe', 'label', 'stem'].includes(type);
- });
- if (findItem) {
- findKey = findItem.id;
- findType = findItem.type;
- return true;
- }
- });
- let groupName = `组${i + 1}`;
- // 如果有标签类组件,获取对应名称
- if (findKey) {
- let item = this.findChildComponentByKey(`grid-${findKey}`);
- if (['describe', 'stem'].includes(findType)) {
- groupName = item.data.content.replace(/<[^>]+>/g, ''); // 去掉html标签
- } else if (findType === 'label') {
- groupName = item.data.dynamicTags.map((tag) => tag.text).join(', ');
- }
- }
- groupList[i].name = groupName;
- }
- });
- });
- ContentSaveCoursewareContent({
- id: this.courseware_id,
- category: 'NEW',
- content: JSON.stringify(this.data),
- component_id_list,
- content_group_component_list: groupList,
- content_group_row_list: this.content_group_row_list,
- }).then(() => {
- this.$message.success('保存成功');
- loading.close();
- if (type === 'quit') {
- this.$emit('back');
- }
- if (type === 'edit') {
- this.$emit('changeEditStatus');
- }
- });
- },
- setBackgroundImage(url, position) {
- this.data.background_image_url = url;
- this.data.background_position = position;
- this.$message.success('设置背景图成功');
- },
- /**
- * 显示设置
- * @param {object} setting
- * @param {string} type
- * @param {string} id
- * @param {object} params
- */
- showSetting(setting, type, id, params = {}) {
- this.$emit('showSetting', setting, type, id, params);
- },
- /**
- * 计算组件移动
- * @param {number} i 行
- * @param {number} j 列
- * @param {number} k 格子
- */
- componentMove(i, j, k) {
- return ({ type, offsetX, offsetY, id }) => {
- this.computedMoveData({ i, j, k, type, offsetX, offsetY, id });
- };
- },
- /**
- * 计算移动数据
- * @param {number} i 行
- * @param {number} j 列
- * @param {number} k 格子
- * @param {string} type 移动类型
- * @param {number} offsetX x 轴偏移量
- * @param {number} offsetY y 轴偏移量
- * @param {string} id 组件 id
- */
- computedMoveData({ i, j, k, type, offsetX, offsetY, id, min_width, min_height, row_width }) {
- const row = this.data.row_list[i];
- const col = row.col_list[j];
- const grid = col.grid_list[k];
- // 上下移动
- if (['top', 'bottom'].includes(type)) {
- this.handleVerticalMove(col, grid, offsetY, id, min_height);
- return;
- }
- // 一行中有多个格子
- let gridList = col.grid_list.filter((item) => item.row === grid.row);
- if (gridList.length > 1) {
- let find = gridList.findIndex((item) => item.id === id); // 当前 id 所在格子索引
- // 移动类型为 left 且不是第一个格子
- if (type === 'left' && find > 0) {
- this.handleMultGridLeftMoveNotFirstGrid({ gridList, grid, col, find, k, offsetX, min_width, row_width });
- }
- // 移动类型为 right 且不是最后一个格子
- if (type === 'right' && find < gridList.length - 1) {
- this.handleMultGridRightMoveNotFirstGrid({ gridList, grid, col, find, k, offsetX, min_width, row_width });
- }
- return;
- }
- // 移动类型为 left 且不是第一个格子
- if (type === 'left' && j > 0) {
- this.handleLeftMoveNotFirstGrid(row, j, offsetX, min_width, row_width);
- }
- // 移动类型为 right 且不是最后一个格子
- if (type === 'right' && j < row.col_list.length - 1) {
- this.handleRightMoveNotLastGrid(row, j, offsetX, min_width, row_width);
- }
- this.$forceUpdate();
- },
- /**
- * 处理垂直移动
- * @param {number} col 列数据
- * @param {object} grid 格子数据
- * @param {number} offsetY y 轴偏移量
- * @param {string} id 组件 id
- * @param {number} min_height 最小高度
- */
- handleVerticalMove(col, grid, offsetY, id, min_height) {
- // 高度为 auto 时
- if (grid.height === 'auto') {
- const gridHeight = document.querySelector(`.${id}`).offsetHeight;
- const height = gridHeight + offsetY;
- if (height < min_height) {
- return;
- }
- grid.height = `${gridHeight + offsetY}px`;
- col.grid_template_rows = `0 ${col.grid_list.map(({ height }) => height).join(' 6px ')} 0`;
- return;
- }
- // 高度为数字时
- const height = Number(grid.height.replace('px', ''));
- const _h = height + offsetY;
- if (_h < min_height) {
- return;
- }
- if (_h >= 50) {
- grid.height = `${_h}px`;
- col.grid_template_rows = `0 ${col.grid_list.map(({ height }) => height).join(' 6px ')} 0`;
- }
- },
- /**
- * 处理左移且不是第一个格子
- * @param {object} row 行数据
- * @param {number} j 第几列
- * @param {number} offsetX x 轴偏移量
- * @param {number} min_width 最小宽度
- * @param {number} row_width 行宽度
- */
- handleLeftMoveNotFirstGrid(row, j, offsetX, min_width, row_width) {
- const prevGrid = row.width_list[j - 1];
- const prevWidth = Number(prevGrid.replace('fr', ''));
- const width = Number(row.width_list[j].replace('fr', ''));
- const max = prevWidth + width - 10;
- if (prevWidth + offsetX < 10 || prevWidth + offsetX > max || width - offsetX > max || width - offsetX < 10) {
- return;
- }
- // 计算拖动的距离与总宽度的比例
- const ratio = (offsetX / document.querySelector('.row').offsetWidth) * 100;
- const _w = width - ratio;
- if ((_w / 100) * row_width < min_width) {
- return;
- }
- row.width_list[j - 1] = `${prevWidth + ratio}fr`;
- row.width_list[j] = `${width - ratio}fr`;
- },
- /**
- * 处理一行中有多个格子的左移且不是第一个格子
- * @param {object} gridList 格子列表
- * @param {object} grid 格子数据
- * @param {object} col 列数据
- * @param {number} find 当前 id 所在格子索引
- * @param {number} k 格子的索引
- * @param {number} offsetX x 轴偏移量
- * @param {number} min_width 最小宽度
- */
- handleMultGridLeftMoveNotFirstGrid({ gridList, grid, col, find, k, offsetX, min_width, row_width }) {
- const prevGrid = gridList[find - 1];
- const prevWidth = Number(prevGrid.width.replace('fr', ''));
- const width = Number(grid.width.replace('fr', ''));
- const max = prevWidth + width - 10;
- if (prevWidth + offsetX < 10 || prevWidth + offsetX > max || width - offsetX > max || width - offsetX < 10) {
- return;
- }
- // 计算拖动的距离与总宽度的比例
- const ratio = (offsetX / document.querySelector('.row').offsetWidth) * 100;
- const _w = width - ratio;
- if ((_w / 100) * row_width < min_width) {
- return;
- }
- col.grid_list[k - 1].width = `${prevWidth + ratio}fr`;
- grid.width = `${_w}fr`;
- },
- /**
- * 处理右移且不是最后一个格子
- * @param {object} row 行数据
- * @param {number} j 第几列
- * @param {number} offsetX x 轴偏移量
- * @param {number} min_width 最小宽度
- * @param {number} row_width 行宽度
- */
- handleRightMoveNotLastGrid(row, j, offsetX, min_width, row_width) {
- let nextGrid = row.width_list[j + 1];
- const nextWidth = Number(nextGrid.replace('fr', ''));
- const width = Number(row.width_list[j].replace('fr', ''));
- const max = nextWidth + width - 10;
- if (nextWidth - offsetX < 10 || nextWidth - offsetX > max || width + offsetX > max || width + offsetX < 10) {
- return;
- }
- const ratio = (offsetX / document.querySelector('.row').offsetWidth) * 100;
- const _w = width + ratio;
- if ((_w / 100) * row_width < min_width) {
- return;
- }
- row.width_list[j + 1] = `${nextWidth - ratio}fr`;
- row.width_list[j] = `${width + ratio}fr`;
- },
- /**
- * 处理一行中有多个格子的右移且不是最后一个格子
- * @param {object} gridList 格子列表
- * @param {object} grid 格子数据
- * @param {object} col 列数据
- * @param {number} find 当前 id 所在格子索引
- * @param {number} k 格子的索引
- * @param {number} offsetX x 轴偏移量
- * @param {number} min_width 最小宽度
- */
- handleMultGridRightMoveNotFirstGrid({ gridList, grid, col, find, k, offsetX, min_width, row_width }) {
- let nextGrid = gridList[find + 1];
- const nextWidth = Number(nextGrid.width.replace('fr', ''));
- const width = Number(grid.width.replace('fr', ''));
- const max = nextWidth + width - 10;
- if (nextWidth - offsetX < 10 || nextWidth - offsetX > max || width + offsetX > max || width + offsetX < 10) {
- return;
- }
- const ratio = (offsetX / document.querySelector('.row').offsetWidth) * 100;
- const _w = width + ratio;
- if ((_w / 100) * row_width < min_width) {
- return;
- }
- col.grid_list[k + 1].width = `${nextWidth - ratio}fr`;
- grid.width = `${width + ratio}fr`;
- },
- /**
- * 重新计算格子宽度
- * @param {number} i 行
- * @param {number} j 列
- */
- recalculateGridWidth(i, j) {
- let col = this.data.row_list[i].col_list[j];
- let grid_template_columns = '0';
- col.grid_list.forEach(({ width }, i) => {
- const w = `${width}`;
- if (i === col.grid_list.length - 1) {
- grid_template_columns += ` ${w} 0`;
- } else {
- grid_template_columns += ` ${w} `;
- }
- });
- col.grid_template_columns = grid_template_columns;
- },
- /**
- * 删除组件
- * @param {number} i 行
- * @param {number} j 列
- * @param {number} k 格子
- */
- deleteComponent(i, j, k) {
- return () => {
- const gridList = this.data.row_list[i].col_list[j].grid_list;
- let delRow = gridList[k].row; // 删除的 grid 的 row
- let delW = gridList[k].width; // 删除的 grid 的 width
- gridList.splice(k, 1);
- // 如果删除后没有 grid 了则删除列
- const colList = this.data.row_list[i].col_list[j];
- if (colList.grid_list.length === 0) {
- this.data.row_list[i].col_list.splice(j, 1);
- let width_list = this.data.row_list[i].width_list;
- const delW = width_list[j];
- width_list.splice(j, 1);
- this.data.row_list[i].width_list = width_list.map((item) => {
- return `${Number(item.replace('fr', '')) + Number(delW.replace('fr', '') / width_list.length)}fr`;
- });
- }
- // 如果删除后没有列了则删除行
- if (this.data.row_list[i].col_list.length === 0) {
- this.data.row_list.splice(i, 1);
- }
- // 如果删除后还有 grid 则重新计算 grid 的 row 和 width
- if (gridList?.length > 0) {
- let delNum = gridList.filter(({ row }) => row === delRow).length;
- let diff = Number(delW.replace('fr', '')) / delNum;
- if (delNum === 0) {
- // 删除 grid 后面的 row 都减 1
- gridList.forEach((item) => {
- if (item.row > delRow) {
- item.row -= 1;
- }
- });
- } else {
- gridList.forEach((item) => {
- if (item.row === delRow) {
- item.width = `${Number(item.width.replace('fr', '')) + diff}fr`;
- }
- });
- }
- }
- };
- },
- computedColStyle(col) {
- let grid = col.grid_list;
- let maxCol = 0; // 最大列数
- let rowList = new Map();
- grid.forEach(({ row }) => {
- rowList.set(row, (rowList.get(row) || 0) + 1);
- });
- let curMaxRow = 0; // 当前列数最多的 row 的值
- rowList.forEach((value, key) => {
- if (value > maxCol) {
- maxCol = value;
- curMaxRow = key;
- }
- });
- // 计算 grid_template_areas
- let gridStr = '';
- let gridArr = [];
- let gridRowArr = []; // 存储不同 row 中间的 line
- grid.forEach(({ grid_area, row }, i) => {
- // 如果 gridArr[row - 1] 不存在则创建
- if (!gridArr[row - 1]) {
- gridArr[row - 1] = [];
- }
- if (row > 1 && grid[i - 1].row !== row) {
- gridRowArr.push({
- row: row - 1,
- str: `middle-${grid_area} `.repeat(maxCol * 3),
- });
- }
- // 如果当前 row 是最大列数的 row
- if (curMaxRow === row) {
- gridArr[row - 1].push(`left-${grid_area} ${grid_area} right-${grid_area}`);
- } else {
- let filter = grid.filter((item) => item.row === row);
- let find = filter.findIndex((item) => item.grid_area === grid_area);
- let needNum = (maxCol - filter.length) * 3; // 需要的数量
- let str = '';
- if (filter.length === 1) {
- str = ` ${grid_area} `.repeat(needNum + 1);
- } else {
- let arr = this.splitInteger(needNum, filter.length);
- str = arr[find] === 0 ? ` ${grid_area} ` : ` ${grid_area} `.repeat(arr[find] + 1);
- }
- gridArr[row - 1].push(`left-${grid_area} ${str} right-${grid_area}`);
- }
- });
- gridArr.forEach((item, i) => {
- let find = gridRowArr.find((row) => row.row === i);
- if (find) {
- gridStr += `'${find.str}' `;
- }
- gridStr += `'${item.join(' ')}' `;
- });
- // 计算 grid_template_columns
- let gridTemCols = '';
- let max = { row: 0, num: 0 };
- grid.forEach(({ row }) => {
- // 计算出 row 的哪个值最多
- let len = grid.filter((item) => item.row === row).length;
- if (max.num < len) {
- max.num = len;
- max.row = row;
- }
- });
- grid.forEach((item) => {
- if (item.row === max.row) {
- gridTemCols += `${item.width} 4px 4px `;
- }
- });
- // 计算 grid_template_rows
- let gridTemplateRows = '';
- // 将 grid 按照 row 分组
- let gridMap = new Map();
- grid.forEach((item) => {
- if (!gridMap.has(item.row)) {
- gridMap.set(item.row, []);
- }
- gridMap.get(item.row).push(item.height);
- });
- gridMap.forEach((value, i) => {
- if (i > 1) {
- gridTemplateRows += '4px ';
- }
- if (value.length === 1) {
- gridTemplateRows += `${value[0]} `;
- } else {
- let isAllAuto = value.every((item) => item === 'auto'); // 是否全是 auto
- gridTemplateRows += isAllAuto ? 'auto ' : `max(${value.join(', ')}) `;
- }
- });
- return {
- width: col.width,
- gridTemplateAreas: `'${'grid-top '.repeat(maxCol * 3)}' ${gridStr} '${'grid-bottom '.repeat(maxCol * 3)}'`,
- gridTemplateColumns: `0 ${gridTemCols.slice(0, gridTemCols.length - 8)} 0`,
- gridTemplateRows: `0 ${gridTemplateRows} 0`,
- };
- },
- /**
- * 分割整数为多个 3 的倍数
- * @param {number} num
- * @param {number} parts
- */
- splitInteger(num, parts) {
- let base = Math.floor(num / parts / 3) * 3;
- let arr = Array(parts).fill(base);
- let remainder = num - base * parts;
- for (let i = 0; remainder > 0; i = (i + 1) % parts) {
- arr[i] += 3;
- remainder -= 3;
- }
- return arr;
- },
- /**
- * 拖拽开始
- * 用点击模拟拖拽
- * @param {MouseEvent} event
- * @param {string} type
- */
- dragStart(event, type) {
- // 获取鼠标位置
- const { clientX, clientY } = event;
- document.body.style.userSelect = 'none'; // 禁止选中文本
- this.drag.dragging = true;
- this.curType = type;
- // 在鼠标位置创建一个拖拽元素
- const dragging = document.createElement('div');
- dragging.className = 'canvas-dragging';
- this.drag.clientX = clientX;
- this.drag.clientY = clientY;
- document.body.appendChild(dragging);
- },
- /**
- * 鼠标移动
- */
- dragMove(event) {
- if (!this.drag.dragging) return;
- const { clientX, clientY } = event;
- this.drag.clientX = clientX;
- this.drag.clientY = clientY;
- if (!this.isEdit) return; // 非编辑状态不允许显隐线
- let { isInsideCanvas } = this.getMarginDifferences();
- this.enterCanvas = isInsideCanvas;
- if (!isInsideCanvas) return;
- this.showRecentLine(clientX, clientY);
- },
- /**
- * 显示最近的线
- * @param {number} clientX
- * @param {number} clientY
- */
- showRecentLine(clientX, clientY) {
- const dragLineList = document.querySelectorAll('.drag-line'); // 获取所有的横线
- const dragVerticalLineList = document.querySelectorAll('.drag-vertical-line'); // 获取所有的竖线
- let minDistance = Infinity;
- let minIndex = -1;
- const list = [...dragLineList, ...dragVerticalLineList];
- list.forEach((item, index) => {
- const rect = item.getBoundingClientRect();
- const distance = Math.sqrt(
- Math.pow(clientX - rect.left - rect.width / 2, 2) + Math.pow(clientY - rect.top - rect.height / 2, 2),
- );
- if (distance < minDistance) {
- minDistance = distance;
- minIndex = index;
- }
- });
- list.forEach((item, index) => {
- if (index === minIndex) {
- this.curRow = Number(item.getAttribute('data-row'));
- this.curCol = Number(item.getAttribute('data-col') || -1);
- this.curGrid = Number(item.getAttribute('data-grid') || -1);
- this.gridInsertType = item.getAttribute('data-type') || '';
- item.style.opacity = 1;
- } else {
- item.style.opacity = 0;
- }
- });
- },
- /**
- * 鼠标松开
- */
- dragEnd() {
- document.body.style.userSelect = 'auto';
- const dragging = document.querySelector('.canvas-dragging');
- if (dragging) {
- document.body.removeChild(dragging);
- this.drag.dragging = false;
- }
- if (!this.isEdit) return;
- if (this.enterCanvas) {
- if (this.curRow >= -1 && this.curCol <= -1) {
- this.calculateRowInsertedObject();
- }
- if (this.curRow >= -1 && this.curCol > -1 && this.curGrid <= -1) {
- this.calculateColObject();
- }
- if (this.curRow >= -1 && this.curCol > -1 && this.curGrid > -1) {
- this.calculateGridObject();
- }
- }
- this.enterCanvas = false;
- },
- computedRowStyle(i) {
- let row = this.data.row_list[i];
- let col = row.col_list;
- if (col.length <= 1) {
- return {
- gridTemplateColumns: '0 100fr 0',
- };
- }
- let str = row.width_list
- .map((item) => {
- return `${item}`;
- })
- .join(' 6px ');
- let gridTemplateColumns = `0 ${str} 0`;
- return {
- gridAutoFlow: 'column',
- gridTemplateColumns,
- gridTemplateRows: 'auto',
- };
- },
- /**
- * 计算网格插入的对象
- */
- calculateGridObject() {
- const id = `ID-${getRandomNumber(12, true)}`;
- const letter = `L${getRandomNumber(6, true)}`;
- let row = this.data.row_list[this.curRow];
- let col = row.col_list[this.curCol];
- let grid = col.grid_list;
- let type = this.gridInsertType;
- if (['row', 'col-middle'].includes(type)) {
- let rowNum = this.curGrid === 0 ? 1 : grid[this.curGrid - 1].row + 1;
- grid.splice(this.curGrid, 0, {
- id,
- grid_area: letter,
- width: '100fr',
- height: 'auto',
- row: rowNum,
- type: this.curType,
- });
- // 在新加入的 grid 后面的 row 都加 1
- grid.forEach((item, i) => {
- if (i > this.curGrid) {
- item.row += 1;
- }
- });
- }
- if (['col-left', 'col-right'].includes(type)) {
- let rowNum = grid[type === 'col-left' ? this.curGrid : this.curGrid - 1].row;
- grid.splice(this.curGrid, 0, {
- id,
- grid_area: letter,
- width: '100fr',
- height: 'auto',
- row: rowNum,
- type: this.curType,
- });
- let allRowNum = grid.filter(({ row }) => row === rowNum).length;
- let w = 0;
- grid.forEach((item, i) => {
- if (item.row === rowNum && i !== this.curGrid) {
- let width = Number(item.width.replace('fr', ''));
- let diff = width / allRowNum;
- item.width = `${width - diff}fr`;
- w += diff;
- }
- });
- grid[this.curGrid].width = `${w}fr`;
- }
- },
- /**
- * 计算列插入的对象
- */
- calculateColObject() {
- const id = `ID-${getRandomNumber(12, true)}`;
- const letter = `L${getRandomNumber(6, true)}`;
- let row = this.data.row_list[this.curRow];
- let col = row.col_list;
- let w = 0;
- row.width_list.forEach((item, i) => {
- let itemW = Number(item.replace('fr', ''));
- let rowW = itemW / (row.width_list.length + 1);
- w += rowW;
- row.width_list[i] = `${itemW - rowW}fr`;
- });
- row.width_list.splice(this.curCol, 0, `${w}fr`);
- col.splice(this.curCol, 0, {
- width: '100fr',
- height: 'auto',
- grid_list: [
- {
- id,
- grid_area: letter,
- row: 1,
- width: '100fr',
- height: 'auto',
- type: this.curType,
- },
- ],
- });
- },
- /**
- * 计算行插入的对象
- */
- calculateRowInsertedObject() {
- const id = `ID-${getRandomNumber(12, true)}`;
- const letter = `L${getRandomNumber(6, true)}`;
- const row_id = `R${getRandomNumber(6, true)}`;
- this.data.row_list.splice(this.curRow + 1, 0, {
- width_list: ['100fr'],
- row_id,
- col_list: [
- {
- width: '100fr',
- height: 'auto',
- grid_list: [
- {
- id,
- grid_area: letter,
- width: '100fr',
- height: 'auto',
- row: 1,
- type: this.curType,
- },
- ],
- },
- ],
- });
- },
- /**
- * 获取拖拽元素和画布的边距差值
- * @returns {object} { leftMarginDifference, topMarginDifference, isInsideCanvas }
- * leftMarginDifference: 拖拽元素和画布左边距差值
- * topMarginDifference: 拖拽元素和画布上边距差值
- * isInsideCanvas: 是否在画布内
- */
- getMarginDifferences() {
- const rect1 = document.querySelector('.canvas-dragging').getBoundingClientRect();
- const rect2 = this.$refs.canvas.getBoundingClientRect();
- const leftMarginDifference = rect1.left - rect2.left + 128;
- const topMarginDifference = rect1.top - rect2.top + 72;
- let isInsideCanvas =
- leftMarginDifference > 0 &&
- leftMarginDifference < rect2.width &&
- topMarginDifference > 0 &&
- topMarginDifference < rect2.height;
- return { leftMarginDifference, topMarginDifference, isInsideCanvas };
- },
- // 获取子组件
- findChildComponentByKey(key) {
- return this.$refs.component.find((child) => child.$vnode.key === key);
- },
- /**
- * 计算分组线样式
- * @param {Array} rowIdList 行 ID 列表
- * @returns {Object} 样式对象
- */
- computedGroupLine(rowIdList) {
- // 获取画布顶部位置
- const canvas = this.$refs.canvas;
- const firstCheckbox = this.$el.querySelector(`.row-checkbox.${rowIdList[0]}`);
- const secCheckbox = this.$el.querySelector(`.row-checkbox.${rowIdList[1]}`);
- // DOM 未渲染,返回默认样式或空对象
- if (!canvas || !firstCheckbox || !secCheckbox) {
- return {};
- }
- const canvasTop = canvas.getBoundingClientRect().top;
- const firstRowTop = firstCheckbox.getBoundingClientRect().top;
- const secRowTop = secCheckbox.getBoundingClientRect().top;
- return {
- top: `${firstRowTop - canvasTop + 22}px`,
- height: `${secRowTop - firstRowTop - 24}px`,
- };
- },
- computedBorderColor(rowId) {
- const groupList = [];
- this.content_group_row_list.forEach(({ row_id, is_pre_same_group }) => {
- if (is_pre_same_group && groupList.length) {
- groupList[groupList.length - 1].push(row_id);
- } else {
- groupList.push([row_id]);
- }
- });
- const index = groupList.findIndex((g) => g.includes(rowId));
- return this.gridBorderColorList[index % this.gridBorderColorList.length];
- },
- /**
- * 计算网格样式
- * @param {Object} grid 网格对象
- * @returns {Object} 样式对象
- */
- computedGridStyle(grid) {
- let marginTop = grid.row === 1 ? '0' : '6px';
- return {
- gridArea: grid.grid_area,
- height: grid.height,
- marginTop,
- };
- },
- },
- };
- </script>
- <style lang="scss" scoped>
- .canvas {
- position: relative;
- display: flex;
- flex-direction: column;
- row-gap: 8px;
- width: $courseware-width;
- min-height: calc(100% - 6px);
- padding: 24px;
- margin: 0 auto;
- background-color: #fff;
- background-repeat: no-repeat;
- border-radius: 4px;
- .group-line {
- position: absolute;
- left: 11px;
- width: 1px;
- background-color: #165dff;
- }
- .row {
- display: grid;
- row-gap: 16px;
- .row-checkbox {
- position: absolute;
- left: 4px;
- }
- > .drag-vertical-line:not(:first-child, :last-child, .grid-line) {
- left: 6px;
- }
- .drag-vertical-line.col-start {
- left: -12px;
- }
- .drag-vertical-line.col-end {
- right: -8px;
- }
- .col {
- display: grid;
- .drag-vertical-line:first-child {
- left: -8px;
- }
- .drag-vertical-line:not(:first-child, :last-child, .grid-line) {
- left: 6px;
- }
- .drag-vertical-line:last-child {
- right: -4px;
- }
- }
- }
- .drag-line {
- z-index: 2;
- width: calc(100% - 16px);
- height: 4px;
- margin: 0 8px;
- background-color: #379fff;
- border-radius: 4px;
- opacity: 0;
- &.drag-row {
- background-color: $right-color;
- }
- &.grid-line:not(:first-child, :last-child) {
- position: relative;
- top: 6px;
- }
- &.grid-line {
- background-color: #f43;
- }
- }
- .drag-vertical-line {
- position: relative;
- z-index: 2;
- width: 4px;
- height: 100%;
- background-color: #379fff;
- border-radius: 4px;
- opacity: 0;
- &.grid-line {
- background-color: #f43;
- }
- }
- }
- </style>
- <style lang="scss">
- .canvas-dragging {
- position: fixed;
- z-index: 999;
- width: 320px;
- height: 180px;
- background-color: #eaf5ff;
- border: 1px solid #b5dbff;
- border-radius: 4px;
- opacity: 0.5;
- transform: translate(-40%, -40%);
- }
- </style>
|