diff --git a/packages/editor/src/utils/editor.ts b/packages/editor/src/utils/editor.ts index 5110b753..00444304 100644 --- a/packages/editor/src/utils/editor.ts +++ b/packages/editor/src/utils/editor.ts @@ -324,11 +324,14 @@ export const fixNodePosition = (config: MNode, parent: MContainer, stage: StageC }; // 序列化配置 +// 仅去掉对象 key 的双引号;字符串值内的 "xxx": 不应被误处理 +// serialize-javascript 在 space: 2 时,每个 key 都会出现在换行 + 空白缩进之后, +// 因此通过 (^|\n)\s* 锚定行首缩进,避免匹配到字符串值中的 \"xxx\": export const serializeConfig = (config: any) => serialize(config, { space: 2, unsafe: true, - }).replace(/"(\w+)":\s/g, '$1: '); + }).replace(/(^|\n)(\s*)"(\w+)":\s/g, '$1$2$3: '); export const moveItemsInContainer = (sourceIndices: number[], parent: MContainer, targetIndex: number) => { sourceIndices.sort((a, b) => a - b); diff --git a/packages/editor/tests/unit/utils/editor.spec.ts b/packages/editor/tests/unit/utils/editor.spec.ts index 1f313810..733fe6ba 100644 --- a/packages/editor/tests/unit/utils/editor.spec.ts +++ b/packages/editor/tests/unit/utils/editor.spec.ts @@ -1,3 +1,4 @@ +/* eslint-disable prettier/prettier */ /* * Tencent is pleased to support the open source community by making TMagicEditor available. * @@ -1046,6 +1047,53 @@ describe('补充:fixNodeLeft / fixNodePosition / serializeConfig', () => { const out = editor.serializeConfig({ a: 1 }); expect(out).toContain('a:'); }); + + test('serializeConfig - 输出去掉了 key 引号', () => { + const out = editor.serializeConfig({ a: { b: 1 }}); + expect(out).toContain('a:'); + expect(out).toContain('b: 1'); + }); + + test('serializeConfig - value中包含"x"', () => { + const out = editor.serializeConfig({ a: '"a": 1' }); + expect(out).toContain('\\"a\\":'); + }); + + test('serializeConfig - value中包含"x"', () => { + const out = editor.serializeConfig({ a: { b: '"a": 1' } }); + expect(out).toContain('\\"a\\":'); + expect(out).toContain('b: '); + }); + + test('serializeConfig - function', () => { + const out = editor.serializeConfig({ + a: () => { + const b = "b"; + switch (b) { + // @ts-ignore + case "a": + return 1; + } + }, + }); + expect(out).toContain('"a":'); + }); + + test('serializeConfig - function', () => { + const out = editor.serializeConfig({ + a: { + b: () => { + const b = "b"; + switch (b) { + // @ts-ignore + case "a": return 1; + } + } + }, + }); + expect(out).toContain('"a":'); + expect(out).toContain('b: '); + }); }); describe('补充:isIncludeDataSource', () => {