feat(editor,dep): 支持复制组件时将组件绑定的数据源一并复制

This commit is contained in:
parisma 2024-05-27 17:44:33 +08:00 committed by roymondchen
parent 2ea876a2a0
commit faabf1bb3a
12 changed files with 245 additions and 30 deletions

View File

@ -15,6 +15,10 @@ export enum DepTargetType {
DATA_SOURCE_COND = 'data-source-cond',
/** 复制组件时关联的组件 */
RELATED_COMP_WHEN_COPY = 'related-comp-when-copy',
/** 复制组件时关联的代码块 */
RELATED_CODE_WHEN_COPY = 'related-code-when-copy',
/** 复制组件时关联的数据源 */
RELATED_DS_WHEN_COPY = 'related-ds-when-copy',
}
export type IsTarget = (key: string | number, value: any) => boolean;

View File

@ -32,10 +32,10 @@ export const createCodeBlockTarget = (id: Id, codeBlock: CodeBlockContent, initi
},
});
export const createRelatedCompTarget = (options: CustomTargetOptions) =>
export const createRelatedTargetForCopy = (options: CustomTargetOptions, type: DepTargetType) =>
new Target({
id: DepTargetType.RELATED_COMP_WHEN_COPY,
type: DepTargetType.RELATED_COMP_WHEN_COPY,
id: type,
type,
...options,
});

View File

@ -70,8 +70,12 @@ export interface EditorProps {
codeOptions?: { [key: string]: any };
/** 禁用鼠标左键按下时就开始拖拽,需要先选中再可以拖拽 */
disabledDragStart?: boolean;
/** 自定义依赖收集器,复制组件时会将关联依赖一并复制 */
/** 自定义依赖收集器,复制组件时会将关联组件一并复制 */
collectorOptions?: CustomTargetOptions;
/** 自定义依赖收集器,复制组件时会将关联代码块一并复制 */
collectorOptionsForCode?: CustomTargetOptions;
/** 自定义依赖收集器,复制组件时会将关联数据源一并复制 */
collectorOptionsForDataSource?: CustomTargetOptions;
/** 标尺配置 */
guidesOptions?: Partial<GuidesOptions>;
/** 禁止多选 */

View File

@ -67,8 +67,6 @@ export const useCodeBlockEdit = (codeBlockService?: CodeBlockService) => {
await codeBlockService?.setCodeDslById(codeId.value, values);
tMagicMessage.success('代码块保存成功');
codeBlockEditor.value?.hide();
};

View File

@ -7,7 +7,7 @@ import {
createDataSourceCondTarget,
createDataSourceMethodTarget,
createDataSourceTarget,
createRelatedCompTarget,
createRelatedTargetForCopy,
DepTargetType,
Target,
} from '@tmagic/dep';
@ -412,7 +412,17 @@ export const initServiceEvents = (
// 初始化复制组件相关的依赖收集器
if (props.collectorOptions && !depService.hasTarget(DepTargetType.RELATED_COMP_WHEN_COPY)) {
depService.addTarget(createRelatedCompTarget(props.collectorOptions));
depService.addTarget(createRelatedTargetForCopy(props.collectorOptions, DepTargetType.RELATED_COMP_WHEN_COPY));
}
if (props.collectorOptionsForCode && !depService.hasTarget(DepTargetType.RELATED_CODE_WHEN_COPY)) {
depService.addTarget(
createRelatedTargetForCopy(props.collectorOptionsForCode, DepTargetType.RELATED_CODE_WHEN_COPY),
);
}
if (props.collectorOptionsForDataSource && !depService.hasTarget(DepTargetType.RELATED_DS_WHEN_COPY)) {
depService.addTarget(
createRelatedTargetForCopy(props.collectorOptionsForDataSource, DepTargetType.RELATED_DS_WHEN_COPY),
);
}
onBeforeUnmount(() => {

View File

@ -17,21 +17,26 @@
*/
import { reactive } from 'vue';
import { keys, pick } from 'lodash-es';
import { cloneDeep, get, keys, pick } from 'lodash-es';
import type { Writable } from 'type-fest';
import { DepTargetType } from '@tmagic/dep';
import type { ColumnConfig } from '@tmagic/form';
import type { CodeBlockContent, CodeBlockDSL, Id } from '@tmagic/schema';
import type { CodeBlockContent, CodeBlockDSL, Id, MNode } from '@tmagic/schema';
import depService from '@editor/services/dep';
import editorService from '@editor/services/editor';
import storageService, { Protocol } from '@editor/services/storage';
import type { AsyncHookPlugin, CodeState } from '@editor/type';
import { CODE_DRAFT_STORAGE_KEY } from '@editor/type';
import { getConfig } from '@editor/utils/config';
import { COPY_CODE_STORAGE_KEY } from '@editor/utils/editor';
import BaseService from './BaseService';
const canUsePluginMethods = {
async: ['setCodeDslById', 'setEditStatus', 'setCombineIds', 'setUndeleteableList', 'deleteCodeDslByIds'] as const,
sync: [],
sync: ['setCodeDslByIdSync'],
};
type AsyncMethodName = Writable<(typeof canUsePluginMethods)['async']>;
@ -46,7 +51,10 @@ class CodeBlock extends BaseService {
});
constructor() {
super(canUsePluginMethods.async.map((methodName) => ({ name: methodName, isAsync: true })));
super([
...canUsePluginMethods.async.map((methodName) => ({ name: methodName, isAsync: true })),
...canUsePluginMethods.sync.map((methodName) => ({ name: methodName, isAsync: false })),
]);
}
/**
@ -88,20 +96,32 @@ class CodeBlock extends BaseService {
* @returns {void}
*/
public async setCodeDslById(id: Id, codeConfig: Partial<CodeBlockContent>): Promise<void> {
this.setCodeDslByIdSync(id, codeConfig, true);
}
/**
*
* ID和代码内容到源dsl
* @param {Id} id id
* @param {CodeBlockContent} codeConfig
* @param {boolean} force true
* @returns {void}
*/
public setCodeDslByIdSync(id: Id, codeConfig: Partial<CodeBlockContent>, force = true): void {
const codeDsl = this.getCodeDsl();
if (!codeDsl) {
throw new Error('dsl中没有codeBlocks');
}
if (codeDsl[id] && !force) return;
const codeConfigProcessed = codeConfig;
if (codeConfig.content) {
const codeConfigProcessed = cloneDeep(codeConfig);
if (codeConfigProcessed.content) {
// 在保存的时候转换代码内容
const parseDSL = getConfig('parseDSL');
if (typeof codeConfig.content === 'string') {
codeConfig.content = parseDSL<(...args: any[]) => any>(codeConfig.content);
if (typeof codeConfigProcessed.content === 'string') {
codeConfigProcessed.content = parseDSL<(...args: any[]) => any>(codeConfigProcessed.content);
}
codeConfigProcessed.content = codeConfig.content;
}
const existContent = codeDsl[id] || {};
@ -233,6 +253,54 @@ class CodeBlock extends BaseService {
return await this.getUniqueId();
}
/**
*
* @param config
* @returns
*/
public copyWithRelated(config: MNode | MNode[]): void {
const copyNodes: MNode[] = Array.isArray(config) ? config : [config];
// 关联的代码块也一并复制
depService.clearByType(DepTargetType.RELATED_CODE_WHEN_COPY);
depService.collect(copyNodes, true, DepTargetType.RELATED_CODE_WHEN_COPY);
const customTarget = depService.getTarget(
DepTargetType.RELATED_CODE_WHEN_COPY,
DepTargetType.RELATED_CODE_WHEN_COPY,
);
const copyData: CodeBlockDSL = {};
if (customTarget) {
Object.keys(customTarget.deps).forEach((nodeId: Id) => {
const node = editorService.getNodeById(nodeId);
if (!node) return;
customTarget!.deps[nodeId].keys.forEach((key) => {
const relateCodeId = get(node, key);
const isExist = Object.keys(copyData).find((codeId: Id) => codeId === relateCodeId);
if (!isExist) {
const relateCode = this.getCodeContentById(relateCodeId);
if (relateCode) {
copyData[relateCodeId] = relateCode;
}
}
});
});
}
storageService.setItem(COPY_CODE_STORAGE_KEY, copyData, {
protocol: Protocol.OBJECT,
});
}
/**
*
* @returns
*/
public paste() {
const codeDsl: CodeBlockDSL = storageService.getItem(COPY_CODE_STORAGE_KEY);
Object.keys(codeDsl).forEach((codeId: Id) => {
// 不覆盖同样id的代码块
this.setCodeDslByIdSync(codeId, codeDsl[codeId], false);
});
}
public resetState() {
this.state.codeDsl = null;
this.state.editable = true;

View File

@ -1,14 +1,19 @@
import { reactive } from 'vue';
import { cloneDeep } from 'lodash-es';
import { cloneDeep, get } from 'lodash-es';
import { Writable } from 'type-fest';
import type { EventOption } from '@tmagic/core';
import { DepTargetType } from '@tmagic/dep';
import type { FormConfig } from '@tmagic/form';
import type { DataSourceSchema } from '@tmagic/schema';
import type { DataSourceSchema, Id, MNode } from '@tmagic/schema';
import { guid, toLine } from '@tmagic/utils';
import depService from '@editor/services/dep';
import editorService from '@editor/services/editor';
import storageService, { Protocol } from '@editor/services/storage';
import type { DatasourceTypeOption, SyncHookPlugin } from '@editor/type';
import { getFormConfig, getFormValue } from '@editor/utils/data-source';
import { COPY_DS_STORAGE_KEY } from '@editor/utils/editor';
import BaseService from './BaseService';
@ -102,7 +107,7 @@ class DataSource extends BaseService {
public add(config: DataSourceSchema) {
const newConfig = {
...config,
id: this.createId(),
id: config.id && !this.getDataSourceById(config.id) ? config.id : this.createId(),
};
this.get('dataSources').push(newConfig);
@ -116,7 +121,6 @@ class DataSource extends BaseService {
const dataSources = this.get('dataSources');
const index = dataSources.findIndex((ds) => ds.id === config.id);
dataSources[index] = cloneDeep(config);
this.emit('update', config);
@ -153,6 +157,51 @@ class DataSource extends BaseService {
public usePlugin(options: SyncHookPlugin<SyncMethodName, DataSource>): void {
super.usePlugin(options);
}
/**
*
* @param config
* @returns
*/
public copyWithRelated(config: MNode | MNode[]): void {
const copyNodes: MNode[] = Array.isArray(config) ? config : [config];
depService.clearByType(DepTargetType.RELATED_DS_WHEN_COPY);
depService.collect(copyNodes, true, DepTargetType.RELATED_DS_WHEN_COPY);
const customTarget = depService.getTarget(DepTargetType.RELATED_DS_WHEN_COPY, DepTargetType.RELATED_DS_WHEN_COPY);
const copyData: DataSourceSchema[] = [];
if (customTarget) {
Object.keys(customTarget.deps).forEach((nodeId: Id) => {
const node = editorService.getNodeById(nodeId);
if (!node) return;
customTarget!.deps[nodeId].keys.forEach((key) => {
const [relateDsId] = get(node, key);
const isExist = copyData.find((dsItem) => dsItem.id === relateDsId);
if (!isExist) {
const relateDs = this.getDataSourceById(relateDsId);
if (relateDs) {
copyData.push(relateDs);
}
}
});
});
}
storageService.setItem(COPY_DS_STORAGE_KEY, copyData, {
protocol: Protocol.OBJECT,
});
}
/**
*
* @returns
*/
public paste() {
const dataSource: DataSourceSchema[] = storageService.getItem(COPY_DS_STORAGE_KEY);
dataSource.forEach((item: DataSourceSchema) => {
// 不覆盖同样id的数据源
if (!this.getDataSourceById(item.id)) {
this.add(item);
}
});
}
}
export type DataSourceService = DataSource;

View File

@ -23,7 +23,7 @@ import { Writable } from 'type-fest';
import { DepTargetType } from '@tmagic/dep';
import type { FormConfig } from '@tmagic/form';
import type { Id, MComponent, MNode } from '@tmagic/schema';
import { getValueByKeyPath, guid, setValueByKeyPath, toLine } from '@tmagic/utils';
import { getNodePath, getValueByKeyPath, guid, setValueByKeyPath, toLine } from '@tmagic/utils';
import depService from '@editor/services/dep';
import editorService from '@editor/services/editor';
@ -199,13 +199,14 @@ class Props extends BaseService {
public replaceRelateId(originConfigs: MNode[], targetConfigs: MNode[]) {
const relateIdMap = this.getRelateIdMap();
if (Object.keys(relateIdMap).length === 0) return;
depService.clearByType(DepTargetType.RELATED_COMP_WHEN_COPY);
depService.collect(originConfigs, true, DepTargetType.RELATED_COMP_WHEN_COPY);
const target = depService.getTarget(DepTargetType.RELATED_COMP_WHEN_COPY, DepTargetType.RELATED_COMP_WHEN_COPY);
if (!target) return;
originConfigs.forEach((config: MNode) => {
const newId = relateIdMap[config.id];
const targetConfig = targetConfigs.find((targetConfig) => targetConfig.id === newId);
const path = getNodePath(newId, targetConfigs);
const targetConfig = path[path.length - 1];
if (!targetConfig) return;
@ -213,9 +214,13 @@ class Props extends BaseService {
const relateOriginId = getValueByKeyPath(fullKey, config);
const relateTargetId = relateIdMap[relateOriginId];
if (!relateTargetId) return;
setValueByKeyPath(fullKey, relateTargetId, targetConfig);
});
// 递归items
if (config.items && Array.isArray(config.items)) {
this.replaceRelateId(config.items, targetConfigs);
}
});
}

View File

@ -25,6 +25,8 @@ import { calcValueByFontsize, getNodePath, isNumber, isPage, isPageFragment, isP
import { Layout } from '@editor/type';
export const COPY_STORAGE_KEY = '$MagicEditorCopyData';
export const COPY_CODE_STORAGE_KEY = '$MagicEditorCopyCode';
export const COPY_DS_STORAGE_KEY = '$MagicEditorCopyDataSource';
/**
*

View File

@ -23,12 +23,14 @@
"@tmagic/stage": "1.4.5",
"@tmagic/utils": "1.4.5",
"element-plus": "^2.6.1",
"lodash-es": "^4.17.21",
"monaco-editor": "^0.48.0",
"serialize-javascript": "^6.0.0",
"vue": "^3.4.27",
"vue-router": "^4.0.10"
},
"devDependencies": {
"@types/lodash-es": "^4.17.4",
"@types/node": "^18.19.0",
"@types/serialize-javascript": "^5.0.1",
"@vitejs/plugin-legacy": "^5.4.0",

View File

@ -17,6 +17,9 @@
:moveable-options="moveableOptions"
:auto-scroll-into-view="true"
:stage-rect="stageRect"
:collector-options="collectorOptions"
:layerContentMenu="contentMenuData"
:stageContentMenu="contentMenuData"
@props-submit-error="propsSubmitErrorHandler"
>
<template #workspace-content>
@ -38,17 +41,29 @@
</template>
<script lang="ts" setup>
import { computed, nextTick, onBeforeUnmount, ref, toRaw } from 'vue';
import { computed, markRaw, nextTick, onBeforeUnmount, Ref, ref, toRaw } from 'vue';
import { useRouter } from 'vue-router';
import { Coin, Connection, Document } from '@element-plus/icons-vue';
import { Coin, Connection, CopyDocument, Document, DocumentCopy } from '@element-plus/icons-vue';
import { cloneDeep } from 'lodash-es';
import serialize from 'serialize-javascript';
import { TMagicDialog, tMagicMessage, tMagicMessageBox } from '@tmagic/design';
import { DatasourceTypeOption, editorService, MenuBarData, MoveableOptions, TMagicEditor } from '@tmagic/editor';
import {
ContentMenu,
COPY_STORAGE_KEY,
DatasourceTypeOption,
DepTargetType,
editorService,
MenuBarData,
MenuButton,
MoveableOptions,
Services,
TMagicEditor,
} from '@tmagic/editor';
import type { MContainer, MNode } from '@tmagic/schema';
import { NodeType } from '@tmagic/schema';
import type { CustomizeMoveableOptionsCallbackConfig } from '@tmagic/stage';
import { asyncLoadJs } from '@tmagic/utils';
import { asyncLoadJs, calcValueByFontsize } from '@tmagic/utils';
import DeviceGroup from '../components/DeviceGroup.vue';
import componentGroupList from '../configs/componentGroupList';
@ -86,6 +101,58 @@ const previewUrl = computed(
() => `${VITE_RUNTIME_PATH}/page/index.html?localPreview=1&page=${editor.value?.editorService.get('page')?.id}`,
);
const collectorOptions = {
name: '蒙层',
isTarget: (key: string | number, value: any) =>
typeof key === 'string' && typeof value === 'string' && key.includes('events') && value.startsWith('overlay_'),
autoCollect: false,
};
const usePasteMenu = (menu?: Ref<InstanceType<typeof ContentMenu> | undefined>): MenuButton => ({
type: 'button',
text: '粘贴(带关联信息)',
icon: markRaw(DocumentCopy),
display: (services) => !!services?.storageService?.getItem(COPY_STORAGE_KEY),
handler: (services) => {
const nodes = services?.editorService?.get('nodes');
if (!nodes || nodes.length === 0) return;
if (menu?.value?.$el) {
const stage = services?.editorService?.get('stage');
const rect = menu.value.$el.getBoundingClientRect();
const parentRect = stage?.container?.getBoundingClientRect();
const initialLeft =
calcValueByFontsize(stage?.renderer.getDocument(), (rect.left || 0) - (parentRect?.left || 0)) /
services.uiService.get('zoom');
const initialTop =
calcValueByFontsize(stage?.renderer.getDocument(), (rect.top || 0) - (parentRect?.top || 0)) /
services.uiService.get('zoom');
services?.editorService?.paste({ left: initialLeft, top: initialTop });
} else {
services?.editorService?.paste();
services?.codeBlockService?.paste();
services?.dataSourceService?.paste();
}
},
});
const contentMenuData = computed(() => [
{
type: 'button',
text: '复制(带关联信息)',
icon: markRaw(CopyDocument),
display: (services: Services) =>
services?.depService?.hasSpecifiedTypeTarget(DepTargetType.RELATED_COMP_WHEN_COPY) || false,
handler: (services: Services) => {
const nodes = services?.editorService?.get('nodes');
nodes && services?.editorService?.copyWithRelated(cloneDeep(nodes));
nodes && services?.codeBlockService?.copyWithRelated(cloneDeep(nodes));
nodes && services?.dataSourceService?.copyWithRelated(cloneDeep(nodes));
},
},
usePasteMenu(),
]);
const menu: MenuBarData = {
left: [
{

6
pnpm-lock.yaml generated
View File

@ -770,6 +770,9 @@ importers:
element-plus:
specifier: ^2.6.1
version: 2.6.1(@vue/composition-api@1.7.2(vue@3.4.27(typescript@5.4.2)))(vue@3.4.27(typescript@5.4.2))
lodash-es:
specifier: ^4.17.21
version: 4.17.21
monaco-editor:
specifier: ^0.48.0
version: 0.48.0
@ -783,6 +786,9 @@ importers:
specifier: ^4.0.10
version: 4.0.10(vue@3.4.27(typescript@5.4.2))
devDependencies:
'@types/lodash-es':
specifier: ^4.17.4
version: 4.17.7
'@types/node':
specifier: ^18.19.0
version: 18.19.3