@nocobase/client-v2 2.4.0-alpha.4 → 2.4.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,351 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import React from 'react';
11
+ import { Form, type FormInstance, type TableProps } from 'antd';
12
+ import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
13
+ import { DisplayItemModel, FlowEngine, FlowEngineProvider, FlowModelProvider } from '@nocobase/flow-engine';
14
+ import { afterEach, describe, expect, it, vi } from 'vitest';
15
+ import {
16
+ DetailsItemModel,
17
+ DisplaySubTableFieldModel,
18
+ DisplayTextFieldModel,
19
+ FormAssociationItemModel,
20
+ FormItemModel,
21
+ TableColumnModel,
22
+ aclCheck,
23
+ displayFieldComponent,
24
+ fixed,
25
+ overflowMode,
26
+ titleField,
27
+ } from '../../../../index';
28
+ import { buildAssociationOptions } from '../../../../actions/displayFieldComponent';
29
+ import { rebuildFieldSubModel } from '../../../../internal/utils/rebuildFieldSubModel';
30
+
31
+ type Row = Record<string, unknown>;
32
+ type TableOptions = TableProps<Row>;
33
+
34
+ const { tableRender } = vi.hoisted(() => ({ tableRender: vi.fn() }));
35
+
36
+ vi.mock('react-i18next', async (importOriginal) => ({
37
+ ...(await importOriginal<typeof import('react-i18next')>()),
38
+ useTranslation: () => ({ t: (value: string) => value }),
39
+ }));
40
+
41
+ vi.mock('antd', async (importOriginal) => ({
42
+ ...(await importOriginal<typeof import('antd')>()),
43
+ Table: (props: TableOptions) => {
44
+ tableRender(props);
45
+ return <div data-testid="rows">{JSON.stringify(props.dataSource)}</div>;
46
+ },
47
+ }));
48
+
49
+ afterEach(() => {
50
+ cleanup();
51
+ vi.restoreAllMocks();
52
+ tableRender.mockClear();
53
+ });
54
+
55
+ function setup(parentUse = 'FormAssociationItemModel') {
56
+ const engine = new FlowEngine();
57
+ engine.registerActions({ aclCheck, displayFieldComponent, fixed, overflowMode, titleField });
58
+ engine.registerModels({
59
+ DetailsItemModel,
60
+ DisplaySubTableFieldModel,
61
+ DisplayTextFieldModel,
62
+ FormAssociationItemModel,
63
+ FormItemModel,
64
+ TableColumnModel,
65
+ });
66
+ const dataSource = engine.dataSourceManager.getDataSource('main');
67
+ dataSource.addCollection({
68
+ name: 'users',
69
+ filterTargetKey: 'id',
70
+ titleField: 'name',
71
+ fields: [
72
+ { name: 'id', type: 'integer', interface: 'integer' },
73
+ { name: 'name', type: 'string', interface: 'input' },
74
+ ],
75
+ });
76
+ dataSource.addCollection({
77
+ name: 'orgs',
78
+ fields: [
79
+ { name: 'staff', type: 'belongsToMany', interface: 'm2m', target: 'users' },
80
+ { name: 'reports', type: 'hasMany', interface: 'o2m', target: 'users' },
81
+ { name: 'members', type: 'belongsToArray', interface: 'mbm', target: 'users' },
82
+ { name: 'manager', type: 'belongsTo', interface: 'm2o', target: 'users' },
83
+ { name: 'name', type: 'string', interface: 'input' },
84
+ ],
85
+ });
86
+ dataSource.addCollection({
87
+ name: 'posts',
88
+ fields: [{ name: 'org', type: 'belongsTo', interface: 'm2o', target: 'orgs' }],
89
+ });
90
+ const parent = engine.createModel<FormAssociationItemModel>({
91
+ use: parentUse,
92
+ stepParams: {
93
+ fieldSettings: {
94
+ init: { dataSourceKey: 'main', collectionName: 'posts', fieldPath: 'org.staff' },
95
+ },
96
+ },
97
+ });
98
+ const resource = { getAppends: vi.fn(() => ['staff']), setAppends: vi.fn(), refresh: vi.fn() };
99
+ parent.context.defineProperty('blockModel', {
100
+ value: { collection: dataSource.getCollection('posts'), resource, addAppends: vi.fn() },
101
+ });
102
+ parent.context.defineProperty('flowSettingsEnabled', { value: false });
103
+ parent.context.defineProperty('aclCheck', { value: vi.fn().mockResolvedValue(true) });
104
+ const field = parent.setSubModel('field', { use: 'DisplaySubTableFieldModel', props: { pageSize: 10 } });
105
+ return { engine, parent, field: field as DisplaySubTableFieldModel, resource, dataSource };
106
+ }
107
+
108
+ function tableProps(): TableOptions {
109
+ return tableRender.mock.lastCall[0] as TableOptions;
110
+ }
111
+
112
+ describe('DisplaySubTableFieldModel in association display fields', () => {
113
+ it.each(['staff', 'reports', 'members'])('offers a subtable for the to-many field %s', (fieldName) => {
114
+ const { parent, dataSource } = setup();
115
+ const collectionField = dataSource.getCollection('orgs').getField(fieldName);
116
+ const bindings = FormAssociationItemModel.getBindingsByField(parent.context, collectionField);
117
+ expect(bindings.map((binding) => binding.modelName)).toContain('DisplaySubTableFieldModel');
118
+ expect(buildAssociationOptions(parent.context, FormAssociationItemModel)).toContainEqual({
119
+ label: expect.any(String),
120
+ value: 'DisplaySubTableFieldModel',
121
+ });
122
+ });
123
+
124
+ it('keeps the binding scoped and preserves the default title-field display', () => {
125
+ const { parent, dataSource } = setup();
126
+ const collection = dataSource.getCollection('orgs');
127
+ for (const itemModel of [DisplayItemModel, TableColumnModel, FormItemModel]) {
128
+ expect(itemModel.getBindingsByField(parent.context, collection.getField('staff'))).not.toEqual(
129
+ expect.arrayContaining([expect.objectContaining({ modelName: 'DisplaySubTableFieldModel' })]),
130
+ );
131
+ }
132
+ for (const fieldName of ['manager', 'name']) {
133
+ expect(FormAssociationItemModel.getBindingsByField(parent.context, collection.getField(fieldName))).not.toEqual(
134
+ expect.arrayContaining([expect.objectContaining({ modelName: 'DisplaySubTableFieldModel' })]),
135
+ );
136
+ }
137
+ expect(DetailsItemModel.getBindingsByField(parent.context, collection.getField('staff'))).toEqual(
138
+ expect.arrayContaining([expect.objectContaining({ modelName: 'DisplaySubTableFieldModel' })]),
139
+ );
140
+ expect(
141
+ FormAssociationItemModel.getDefaultBindingByField(parent.context, collection.getField('staff'), {
142
+ fallbackToTargetTitleField: true,
143
+ })?.modelName,
144
+ ).toBe('DisplayTextFieldModel');
145
+ });
146
+
147
+ it.each([undefined, null, [], { rows: [] }])('renders an empty table for %j', (value) => {
148
+ const { field } = setup();
149
+ field.setProps({ value });
150
+ render(field.render());
151
+ expect(tableProps().dataSource).toEqual([]);
152
+ });
153
+
154
+ it('updates rows and resets pagination when the association changes or is cleared', async () => {
155
+ const { field, resource } = setup();
156
+ field.setProps({ value: [{ id: 1, name: 'Alice' }] });
157
+ const view = render(field.render());
158
+ await act(async () => {
159
+ const pagination = tableProps().pagination;
160
+ if (pagination) pagination.onChange?.(3, 10);
161
+ });
162
+ expect(tableProps().pagination).toMatchObject({ current: 3 });
163
+ act(() => {
164
+ field.setProps({ value: { rows: [{ id: 2, name: 'Bob' }] } });
165
+ view.rerender(field.render());
166
+ });
167
+ expect(screen.getByTestId('rows').textContent).toContain('Bob');
168
+ expect(screen.getByTestId('rows').textContent).not.toContain('Alice');
169
+ expect(tableProps().pagination).toMatchObject({ current: 1 });
170
+ act(() => {
171
+ field.setProps({ value: null });
172
+ view.rerender(field.render());
173
+ });
174
+ expect(tableProps().dataSource).toEqual([]);
175
+ expect(resource.refresh).not.toHaveBeenCalled();
176
+ });
177
+
178
+ it('sorts nested columns locally without mutating form values or refreshing the form resource', async () => {
179
+ const { field, resource } = setup();
180
+ const rows = [
181
+ { id: 1, name: 'Bob' },
182
+ { id: 2, name: 'Alice' },
183
+ ];
184
+ const original = structuredClone(rows);
185
+ field.setProps({ value: rows });
186
+ render(field.render());
187
+ await act(async () => {
188
+ await tableProps().onChange?.(
189
+ {},
190
+ {},
191
+ { field: 'org.staff.name', order: 'ascend' },
192
+ {
193
+ action: 'sort',
194
+ currentDataSource: rows,
195
+ },
196
+ );
197
+ });
198
+ expect(tableProps().dataSource).toEqual([rows[1], rows[0]]);
199
+ await act(async () => {
200
+ await tableProps().onChange?.(
201
+ {},
202
+ {},
203
+ { field: 'org.staff.name', order: 'descend' },
204
+ {
205
+ action: 'sort',
206
+ currentDataSource: rows,
207
+ },
208
+ );
209
+ });
210
+ expect(tableProps().dataSource).toEqual(rows);
211
+ await act(async () => {
212
+ await tableProps().onChange?.(
213
+ {},
214
+ {},
215
+ { field: 'org.staff.name' },
216
+ {
217
+ action: 'sort',
218
+ currentDataSource: rows,
219
+ },
220
+ );
221
+ });
222
+ expect(tableProps().dataSource).toEqual(rows);
223
+ expect(rows).toEqual(original);
224
+ expect(resource.setAppends).not.toHaveBeenCalled();
225
+ expect(resource.refresh).not.toHaveBeenCalled();
226
+ });
227
+
228
+ it('retains resource-based sorting in details fields', async () => {
229
+ const { field, resource } = setup('DetailsItemModel');
230
+ field.setProps({ value: [{ id: 1 }] });
231
+ render(field.render());
232
+ await act(async () => {
233
+ await tableProps().onChange?.(
234
+ {},
235
+ {},
236
+ { field: 'name', order: 'ascend' },
237
+ {
238
+ action: 'sort',
239
+ currentDataSource: [],
240
+ },
241
+ );
242
+ });
243
+ expect(resource.setAppends).toHaveBeenCalledWith(['staff(sort=name)']);
244
+ expect(resource.refresh).toHaveBeenCalledOnce();
245
+ });
246
+
247
+ it('uses the configured sort field and keeps local ordering when paginating', async () => {
248
+ const { field, resource } = setup();
249
+ const rows = [{ id: 10 }, { id: 2 }];
250
+ field.setProps({ value: rows });
251
+ render(field.render());
252
+ const column: NonNullable<TableOptions['columns']>[number] & { sortField: string } = {
253
+ sortField: 'org.staff.id',
254
+ };
255
+ await act(async () => {
256
+ await tableProps().onChange?.(
257
+ {},
258
+ {},
259
+ { field: 'other', column, order: 'ascend' },
260
+ {
261
+ action: 'sort',
262
+ currentDataSource: rows,
263
+ },
264
+ );
265
+ });
266
+ expect(tableProps().dataSource).toEqual([rows[1], rows[0]]);
267
+ await act(async () => {
268
+ await tableProps().onChange?.(
269
+ { current: 2 },
270
+ {},
271
+ {},
272
+ {
273
+ action: 'paginate',
274
+ currentDataSource: rows,
275
+ },
276
+ );
277
+ });
278
+ expect(tableProps().dataSource).toEqual([rows[1], rows[0]]);
279
+ expect(resource.refresh).not.toHaveBeenCalled();
280
+ });
281
+
282
+ it('follows form association changes without writing displayed records into the form', async () => {
283
+ vi.spyOn(window, 'matchMedia').mockImplementation((query) => ({
284
+ matches: false,
285
+ media: query,
286
+ onchange: null,
287
+ addListener: vi.fn(),
288
+ removeListener: vi.fn(),
289
+ addEventListener: vi.fn(),
290
+ removeEventListener: vi.fn(),
291
+ dispatchEvent: vi.fn(),
292
+ }));
293
+ const { engine, parent, resource } = setup();
294
+ let form: FormInstance;
295
+ const firstOrg = { id: 1, staff: [{ id: 1, name: 'Alice' }] };
296
+ const secondOrg = { id: 2, staff: [{ id: 2, name: 'Bob' }] };
297
+ function TestForm() {
298
+ const [formInstance] = Form.useForm();
299
+ form = formInstance;
300
+ parent.context.defineProperty('form', { value: formInstance });
301
+ parent.context.defineProperty('formValues', { get: () => formInstance.getFieldsValue(true), cache: false });
302
+ return (
303
+ <Form form={formInstance} initialValues={{ org: firstOrg, note: 'unsaved' }}>
304
+ <FlowModelProvider model={parent}>{parent.renderItem()}</FlowModelProvider>
305
+ </Form>
306
+ );
307
+ }
308
+ render(
309
+ <FlowEngineProvider engine={engine}>
310
+ <TestForm />
311
+ </FlowEngineProvider>,
312
+ );
313
+ await waitFor(() => expect(screen.getByTestId('rows').textContent).toContain('Alice'));
314
+ act(() => form.setFieldValue('org', secondOrg));
315
+ await waitFor(() => expect(screen.getByTestId('rows').textContent).toContain('Bob'));
316
+ expect(form.getFieldsValue(true)).toEqual({ org: secondOrg, note: 'unsaved' });
317
+ act(() => form.setFieldValue('org', null));
318
+ await waitFor(() => expect(tableProps().dataSource).toEqual([]));
319
+ expect(form.getFieldsValue(true)).toEqual({ org: null, note: 'unsaved' });
320
+ expect(resource.refresh).not.toHaveBeenCalled();
321
+ });
322
+
323
+ it('keeps nested column paths and column configuration when switching components', async () => {
324
+ const { parent, field } = setup();
325
+ vi.spyOn(parent, 'save').mockResolvedValue(undefined);
326
+ const column = field.addSubModel('columns', {
327
+ use: 'TableColumnModel',
328
+ stepParams: {
329
+ fieldSettings: {
330
+ init: { dataSourceKey: 'main', collectionName: 'posts', fieldPath: 'org.staff.name' },
331
+ },
332
+ },
333
+ subModels: { field: { use: 'DisplayTextFieldModel' } },
334
+ });
335
+ expect(field.context.prefixFieldPath).toBe('org.staff');
336
+ expect(field.collection.name).toBe('users');
337
+ const columnField = column.subModels.field as DisplayTextFieldModel;
338
+ const createFork = vi.spyOn(columnField, 'createFork');
339
+ (column as TableColumnModel).renderItem()(undefined, { id: 1, name: 'Alice' }, 0);
340
+ expect(createFork.mock.results[0].value.props.value).toBe('Alice');
341
+ expect(createFork.mock.results[0].value.context.record).toEqual({ id: 1, name: 'Alice' });
342
+ await rebuildFieldSubModel({ parentModel: parent, targetUse: 'DisplayTextFieldModel' });
343
+ await rebuildFieldSubModel({ parentModel: parent, targetUse: 'DisplaySubTableFieldModel' });
344
+ const rebuilt = parent.subModels.field as DisplaySubTableFieldModel;
345
+ expect(rebuilt.uid).toBe(field.uid);
346
+ expect(rebuilt.serialize().subModels.columns[0]).toMatchObject({
347
+ uid: column.uid,
348
+ stepParams: { fieldSettings: { init: { fieldPath: 'org.staff.name' } } },
349
+ });
350
+ });
351
+ });