feat(editor): 数据源字段选择支持数组下标与迭代器元素字段

迭代器子组件可同时选元素字段和下标,其余场景只保留固定下标;已选路径缺节点时补回选项,避免级联框空白。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
roymondchen 2026-12-01 16:03:06 +08:00
parent f81ec0100c
commit d068b7c1c4
5 changed files with 799 additions and 23 deletions

View File

@ -87,7 +87,7 @@
import { computed, inject, ref, watch } from 'vue';
import { Edit, View } from '@element-plus/icons-vue';
import type { DataSourceFieldType } from '@tmagic/core';
import type { DataSourceFieldType, DataSourceSchema } from '@tmagic/core';
import { getDesignConfig, TMagicButton, TMagicCascader, TMagicSelect, TMagicTooltip } from '@tmagic/design';
import { type FilterFunction, filterFunction, type FormState, type SelectOption } from '@tmagic/form';
import { DATA_SOURCE_FIELDS_SELECT_VALUE_PREFIX, removeDataSourceFieldPrefix } from '@tmagic/utils';
@ -95,7 +95,7 @@ import { DATA_SOURCE_FIELDS_SELECT_VALUE_PREFIX, removeDataSourceFieldPrefix } f
import MIcon from '@editor/components/Icon.vue';
import { useServices } from '@editor/hooks/use-services';
import { type EventBus, SideItemKey } from '@editor/type';
import { getCascaderOptionsFromFields } from '@editor/utils';
import { ensureSelectedArrayIndices, getCascaderOptionsFromFields, getDataSourceEditorData } from '@editor/utils';
const props = defineProps<{
/**
@ -122,7 +122,7 @@ const modelValue = defineModel<string[] | any>('modelValue', { default: () => []
const optionComponent = getDesignConfig('components')?.option;
const { dataSourceService, uiService } = useServices();
const { dataSourceService, uiService, editorService } = useServices();
const mForm = inject<FormState | undefined>('mForm');
const eventBus = inject<EventBus | null>('eventBus', null);
@ -173,21 +173,80 @@ watch(
},
);
/**
* 与 core `App.iteratorContainerType` 一致:默认包含 `iterator-container`,并包含业务追加的自定义类型。
* runtime 还没就绪时只能识别默认类型。stage 是 markRaw,runtime 晚到不会让 computed 重算,
* 所以在 runtime-ready 时把类型集合写进 ref。
*/
const iteratorContainerTypes = ref<{ has(_type: string): boolean } | null>(null);
const syncIteratorContainerTypes = () => {
const types = editorService?.get('stage')?.renderer?.runtime?.getApp?.()?.iteratorContainerType;
// runtime 在 iframe 里创建 Set 时,instanceof 对不上当前窗口的 Set,只认 has。
iteratorContainerTypes.value = typeof types?.has === 'function' ? types : null;
};
watch(
() => editorService?.get('stage') ?? null,
(stage, _, onCleanup) => {
syncIteratorContainerTypes();
if (!stage?.on) return;
stage.on('runtime-ready', syncIteratorContainerTypes);
onCleanup(() => {
stage.off('runtime-ready', syncIteratorContainerTypes);
});
},
{ immediate: true },
);
const isIteratorContainer = (type?: string) => {
if (!type) return false;
const types = iteratorContainerTypes.value;
return types ? types.has(type) : type === 'iterator-container';
};
/** 迭代器容器自身不算子组件,只有放进它里面的节点才同时支持 array.xxx 和下标 */
const inIteratorChild = computed(() => {
const nodeId = mForm?.initValues?.id;
if (!editorService?.getNodeInfo || nodeId === undefined || nodeId === null || nodeId === '') return false;
// getNodeInfo 内部只调用一次 getNodePath。path 最后一项是节点自身。
const { path } = editorService.getNodeInfo(nodeId);
return path.slice(0, -1).some((node) => isIteratorContainer(node.type));
});
const fieldOptions = (ds: DataSourceSchema) =>
getCascaderOptionsFromFields(ds.fields, props.dataSourceFieldType, getDataSourceEditorData(ds), {
directArrayElements: inIteratorChild.value,
});
const fieldsOptions = computed(() => {
const ds = allDataSources.value.find((ds) => ds.id === removeDataSourceFieldPrefix(selectDataSourceId.value));
if (!ds) return [];
return getCascaderOptionsFromFields(ds.fields, props.dataSourceFieldType);
const options = fieldOptions(ds);
ensureSelectedArrayIndices(options, selectFieldsId.value);
return options;
});
const cascaderOptions = computed(() => {
const selected = Array.isArray(modelValue.value) ? modelValue.value : [];
const selectedDsId = `${selected[0] ?? ''}`;
const selectedFields = selected.slice(1);
const options =
dataSources.value?.map((ds) => ({
label: ds.title || ds.id,
value: valueIsKey.value ? ds.id : `${DATA_SOURCE_FIELDS_SELECT_VALUE_PREFIX}${ds.id}`,
children: getCascaderOptionsFromFields(ds.fields, props.dataSourceFieldType),
})) || [];
dataSources.value?.map((ds) => {
const value = valueIsKey.value ? ds.id : `${DATA_SOURCE_FIELDS_SELECT_VALUE_PREFIX}${ds.id}`;
const children = fieldOptions(ds);
if (value === selectedDsId) {
ensureSelectedArrayIndices(children, selectedFields);
}
return {
label: ds.title || ds.id,
value,
children,
};
}) || [];
return options.filter((option) => option.children.length);
});

View File

@ -1,6 +1,13 @@
import type { DataSchema, DataSourceFieldType, DataSourceSchema } from '@tmagic/core';
import { type CascaderOption, type FormConfig, type TabConfig } from '@tmagic/form';
import { dataSourceTemplateRegExp, getKeysArray, isArrayIndex, isNumber } from '@tmagic/utils';
import {
dataSourceTemplateRegExp,
getDefaultValueFromFields,
getKeysArray,
isArrayIndex,
isNumber,
isObject,
} from '@tmagic/utils';
import BaseFormConfig from './formConfigs/base';
import HttpFormConfig from './formConfigs/http';
@ -207,20 +214,157 @@ export const getDisplayField = (dataSources: DataSourceSchema[], key: string) =>
return displayState;
};
interface FieldCascaderOption extends CascaderOption {
children?: FieldCascaderOption[];
/** 字段类型。数组节点才需要继续补下标 */
fieldType?: DataSourceFieldType;
/** 数组下标节点,不是 schema 里的字段 */
arrayIndex?: boolean;
}
/** 编辑器里这份数据源当前用于展示的数据:优先 useInEditor 的 mock,否则用字段默认值 */
export const getDataSourceEditorData = (ds: Pick<DataSourceSchema, 'fields' | 'mocks'>): Record<string, any> => {
const mock = ds.mocks?.find((item) => item.useInEditor)?.data;
if (mock && isObject(mock)) return mock;
return getDefaultValueFromFields(ds.fields || []);
};
const cloneSchemaOptions = (nodes: FieldCascaderOption[]): FieldCascaderOption[] =>
nodes
.filter((node) => !node.arrayIndex)
.map((node) => ({
label: node.label,
value: node.value,
fieldType: node.fieldType,
...(node.children?.length ? { children: cloneSchemaOptions(node.children) } : {}),
}));
const cloneOptions = (nodes: FieldCascaderOption[]): FieldCascaderOption[] =>
nodes.map((node) => ({
label: node.label,
value: node.value,
fieldType: node.fieldType,
...(node.arrayIndex ? { arrayIndex: true } : {}),
...(node.children?.length ? { children: cloneOptions(node.children) } : {}),
}));
/**
* 已选路径对不上选项时补节点,否则级联框输入框是空的。
* 数组字段后面缺的下标会补上;只展示下标时,已保存的元素字段路径(`array.xxx`)也会补回。
* 对象上的数字字段名仍然按字段处理。
*/
export const ensureSelectedArrayIndices = (options: FieldCascaderOption[], fieldPath: Array<string | number>) => {
let level = options;
let parent: FieldCascaderOption | undefined;
for (let i = 0; i < fieldPath.length; i++) {
const segment = `${fieldPath[i]}`;
let node = level.find((opt) => `${opt.value}` === segment);
if (!node && parent?.fieldType === 'array') {
if (isArrayIndex(segment)) {
const fromSchema = cloneSchemaOptions(level);
const fromIndex = cloneSchemaOptions(level.find((item) => item.arrayIndex)?.children || []);
const children = fromSchema.length ? fromSchema : fromIndex;
node = {
label: `[${segment}]`,
value: Number(segment),
arrayIndex: true,
...(children.length ? { children } : {}),
};
level.push(node);
} else {
node = cloneOptions(level.find((item) => item.arrayIndex)?.children || []).find(
(item) => !item.arrayIndex && `${item.value}` === segment,
);
if (node) level.push(node);
}
}
if (!node) return;
parent = node;
if (i === fieldPath.length - 1) return;
if (!node.children) node.children = [];
level = node.children;
}
};
export interface CascaderFieldsContext {
/**
* 是否把数组元素字段直接列在数组下面(`array.xxx`)。
* 迭代器子组件里为 true,同时保留下标(`array[0].xxx` / `array.0.xxx`)。
* 为 false 时只保留下标。不传则保留元素字段,供事件选择等其它调用方使用。
*/
directArrayElements?: boolean;
}
/** 数组下标固定提供 0–19,不随 mock 或默认值的长度变化 */
const ARRAY_INDEX_COUNT = 20;
const appendArrayIndexOptions = (
field: DataSchema,
dataSourceFieldType: DataSourceFieldType[],
typeSet: Set<DataSourceFieldType>,
includesAny: boolean,
context: CascaderFieldsContext,
): FieldCascaderOption[] => {
const elementFields = field.fields;
const taken = new Set((elementFields || []).map((item) => item.name));
const elementType: DataSourceFieldType = elementFields?.length ? 'object' : 'any';
// 没声明元素结构时,限定了具体类型就选不中这个下标
if (!elementFields?.length && !includesAny) return [];
const children = getCascaderOptionsFromFields(elementFields, dataSourceFieldType, {}, context);
const indexMatches = includesAny || typeSet.has(elementType);
if (!indexMatches && !children.length) return [];
const indexNodes: FieldCascaderOption[] = [];
for (let index = 0; index < ARRAY_INDEX_COUNT; index++) {
const name = `${index}`;
// 元素上已有同名数字字段时,下标不占用这个 value,和 resolveFieldByPath 的优先顺序一致
if (taken.has(name)) continue;
indexNodes.push({
label: `[${index}]`,
value: index,
arrayIndex: true,
...(children.length ? { children } : {}),
});
}
return indexNodes;
};
export const getCascaderOptionsFromFields = (
fields: DataSchema[] = [],
dataSourceFieldType: DataSourceFieldType[] = ['any'],
): CascaderOption[] => {
const typeSet = new Set(dataSourceFieldType.length ? dataSourceFieldType : ['any']);
data?: Record<string, any>,
context: CascaderFieldsContext = {},
): FieldCascaderOption[] => {
const typeSet = new Set<DataSourceFieldType>(dataSourceFieldType.length ? dataSourceFieldType : ['any']);
const includesAny = typeSet.has('any');
const result: CascaderOption[] = [];
const result: FieldCascaderOption[] = [];
for (const field of fields) {
const fieldType = field.type || 'any';
const isContainerType = fieldType === 'any' || fieldType === 'array' || fieldType === 'object';
const showElementFields = fieldType !== 'array' || context.directArrayElements !== false;
// 下标固定 0–19,不看 mock 有没有写出这一层。调用方传了 data,子树就继续带上,
// 否则数组元素上的嵌套数组,以及 mock 里缺了的中间对象,都不会出现下标。
const nestedData = data ? {} : undefined;
const children = isContainerType ? getCascaderOptionsFromFields(field.fields, dataSourceFieldType) : [];
let children: FieldCascaderOption[] =
isContainerType && showElementFields
? getCascaderOptionsFromFields(field.fields, dataSourceFieldType, nestedData, context)
: [];
if (fieldType === 'array' && data) {
const indexNodes = appendArrayIndexOptions(field, dataSourceFieldType, typeSet, includesAny, context);
children = [...children, ...indexNodes];
}
const matchesType = includesAny || typeSet.has(fieldType);
@ -229,6 +373,7 @@ export const getCascaderOptionsFromFields = (
label: `${field.title || field.name}(${field.type})`,
value: field.name,
children,
fieldType,
});
}
}

View File

@ -9,15 +9,17 @@ import { mount } from '@vue/test-utils';
import FieldSelect from '@editor/fields/DataSourceFieldSelect/FieldSelect.vue';
import DSFSIndex from '@editor/fields/DataSourceFieldSelect/Index.vue';
import { getCascaderOptionsFromFields } from '@editor/utils';
const { messageError } = vi.hoisted(() => ({ messageError: vi.fn() }));
const dataSourceService = { get: vi.fn() };
const propsService = { getDisabledDataSource: vi.fn() };
const uiService = { get: vi.fn(), set: vi.fn() };
const editorService = { getNodeById: vi.fn(), getParentById: vi.fn(), getNodeInfo: vi.fn(), get: vi.fn() };
vi.mock('@editor/hooks/use-services', () => ({
useServices: () => ({ dataSourceService, propsService, uiService }),
useServices: () => ({ dataSourceService, propsService, uiService, editorService }),
}));
vi.mock('@editor/components/Icon.vue', () => ({
@ -111,6 +113,10 @@ beforeEach(() => {
]);
propsService.getDisabledDataSource.mockReturnValue(false);
uiService.get.mockReturnValue([{ $key: 'data-source' }]);
editorService.getNodeById.mockReturnValue(null);
editorService.getParentById.mockReturnValue(null);
editorService.getNodeInfo.mockReturnValue({ path: [] });
editorService.get.mockReturnValue(null);
});
describe('FieldSelect', () => {
@ -152,6 +158,84 @@ describe('FieldSelect', () => {
expect(wrapper.emitted('change')?.[0]?.[0]).toEqual(['ds1', 'a']);
});
test('model 按路径数组原样传给 cascader', () => {
const wrapper = mount(FieldSelect, {
props: { modelValue: ['ds-ds1', 'array', 1, 'xxx'] } as any,
});
expect(wrapper.findComponent({ name: 'TMagicCascader' }).props('modelValue')).toEqual([
'ds-ds1',
'array',
1,
'xxx',
]);
const fieldsOnly = mount(FieldSelect, {
props: { dataSourceId: 'ds1', modelValue: ['array', 'xxx'] } as any,
});
expect(fieldsOnly.findComponent({ name: 'TMagicCascader' }).props('modelValue')).toEqual(['array', 'xxx']);
});
test('迭代器子组件同时支持元素字段和下标,容器自身和外部只留下标', () => {
const iterator = { id: 'iter1', type: 'iterator-container', dsField: ['ds1', 'array'] };
editorService.getNodeInfo.mockImplementation((id: string) =>
id === 'text1'
? { path: [{ id: 'page1', type: 'page' }, iterator, { id: 'text1', type: 'text' }] }
: { path: [{ id: 'page1', type: 'page' }, iterator] },
);
mount(FieldSelect, {
props: { modelValue: ['ds-ds1', 'array', 'xxx'] } as any,
global: { provide: { mForm: { initValues: { id: 'text1' } } } },
});
expect(getCascaderOptionsFromFields).toHaveBeenCalledWith(
expect.anything(),
undefined,
expect.anything(),
expect.objectContaining({ directArrayElements: true }),
);
vi.mocked(getCascaderOptionsFromFields).mockClear();
mount(FieldSelect, {
props: { modelValue: ['ds-ds1', 'array', 0, 'xxx'] } as any,
global: { provide: { mForm: { initValues: { id: 'iter1' } } } },
});
expect(getCascaderOptionsFromFields).toHaveBeenCalledWith(
expect.anything(),
undefined,
expect.anything(),
expect.objectContaining({ directArrayElements: false }),
);
});
test('自定义 iteratorContainerType 的容器子节点同样支持元素字段', () => {
editorService.get.mockReturnValue({
renderer: {
runtime: {
getApp: () => ({ iteratorContainerType: new Set(['iterator-container', 'my-iter']) }),
},
},
});
editorService.getNodeInfo.mockReturnValue({
path: [
{ id: 'page1', type: 'page' },
{ id: 'iter1', type: 'my-iter' },
{ id: 'text1', type: 'text' },
],
});
mount(FieldSelect, {
props: { modelValue: ['ds-ds1', 'array', 'xxx'] } as any,
global: { provide: { mForm: { initValues: { id: 'text1' } } } },
});
expect(getCascaderOptionsFromFields).toHaveBeenCalledWith(
expect.anything(),
undefined,
expect.anything(),
expect.objectContaining({ directArrayElements: true }),
);
});
test('onChangeHandler emit', async () => {
const wrapper = mount(FieldSelect, { props: {} as any });
await wrapper.find('.fake-cascader').trigger('click');

View File

@ -9,10 +9,19 @@ import { mount } from '@vue/test-utils';
import DataSourceFields from '@editor/fields/DataSourceFields.vue';
const { messageBoxConfirm, messageError } = vi.hoisted(() => ({
messageBoxConfirm: vi.fn(async () => true),
messageError: vi.fn(),
}));
const { messageBoxConfirm, messageError, fieldFormSubmitPayload, fieldFormChangeRecords, capturedFieldFormValues } =
vi.hoisted(() => {
const current: Record<string, any> = { index: -1, name: 'a', title: 't', type: 'string' };
const changeRecords: { propPath?: string; value: any }[] = [];
return {
messageBoxConfirm: vi.fn(async () => true),
messageError: vi.fn(),
fieldFormSubmitPayload: { current },
fieldFormChangeRecords: { current: changeRecords },
capturedFieldFormValues: { current: null as any },
};
});
const uiService = { get: vi.fn() };
vi.mock('@editor/hooks/use-services', () => ({
@ -73,17 +82,19 @@ vi.mock('@tmagic/form', async () => {
capturedConfigs.push(props.config);
const isJson =
Array.isArray(props.config) && props.config.some((c: any) => c.type === 'vs-code' && c.language === 'json');
return () =>
h('div', {
return () => {
if (!isJson) capturedFieldFormValues.current = props.values;
return h('div', {
class: ['fake-form-box', isJson ? 'json-form' : 'field-form'],
onClick: () => {
if (isJson) {
emit('submit', { data: '{"foo":1}' });
} else {
emit('submit', { index: -1, name: 'a', title: 't', type: 'string' }, { changeRecords: [] });
emit('submit', fieldFormSubmitPayload.current, { changeRecords: fieldFormChangeRecords.current });
}
},
});
};
},
}),
};
@ -121,6 +132,9 @@ beforeEach(() => {
vi.clearAllMocks();
capturedColumns = [];
capturedConfigs = [];
capturedFieldFormValues.current = null;
fieldFormSubmitPayload.current = { index: -1, name: 'a', title: 't', type: 'string' };
fieldFormChangeRecords.current = [];
});
describe('DataSourceFields', () => {
@ -202,8 +216,203 @@ describe('DataSourceFields', () => {
const setModel = vi.fn();
typeItem.onChange(undefined, 'string', { setModel });
expect(setModel).toHaveBeenCalledWith('fields', []);
typeItem.onChange(undefined, 'object', { setModel });
expect(setModel).toHaveBeenCalledTimes(1);
setModel.mockClear();
typeItem.onChange(undefined, 'object', { setModel });
expect(setModel).toHaveBeenCalledWith('defaultValue', {});
expect(setModel).not.toHaveBeenCalledWith('fields', []);
});
test('切到数组且默认值为空时写成 [],切走时空数组恢复成空字符串', () => {
mount(DataSourceFields, {
props: { config: {}, model: { fields: [] }, name: 'fields', prop: 'fields' } as any,
});
const typeItem = capturedConfigs[0].find((c: any) => c.name === 'type');
const setModel = vi.fn();
typeItem.onChange(undefined, 'array', { model: { defaultValue: '' }, setModel });
expect(setModel).toHaveBeenCalledWith('defaultValue', []);
setModel.mockClear();
typeItem.onChange(undefined, 'array', { model: { type: 'array' }, setModel });
expect(setModel).toHaveBeenCalledWith('defaultValue', []);
setModel.mockClear();
typeItem.onChange(undefined, 'array', { model: { defaultValue: [{ id: 1 }] }, setModel });
expect(setModel).not.toHaveBeenCalled();
setModel.mockClear();
typeItem.onChange(undefined, 'string', { model: { defaultValue: [] }, setModel });
expect(setModel).toHaveBeenCalledWith('fields', []);
expect(setModel).toHaveBeenCalledWith('defaultValue', '');
setModel.mockClear();
typeItem.onChange(undefined, 'string', { model: { defaultValue: 'kept' }, setModel });
expect(setModel).not.toHaveBeenCalledWith('defaultValue', '');
});
test('提交数组字段时未填默认值收成空数组', async () => {
fieldFormSubmitPayload.current = { index: -1, name: 'list', title: '列表', type: 'array', defaultValue: '' };
const wrapper = mount(DataSourceFields, {
props: { config: {}, model: { fields: [] }, name: 'fields', prop: 'fields' } as any,
});
await wrapper.findAll('.fake-btn')[1].trigger('click');
await wrapper.find('.field-form').trigger('click');
const lastCall = (wrapper.emitted('change') as any[]).pop();
expect(lastCall[0]).toMatchObject({ name: 'list', type: 'array', defaultValue: [] });
expect(lastCall[1].changeRecords[0].value.defaultValue).toEqual([]);
});
test('提交数组字段时已填默认值保持不变', async () => {
fieldFormSubmitPayload.current = {
index: 0,
name: 'list',
title: '列表',
type: 'array',
defaultValue: [{ id: 1 }],
};
const wrapper = mount(DataSourceFields, {
props: {
config: {},
model: { fields: [{ name: 'list', title: '列表', type: 'array' }] },
name: 'fields',
prop: 'fields',
} as any,
});
await wrapper.find('.field-form').trigger('click');
const lastCall = (wrapper.emitted('change') as any[]).pop();
expect(lastCall[0].defaultValue).toEqual([{ id: 1 }]);
expect(lastCall[1].modifyKey).toBe(0);
expect(lastCall[1].changeRecords).toEqual([]);
});
test('编辑数组字段时未填默认值会写入空数组', async () => {
fieldFormSubmitPayload.current = { index: 0, name: 'list', title: '列表', type: 'array', defaultValue: '' };
fieldFormChangeRecords.current = [{ propPath: 'title', value: '列表' }];
const wrapper = mount(DataSourceFields, {
props: {
config: {},
model: { fields: [{ name: 'list', title: '列表', type: 'array', defaultValue: '' }] },
name: 'fields',
prop: 'fields',
} as any,
});
await wrapper.find('.field-form').trigger('click');
const lastCall = (wrapper.emitted('change') as any[]).pop();
expect(lastCall[0].defaultValue).toEqual([]);
expect(lastCall[1].changeRecords).toEqual([
{ propPath: 'fields.0.title', value: '列表' },
{ propPath: 'fields.0.defaultValue', value: [] },
]);
fieldFormSubmitPayload.current = { index: 0, name: 'list', title: '列表', type: 'array' };
fieldFormChangeRecords.current = [{ propPath: 'defaultValue', value: '' }];
await wrapper.find('.field-form').trigger('click');
const replaced = (wrapper.emitted('change') as any[]).pop();
expect(replaced[0].defaultValue).toEqual([]);
expect(replaced[1].changeRecords).toEqual([{ propPath: 'fields.0.defaultValue', value: [] }]);
});
test('切到对象且默认值为空时写成 {},切走时空对象恢复成空字符串', () => {
mount(DataSourceFields, {
props: { config: {}, model: { fields: [] }, name: 'fields', prop: 'fields' } as any,
});
const typeItem = capturedConfigs[0].find((c: any) => c.name === 'type');
const setModel = vi.fn();
typeItem.onChange(undefined, 'object', { model: { defaultValue: '' }, setModel });
expect(setModel).toHaveBeenCalledWith('defaultValue', {});
setModel.mockClear();
typeItem.onChange(undefined, 'object', { model: { defaultValue: [] }, setModel });
expect(setModel).toHaveBeenCalledWith('defaultValue', {});
setModel.mockClear();
typeItem.onChange(undefined, 'object', { model: { defaultValue: { a: 1 } }, setModel });
expect(setModel).not.toHaveBeenCalled();
setModel.mockClear();
typeItem.onChange(undefined, 'array', { model: { defaultValue: {} }, setModel });
expect(setModel).toHaveBeenCalledWith('defaultValue', []);
setModel.mockClear();
typeItem.onChange(undefined, 'string', { model: { defaultValue: {} }, setModel });
expect(setModel).toHaveBeenCalledWith('fields', []);
expect(setModel).toHaveBeenCalledWith('defaultValue', '');
});
test('提交对象字段时未填默认值收成空对象', async () => {
fieldFormSubmitPayload.current = { index: -1, name: 'info', title: '信息', type: 'object', defaultValue: '' };
const wrapper = mount(DataSourceFields, {
props: { config: {}, model: { fields: [] }, name: 'fields', prop: 'fields' } as any,
});
await wrapper.findAll('.fake-btn')[1].trigger('click');
await wrapper.find('.field-form').trigger('click');
const lastCall = (wrapper.emitted('change') as any[]).pop();
expect(lastCall[0]).toMatchObject({ name: 'info', type: 'object', defaultValue: {} });
expect(lastCall[1].changeRecords[0].value.defaultValue).toEqual({});
});
test('提交对象字段时已填默认值保持不变', async () => {
fieldFormSubmitPayload.current = {
index: 0,
name: 'info',
title: '信息',
type: 'object',
defaultValue: { a: 1 },
};
const wrapper = mount(DataSourceFields, {
props: {
config: {},
model: { fields: [{ name: 'info', title: '信息', type: 'object' }] },
name: 'fields',
prop: 'fields',
} as any,
});
await wrapper.find('.field-form').trigger('click');
const lastCall = (wrapper.emitted('change') as any[]).pop();
expect(lastCall[0].defaultValue).toEqual({ a: 1 });
expect(lastCall[1].changeRecords).toEqual([]);
});
test('编辑对象字段时未填默认值会写入空对象', async () => {
fieldFormSubmitPayload.current = { index: 0, name: 'info', title: '信息', type: 'object' };
fieldFormChangeRecords.current = [{ propPath: 'defaultValue', value: '' }];
const wrapper = mount(DataSourceFields, {
props: {
config: {},
model: { fields: [{ name: 'info', title: '信息', type: 'object', defaultValue: '' }] },
name: 'fields',
prop: 'fields',
} as any,
});
await wrapper.find('.field-form').trigger('click');
const lastCall = (wrapper.emitted('change') as any[]).pop();
expect(lastCall[0].defaultValue).toEqual({});
expect(lastCall[1].changeRecords).toEqual([{ propPath: 'fields.0.defaultValue', value: {} }]);
});
test('编辑对象字段时空默认值显示为空对象', async () => {
const row = { name: 'info', title: '信息', type: 'object', defaultValue: '' };
const wrapper = mount(DataSourceFields, {
props: { config: {}, model: { fields: [row] }, name: 'fields', prop: 'fields' } as any,
});
const editAction = capturedColumns[capturedColumns.length - 1].actions[0];
editAction.handler(row, 0);
await wrapper.vm.$nextTick();
expect(capturedFieldFormValues.current).toMatchObject({ type: 'object', defaultValue: {}, index: 0 });
});
test('编辑数组字段时空默认值显示为空数组', async () => {
const row = { name: 'list', title: '列表', type: 'array', defaultValue: '' };
const wrapper = mount(DataSourceFields, {
props: { config: {}, model: { fields: [row] }, name: 'fields', prop: 'fields' } as any,
});
const editAction = capturedColumns[capturedColumns.length - 1].actions[0];
editAction.handler(row, 0);
await wrapper.vm.$nextTick();
expect(capturedFieldFormValues.current).toMatchObject({ type: 'array', defaultValue: [], index: 0 });
});
test('name 字段 validator 重复提示', () => {

View File

@ -6,7 +6,9 @@
import { describe, expect, test } from 'vitest';
import {
ensureSelectedArrayIndices,
getCascaderOptionsFromFields,
getDataSourceEditorData,
getDisplayField,
getFieldType,
getFormConfig,
@ -14,6 +16,8 @@ import {
resolveFieldByPath,
} from '@editor/utils/data-source';
const arrayIndexValues = (count = 20) => Array.from({ length: count }, (_, index) => index);
describe('data-source utils', () => {
test('getFormConfig - base 类型', () => {
const cfg = getFormConfig('base', {});
@ -310,6 +314,281 @@ describe('data-source utils', () => {
expect(opts).toHaveLength(1);
});
test('getDataSourceEditorData 优先 useInEditor mock,否则用字段默认值', () => {
const fields: any = [{ name: 'array', type: 'array', defaultValue: [{ a: 1 }] }];
expect(getDataSourceEditorData({ fields, mocks: [] })).toEqual({ array: [{ a: 1 }] });
expect(
getDataSourceEditorData({
fields,
mocks: [{ title: 'off', enable: true, useInEditor: false, data: { array: [] } }],
}),
).toEqual({ array: [{ a: 1 }] });
expect(
getDataSourceEditorData({
fields,
mocks: [{ title: 'on', enable: true, useInEditor: true, data: { array: [{ a: 2 }, { a: 3 }] } }],
}),
).toEqual({ array: [{ a: 2 }, { a: 3 }] });
expect(
getDataSourceEditorData({
fields,
mocks: [{ title: 'bad', enable: true, useInEditor: true, data: [] as any }],
}),
).toEqual({ array: [{ a: 1 }] });
});
test('getCascaderOptionsFromFields 按数组数据展示 array[i].field', () => {
const fields: any = [
{
name: 'array',
title: 'array',
type: 'array',
fields: [{ name: 'xxx', title: 'xxx', type: 'string' }],
},
{
name: 'obj',
type: 'object',
fields: [
{
name: 'list',
type: 'array',
fields: [{ name: 'xxxx', type: 'number' }],
},
],
},
];
const opts = getCascaderOptionsFromFields(fields, ['any'], {
array: [{ xxx: 'a' }, { xxx: 'b' }],
obj: { list: [{ xxxx: 1 }] },
});
const arrayNode = opts.find((item) => item.value === 'array');
expect(arrayNode?.children?.map((item) => item.value)).toEqual(['xxx', ...arrayIndexValues()]);
expect(arrayNode?.children?.[1]).toMatchObject({ label: '[0]', value: 0, arrayIndex: true });
expect(arrayNode?.children?.[1].children?.[0].value).toBe('xxx');
const listNode = opts.find((item) => item.value === 'obj')?.children?.find((item) => item.value === 'list');
expect(listNode?.children?.map((item) => item.value)).toEqual(['xxxx', ...arrayIndexValues()]);
});
test('非迭代器子组件只保留数组下标,子组件同时保留 array.xxx', () => {
const fields: any = [
{
name: 'array',
type: 'array',
fields: [{ name: 'xxx', type: 'string' }],
},
{
name: 'obj',
type: 'object',
fields: [
{
name: 'list',
type: 'array',
fields: [{ name: 'yyyy', type: 'number' }],
},
],
},
];
const data = {
array: [{ xxx: 'a' }, { xxx: 'b' }],
obj: { list: [{ yyyy: 1 }] },
};
const outside = getCascaderOptionsFromFields(fields, ['any'], data, { directArrayElements: false });
const arrayNode = outside.find((item) => item.value === 'array');
expect(arrayNode?.children?.map((item) => item.value)).toEqual(arrayIndexValues());
expect(arrayNode?.children?.[0].children?.map((item) => item.value)).toEqual(['xxx']);
const listNode = outside.find((item) => item.value === 'obj')?.children?.find((item) => item.value === 'list');
expect(listNode?.children?.map((item) => item.value)).toEqual(arrayIndexValues());
const inside = getCascaderOptionsFromFields(fields, ['any'], data, { directArrayElements: true });
expect(inside.find((item) => item.value === 'array')?.children?.map((item) => item.value)).toEqual([
'xxx',
...arrayIndexValues(),
]);
const insideList = inside.find((item) => item.value === 'obj')?.children?.find((item) => item.value === 'list');
expect(insideList?.children?.map((item) => item.value)).toEqual(['yyyy', ...arrayIndexValues()]);
});
test('getCascaderOptionsFromFields 元素字段与下标同名时保留字段', () => {
const fields: any = [
{
name: 'array',
type: 'array',
fields: [
{ name: '0', type: 'number' },
{ name: 'xxx', type: 'string' },
],
},
];
const opts = getCascaderOptionsFromFields(fields, ['any'], {
array: [{ xxx: 'a' }, { xxx: 'b' }],
});
expect(opts[0].children?.map((item) => item.value)).toEqual(['0', 'xxx', ...arrayIndexValues().slice(1)]);
expect(opts[0].children?.find((item) => item.value === '0')?.arrayIndex).toBeUndefined();
expect(opts[0].children?.find((item) => item.value === 1)?.arrayIndex).toBe(true);
});
test('getCascaderOptionsFromFields 限定字段类型时仍保留能下钻到该类型的数组项', () => {
const fields: any = [
{
name: 'array',
type: 'array',
fields: [{ name: 'n', type: 'number' }],
},
];
const opts = getCascaderOptionsFromFields(fields, ['number'], { array: [{ n: 1 }] });
expect(opts[0].children?.map((item) => item.value)).toEqual(['n', ...arrayIndexValues()]);
expect(opts[0].children?.[1].children?.map((item) => item.value)).toEqual(['n']);
const objectOnly = getCascaderOptionsFromFields(
[{ name: 'array', type: 'array', fields: [{ name: 'n', type: 'number' }] }] as any,
['object'],
{ array: [{ n: 1 }] },
);
expect(objectOnly[0].children?.map((item) => item.value)).toEqual(arrayIndexValues());
});
test('getCascaderOptionsFromFields 未声明元素结构时只在允许 any 时展示下标', () => {
const fields: any = [{ name: 'array', type: 'array' }];
const data = { array: [1, 2] };
const anyOpts = getCascaderOptionsFromFields(fields, ['any'], data);
expect(anyOpts[0].children?.map((item) => item.label)).toEqual(arrayIndexValues().map((value) => `[${value}]`));
expect(anyOpts[0].children?.[0].children).toBeUndefined();
expect(getCascaderOptionsFromFields(fields, ['number'], data)).toEqual([]);
});
test('getCascaderOptionsFromFields 不传数据时不插入数组下标', () => {
const fields: any = [
{
name: 'array',
type: 'array',
defaultValue: [{ xxx: 1 }],
fields: [{ name: 'xxx', type: 'string' }],
},
];
const opts = getCascaderOptionsFromFields(fields);
expect(opts[0].children?.map((item) => item.value)).toEqual(['xxx']);
});
test('ensureSelectedArrayIndices 为数据里没有的下标补节点,非数组不补', () => {
const fields: any = [
{
name: 'array',
type: 'array',
fields: [{ name: 'xxx', type: 'string' }],
},
{ name: 'title', type: 'string' },
];
const opts = getCascaderOptionsFromFields(fields, ['any'], { array: [] });
ensureSelectedArrayIndices(opts, ['array', '1', 'xxx']);
const arrayNode = opts.find((item) => item.value === 'array');
expect(arrayNode?.children?.map((item) => item.value)).toEqual(['xxx', ...arrayIndexValues()]);
expect(arrayNode?.children?.[1].children?.[0].value).toBe('xxx');
const titleOpts = getCascaderOptionsFromFields(fields, ['any'], { array: [] });
ensureSelectedArrayIndices(titleOpts, ['title', '0']);
expect(titleOpts.find((item) => item.value === 'title')?.children).toEqual([]);
});
test('ensureSelectedArrayIndices 只剩已有下标时,缺失下标复制元素字段', () => {
const fields: any = [
{
name: 'array',
type: 'array',
fields: [{ name: 'xxx', type: 'string' }],
},
];
const opts = getCascaderOptionsFromFields(
fields,
['any'],
{ array: [{ xxx: 'a' }] },
{ directArrayElements: false },
);
ensureSelectedArrayIndices(opts, ['array', '3', 'xxx']);
const index = opts[0].children?.find((item) => item.value === 3);
expect(index?.children?.map((item) => item.value)).toEqual(['xxx']);
});
test('ensureSelectedArrayIndices 下标之后还有不存在的字段时停住', () => {
const fields: any = [{ name: 'array', type: 'array' }];
const opts = getCascaderOptionsFromFields(fields, ['any'], { array: [] });
ensureSelectedArrayIndices(opts, ['array', '2', 'missing']);
expect(opts[0].children?.map((item) => item.value)).toEqual(arrayIndexValues());
expect(opts[0].children?.find((item) => item.value === 2)?.children).toEqual([]);
});
test('没有 mock 和默认值时仍可按字段结构选择 array[0].xxx', () => {
const fields: any = [
{
name: 'array',
type: 'array',
fields: [
{ name: 'xxx', type: 'string' },
{ name: 'list', type: 'array', fields: [{ name: 'yyyy', type: 'number' }] },
],
},
];
const outside = getCascaderOptionsFromFields(fields, ['any'], {}, { directArrayElements: false });
expect(outside[0].children?.map((item) => item.value)).toEqual(arrayIndexValues());
expect(outside[0].children?.[0].children?.map((item) => item.value)).toEqual(['xxx', 'list']);
const nested = outside[0].children?.[0].children?.find((item) => item.value === 'list');
expect(nested?.children?.map((item) => item.value)).toEqual(arrayIndexValues());
expect(nested?.children?.[0].children?.map((item) => item.value)).toEqual(['yyyy']);
const inside = getCascaderOptionsFromFields(fields, ['any'], { array: [] }, { directArrayElements: true });
expect(inside[0].children?.map((item) => item.value)).toEqual(['xxx', 'list', ...arrayIndexValues()]);
const directList = inside[0].children?.find((item) => item.value === 'list');
expect(directList?.children?.map((item) => item.value)).toEqual(['yyyy', ...arrayIndexValues()]);
});
test('mock 缺了中间对象时,下层数组仍有下标', () => {
const fields: any = [
{
name: 'obj',
type: 'object',
fields: [{ name: 'list', type: 'array', fields: [{ name: 'yyyy', type: 'number' }] }],
},
];
const opts = getCascaderOptionsFromFields(fields, ['any'], { unrelated: true }, { directArrayElements: false });
const list = opts[0].children?.find((item) => item.value === 'list');
expect(list?.children?.map((item) => item.value)).toEqual(arrayIndexValues());
expect(list?.children?.[0].children?.map((item) => item.value)).toEqual(['yyyy']);
});
test('ensureSelectedArrayIndices 只留下标时补回已选的元素字段', () => {
const fields: any = [
{
name: 'array',
type: 'array',
fields: [
{ name: 'xxx', type: 'string' },
{ name: 'list', type: 'array', fields: [{ name: 'yyyy', type: 'number' }] },
],
},
];
const opts = getCascaderOptionsFromFields(fields, ['any'], {}, { directArrayElements: false });
ensureSelectedArrayIndices(opts, ['array', 'xxx']);
expect(opts[0].children?.find((item) => item.value === 'xxx')).toMatchObject({
value: 'xxx',
fieldType: 'string',
});
const nested = getCascaderOptionsFromFields(fields, ['any'], {}, { directArrayElements: false });
ensureSelectedArrayIndices(nested, ['array', 'list', 2, 'yyyy']);
const list = nested[0].children?.find((item) => item.value === 'list');
expect(list?.arrayIndex).toBeUndefined();
expect(list?.children?.map((item) => item.value)).toEqual(arrayIndexValues());
expect(list?.children?.find((item) => item.value === 2)?.children?.map((item) => item.value)).toEqual(['yyyy']);
const bare = getCascaderOptionsFromFields(fields, ['any'], undefined, { directArrayElements: false });
ensureSelectedArrayIndices(bare, ['array', 'xxx']);
expect(bare[0].children).toEqual([]);
});
test('getFieldType - 第二层 fields 缺失提前返回', () => {
const ds: any = { fields: [{ name: 'a', type: 'string' }] };
expect(getFieldType(ds, ['a', 'b'])).toBe('');