@nocobase/client-v2 2.4.0-alpha.18 → 2.4.0-alpha.19

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,256 @@
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 { afterEach, describe, expect, it, vi } from 'vitest';
11
+ import { Collection, FlowEngine, MultiRecordResource, SingleRecordResource } from '@nocobase/flow-engine';
12
+ import { APIClient } from '@nocobase/sdk';
13
+ import MockAdapter from 'axios-mock-adapter';
14
+ import { DeleteActionModel } from '../DeleteActionModel';
15
+ import { BulkDeleteActionModel } from '../BulkDeleteActionModel';
16
+ import { parseQuery } from '../../../../../../resourcer/src/utils';
17
+
18
+ type RecordData = Record<string, unknown>;
19
+
20
+ function setup(single = false) {
21
+ const engine = new FlowEngine();
22
+ const resource = single ? engine.createResource(SingleRecordResource) : engine.createResource(MultiRecordResource);
23
+ const collection = new Collection({ name: 'users', filterTargetKey: ['code', 'staffname'] });
24
+ const ctx = {
25
+ record: { code: 'S1523968', staffname: 'Test user' } as RecordData,
26
+ resource,
27
+ blockModel: {
28
+ resource,
29
+ collection,
30
+ association: { type: 'hasMany', targetKey: 'code' } as { type: string; targetKey?: unknown } | undefined,
31
+ },
32
+ message: { success: vi.fn(), error: vi.fn(), warning: vi.fn() },
33
+ t: (value: string) => value,
34
+ };
35
+ const model = new DeleteActionModel({ uid: 'delete', flowEngine: engine });
36
+ const bulkModel = new BulkDeleteActionModel({ uid: 'bulk-delete', flowEngine: engine });
37
+ const handler = model.getFlow('deleteSettings').getStep('delete').serialize().handler;
38
+ const bulkHandler = bulkModel.getFlow('deleteSettings').getStep('delete').serialize().handler;
39
+ return {
40
+ ctx,
41
+ resource,
42
+ run: () => handler(ctx as Parameters<typeof handler>[0], {}),
43
+ runBulk: () => bulkHandler(ctx as Parameters<typeof bulkHandler>[0], {}),
44
+ };
45
+ }
46
+
47
+ afterEach(() => vi.restoreAllMocks());
48
+
49
+ describe('hasMany delete actions', () => {
50
+ it('uses the association target key when the collection has multiple identifier fields', async () => {
51
+ const { ctx, resource, run } = setup();
52
+ const destroy = vi.spyOn(resource, 'destroy').mockResolvedValue();
53
+ await run();
54
+ expect(destroy).toHaveBeenCalledWith('S1523968');
55
+ expect(ctx.message.success).toHaveBeenCalledOnce();
56
+ });
57
+
58
+ it('uses the association target key when the collection identifier is a different scalar', async () => {
59
+ const { ctx, resource, run } = setup();
60
+ ctx.blockModel.collection = new Collection({ name: 'users', filterTargetKey: 'staffname' });
61
+ const destroy = vi.spyOn(resource, 'destroy').mockResolvedValue();
62
+ await run();
63
+ expect(destroy).toHaveBeenCalledWith('S1523968');
64
+ });
65
+
66
+ it('supports uppercase target keys', async () => {
67
+ const { ctx, resource, run } = setup();
68
+ ctx.blockModel.association.targetKey = 'ID';
69
+ ctx.record = { ID: 'A' };
70
+ const destroy = vi.spyOn(resource, 'destroy').mockResolvedValue();
71
+ await run();
72
+ expect(destroy).toHaveBeenCalledWith('A');
73
+ });
74
+
75
+ it.each([0, '0', 42, '9223372036854775807'])('preserves target key %s', async (value) => {
76
+ const { ctx, resource, run } = setup();
77
+ ctx.record.code = value;
78
+ const destroy = vi.spyOn(resource, 'destroy').mockResolvedValue();
79
+ await run();
80
+ expect(destroy).toHaveBeenCalledWith(value);
81
+ });
82
+
83
+ it.each([undefined, null, '', {}, [], false, NaN, Infinity])('rejects invalid target value %s', async (value) => {
84
+ const { ctx, resource, run } = setup();
85
+ ctx.record.code = value;
86
+ const destroy = vi.spyOn(resource, 'destroy').mockResolvedValue();
87
+ await run();
88
+ expect(destroy).not.toHaveBeenCalled();
89
+ expect(ctx.message.error).toHaveBeenCalledWith('The association target key is missing or invalid.');
90
+ expect(ctx.message.success).not.toHaveBeenCalled();
91
+ });
92
+
93
+ it('rejects missing association target key metadata', async () => {
94
+ const { ctx, resource, run } = setup();
95
+ ctx.blockModel.association.targetKey = undefined;
96
+ const destroy = vi.spyOn(resource, 'destroy').mockResolvedValue();
97
+ await run();
98
+ expect(destroy).not.toHaveBeenCalled();
99
+ expect(ctx.message.error).toHaveBeenCalledOnce();
100
+ });
101
+
102
+ it.each([undefined, 'belongsToMany', 'hasOne', 'belongsTo'])('preserves identifiers for %s', async (type) => {
103
+ const { ctx, resource, run } = setup();
104
+ ctx.blockModel.association = type ? { type, targetKey: 'code' } : undefined;
105
+ const destroy = vi.spyOn(resource, 'destroy').mockResolvedValue();
106
+ await run();
107
+ expect(destroy).toHaveBeenCalledWith(ctx.record);
108
+ });
109
+
110
+ it('preserves the existing call for a non-hasMany single record resource', async () => {
111
+ const { ctx, resource, run } = setup(true);
112
+ ctx.blockModel.association = undefined;
113
+ const destroy = vi.spyOn(resource, 'destroy').mockResolvedValue();
114
+ await run();
115
+ expect(destroy).toHaveBeenCalledWith(ctx.record);
116
+ });
117
+
118
+ it.each([false, true])('serializes a scalar URL with singleRecord=%s', async (single) => {
119
+ const { ctx, resource, run } = setup(single);
120
+ const api = new APIClient({ baseURL: 'http://localhost/api/' });
121
+ const mock = new MockAdapter(api.axios);
122
+ mock.onPost('orgs/110013/users:destroy').reply(200, { data: true });
123
+ resource.setAPIClient(api).setResourceName('orgs.users').setSourceId('110013');
124
+ resource.setFilterByTk(ctx.record);
125
+ vi.spyOn(resource, 'refresh').mockResolvedValue();
126
+ try {
127
+ await run();
128
+ expect(mock.history.post).toHaveLength(1);
129
+ const url = new URL(api.axios.getUri(mock.history.post[0]));
130
+ expect(url.pathname).toBe('/api/orgs/110013/users:destroy');
131
+ expect(url.searchParams.get('filterByTk')).toBe('S1523968');
132
+ expect(url.searchParams.has('filterByTk[code]')).toBe(false);
133
+ expect(ctx.message.success).toHaveBeenCalledOnce();
134
+ } finally {
135
+ mock.restore();
136
+ }
137
+ });
138
+
139
+ describe.each([false, true])('literal hasMany keys with singleRecord=%s', (single) => {
140
+ it.each([
141
+ '["A","B"]',
142
+ '{"code":"A"}',
143
+ '{"0":"A","1":"B"}',
144
+ '[]',
145
+ '{}',
146
+ ' \n ["A","B"] \t',
147
+ '[not JSON',
148
+ '{not JSON',
149
+ '["中文 & + %", "B"]',
150
+ ])('preserves %s through server query parsing', async (key) => {
151
+ const { ctx, resource, run } = setup(single);
152
+ ctx.record.code = key;
153
+ const api = new APIClient({ baseURL: 'http://localhost/api/' });
154
+ const mock = new MockAdapter(api.axios);
155
+ mock.onPost('orgs/110013/users:destroy').reply(200, { data: true });
156
+ resource.setAPIClient(api).setResourceName('orgs.users').setSourceId('110013');
157
+ resource.setFilterByTk(ctx.record);
158
+ vi.spyOn(resource, 'refresh').mockResolvedValue();
159
+ try {
160
+ await run();
161
+ expect(mock.history.post).toHaveLength(1);
162
+ const config = mock.history.post[0];
163
+ const paramsSerializer =
164
+ typeof config.paramsSerializer === 'function'
165
+ ? { serialize: config.paramsSerializer }
166
+ : config.paramsSerializer;
167
+ const url = new URL(api.axios.getUri({ ...config, paramsSerializer }));
168
+ expect(url.pathname).toBe('/api/orgs/110013/users:destroy');
169
+ expect(parseQuery(url.search.slice(1)).filterByTk).toEqual([key]);
170
+ expect(ctx.message.success).toHaveBeenCalledOnce();
171
+ } finally {
172
+ mock.restore();
173
+ }
174
+ });
175
+ });
176
+
177
+ it.each([undefined, 'belongsToMany', 'hasOne', 'belongsTo'])(
178
+ 'does not wrap scalar keys outside hasMany: %s',
179
+ async (type) => {
180
+ const { ctx, resource, run } = setup();
181
+ ctx.blockModel.association = type ? { type, targetKey: 'code' } : undefined;
182
+ ctx.blockModel.collection = new Collection({ name: 'users', filterTargetKey: 'code' });
183
+ ctx.record.code = '["A","B"]';
184
+ const destroy = vi.spyOn(resource, 'destroy').mockResolvedValue();
185
+ await run();
186
+ expect(destroy).toHaveBeenCalledWith('["A","B"]');
187
+ },
188
+ );
189
+
190
+ it('preserves special string elements in a hasMany bulk request', async () => {
191
+ const { resource, runBulk } = setup();
192
+ const keys = ['["A","B"]', '{"code":"A"}'];
193
+ (resource as MultiRecordResource).setSelectedRows(keys.map((code) => ({ code })));
194
+ const api = new APIClient({ baseURL: 'http://localhost/api/' });
195
+ const mock = new MockAdapter(api.axios);
196
+ mock.onPost('orgs/110013/users:destroy').reply(200, { data: true });
197
+ resource.setAPIClient(api).setResourceName('orgs.users').setSourceId('110013');
198
+ vi.spyOn(resource, 'refresh').mockResolvedValue();
199
+ try {
200
+ await runBulk();
201
+ expect(mock.history.post).toHaveLength(1);
202
+ const config = mock.history.post[0];
203
+ const paramsSerializer =
204
+ typeof config.paramsSerializer === 'function'
205
+ ? { serialize: config.paramsSerializer }
206
+ : config.paramsSerializer;
207
+ const url = new URL(api.axios.getUri({ ...config, paramsSerializer }));
208
+ expect(parseQuery(url.search.slice(1)).filterByTk).toEqual(keys);
209
+ } finally {
210
+ mock.restore();
211
+ }
212
+ });
213
+
214
+ it('sends scalar target keys for selected hasMany records', async () => {
215
+ const { resource, runBulk } = setup();
216
+ const rows = [
217
+ { code: 'A', staffname: 'a' },
218
+ { code: 'B', staffname: 'b' },
219
+ ];
220
+ (resource as MultiRecordResource).setSelectedRows(rows);
221
+ const destroy = vi.spyOn(resource, 'destroy').mockResolvedValue();
222
+ await runBulk();
223
+ expect(destroy).toHaveBeenCalledWith(['A', 'B']);
224
+ });
225
+
226
+ it('rejects the entire batch when one selected row has no target key', async () => {
227
+ const { ctx, resource, runBulk } = setup();
228
+ (resource as MultiRecordResource).setSelectedRows([{ code: 'A' }, { staffname: 'b' }]);
229
+ const destroy = vi.spyOn(resource, 'destroy').mockResolvedValue();
230
+ await runBulk();
231
+ expect(destroy).not.toHaveBeenCalled();
232
+ expect(ctx.message.error).toHaveBeenCalledOnce();
233
+ expect(ctx.message.success).not.toHaveBeenCalled();
234
+ });
235
+
236
+ it('preserves collection identifiers for other bulk deletion', async () => {
237
+ const { ctx, resource, runBulk } = setup();
238
+ ctx.blockModel.association = { type: 'belongsToMany', targetKey: 'code' };
239
+ const rows = [
240
+ { code: 'A', staffname: 'a' },
241
+ { code: 'B', staffname: 'b' },
242
+ ];
243
+ (resource as MultiRecordResource).setSelectedRows(rows);
244
+ const destroy = vi.spyOn(resource, 'destroy').mockResolvedValue();
245
+ await runBulk();
246
+ expect(destroy).toHaveBeenCalledWith(rows);
247
+ });
248
+
249
+ it('does not delete an empty selection', async () => {
250
+ const { ctx, resource, runBulk } = setup();
251
+ const destroy = vi.spyOn(resource, 'destroy').mockResolvedValue();
252
+ await runBulk();
253
+ expect(destroy).not.toHaveBeenCalled();
254
+ expect(ctx.message.warning).toHaveBeenCalledOnce();
255
+ });
256
+ });
@@ -0,0 +1,40 @@
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
+ type RecordData = Record<string, unknown>;
11
+ type TargetValue = string | number;
12
+
13
+ // hasMany destroy identifies rows by the association target key, not the collection filterTargetKey.
14
+ export function getHasManyDeleteFilterByTk(
15
+ targetKey: unknown,
16
+ records: RecordData | RecordData[],
17
+ ): TargetValue | TargetValue[] | undefined {
18
+ if (typeof targetKey !== 'string' || !targetKey) {
19
+ return undefined;
20
+ }
21
+ const rows = Array.isArray(records) ? records : [records];
22
+ const values: TargetValue[] = [];
23
+ for (const row of rows) {
24
+ const value = row?.[targetKey];
25
+ if (
26
+ (typeof value !== 'string' && typeof value !== 'number') ||
27
+ value === '' ||
28
+ (typeof value === 'number' && !Number.isFinite(value))
29
+ ) {
30
+ return undefined;
31
+ }
32
+ values.push(value);
33
+ }
34
+ if (Array.isArray(records)) {
35
+ return values;
36
+ }
37
+ const value = values[0];
38
+ // Preserve JSON-like string keys as one value when the server parses filterByTk.
39
+ return typeof value === 'string' && ['[', '{'].includes(value.trimStart()[0]) ? [value] : value;
40
+ }
@@ -7,33 +7,48 @@
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
9
 
10
- import { FlowModel, FlowModelRenderer, observable, type ParamObject, tExpr } from '@nocobase/flow-engine';
10
+ import { observer } from '@formily/reactive-react';
11
+ import { loadRouteContentForEditing } from '../../../FlowModelRepository';
12
+ import {
13
+ type CreateModelOptions,
14
+ FlowModel,
15
+ FlowModelRenderer,
16
+ observable,
17
+ type ParamObject,
18
+ tExpr,
19
+ } from '@nocobase/flow-engine';
11
20
  import { Icon, type NocoBaseDesktopRoute } from '../../../../flow-compat';
12
21
  import type { RouteRepository } from '../../../../RouteRepository';
13
- import { useRequest } from 'ahooks';
22
+ import { RouteContent, useRouteContentRequest } from '../../../useRouteContentRequest';
14
23
  import _ from 'lodash';
15
24
  import React from 'react';
16
25
  import { SkeletonFallback } from '../../../components/SkeletonFallback';
17
26
  import { TextAreaWithContextSelector } from '../../../components/TextAreaWithContextSelector';
18
27
  import { BlockGridModel } from '../BlockGridModel';
19
28
 
20
- function PageTabChildrenRenderer({ ctx, options }) {
21
- const { data, loading } = useRequest(
22
- async () => {
23
- const model: FlowModel = await ctx.engine.loadOrCreateModel(options, { skipSave: !ctx.flowSettingsEnabled });
29
+ const PageTabChildrenRenderer = observer(({ ctx, options }: PageTabChildrenProps) => {
30
+ const isRoute = ctx.model instanceof RootPageTabModel && ctx.model.props.route?.id != null;
31
+ const { model, loading, error, needsConfirmation } = useRouteContentRequest(
32
+ async (forEditing) => {
33
+ const model = forEditing
34
+ ? await loadRouteContentForEditing(ctx.engine, options)
35
+ : await ctx.engine.loadOrCreateModel(options, { skipSave: isRoute || !ctx.flowSettingsEnabled });
24
36
  model.context.addDelegate(ctx);
25
37
  return model;
26
38
  },
27
- {
28
- refreshDeps: [ctx.model.uid],
29
- },
39
+ isRoute && ctx.flowSettingsEnabled,
40
+ [ctx.model.uid],
30
41
  );
42
+ if (error && isRoute) throw error;
31
43
  const margin = ctx?.isMobileLayout ? 8 : ctx?.themeToken.marginBlock;
32
- if (loading || !data?.uid) {
44
+ if (!model?.uid || (loading && !isRoute)) {
33
45
  return <SkeletonFallback style={{ margin }} />;
34
46
  }
35
- return <FlowModelRenderer model={data} fallback={<SkeletonFallback style={{ margin }} />} />;
36
- }
47
+ const grid = <FlowModelRenderer model={model} fallback={<SkeletonFallback style={{ margin }} />} />;
48
+ return isRoute ? <RouteContent pending={needsConfirmation}>{grid}</RouteContent> : grid;
49
+ });
50
+
51
+ type PageTabChildrenProps = { ctx: FlowModel['context']; options: CreateModelOptions };
37
52
 
38
53
  /**
39
54
  * 统一归一化 `desktopRoutes:updateOrCreate` 的返回值。
@@ -7,6 +7,7 @@
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
9
 
10
+ import { css, cx } from '@emotion/css';
10
11
  import {
11
12
  Collection,
12
13
  DisplayItemModel,
@@ -14,6 +15,8 @@ import {
14
15
  FieldModelRenderer,
15
16
  FlowModelContext,
16
17
  FormItem,
18
+ formItemStyle,
19
+ untracked,
17
20
  } from '@nocobase/flow-engine';
18
21
  import { get, castArray } from 'lodash';
19
22
  import React from 'react';
@@ -22,6 +25,49 @@ import { DetailsGridModel } from './DetailsGridModel';
22
25
  import { rebuildFieldSubModel } from '../../../internal/utils/rebuildFieldSubModel';
23
26
  import { isToManyAssociationField } from '../../../internal/utils/modelUtils';
24
27
 
28
+ function mobileHorizontalItemStyle(marginBottom: number) {
29
+ return css`
30
+ &&.ant-form-item {
31
+ margin-bottom: ${formItemStyle.marginBottom}px;
32
+
33
+ @media (max-width: 575px) {
34
+ margin-bottom: ${marginBottom}px;
35
+ min-height: ${32 - marginBottom}px;
36
+
37
+ > .ant-form-item-row > .ant-form-item-label {
38
+ padding-bottom: 0;
39
+ line-height: max(20px, 1.4em);
40
+
41
+ > label {
42
+ height: auto;
43
+ line-height: max(20px, 1.4em);
44
+ }
45
+ }
46
+
47
+ > .ant-form-item-row > .ant-form-item-control > .ant-form-item-control-input {
48
+ min-height: 20px;
49
+ }
50
+ }
51
+ }
52
+ `;
53
+ }
54
+
55
+ const mobileSpacingByBlock = new Map([
56
+ ['DetailsBlockModel', mobileHorizontalItemStyle(3)],
57
+ ['GridCardBlockModel', mobileHorizontalItemStyle(8)],
58
+ ]);
59
+
60
+ const mobilePlainTextStyle = css`
61
+ @media (max-width: 575px) {
62
+ > .ant-form-item-row
63
+ > .ant-form-item-control
64
+ > .ant-form-item-control-input
65
+ > .ant-form-item-control-input-content {
66
+ line-height: max(20px, 1.4em);
67
+ }
68
+ }
69
+ `;
70
+
25
71
  /**
26
72
  * 从 record 中取值
27
73
  * @param record 当前行数据
@@ -217,8 +263,23 @@ export class DetailsItemModel extends DisplayItemModel<{
217
263
  idx,
218
264
  }),
219
265
  );
266
+ const spacing =
267
+ this.context.isMobileLayout && mergedProps.layout === 'horizontal'
268
+ ? mobileSpacingByBlock.get(this.context.blockModel.use)
269
+ : undefined;
270
+ const isPlainText =
271
+ spacing &&
272
+ modelForRender?.use === 'DisplayTextFieldModel' &&
273
+ (mergedProps.displayStyle ??
274
+ fieldModel.getStepParams('displayFieldSettings', 'displayStyle')?.displayStyle ??
275
+ // FieldModelRenderer writes back fork props after rendering. Subscribing here would render the item again.
276
+ untracked(() => modelForRender.props.displayStyle)) !== 'tag';
220
277
  return (
221
- <FormItem {...mergedProps} value={value}>
278
+ <FormItem
279
+ {...mergedProps}
280
+ itemMarginClassName={spacing && cx(spacing, isPlainText && mobilePlainTextStyle)}
281
+ value={value}
282
+ >
222
283
  <FieldModelRenderer model={modelForRender} />
223
284
  </FormItem>
224
285
  );
@@ -0,0 +1,77 @@
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 { FlowEngine, FlowModel, Tracker } from '@nocobase/flow-engine';
11
+ import { render } from '@testing-library/react';
12
+ import React from 'react';
13
+ import { expect, it, vi } from 'vitest';
14
+ import { DetailsItemModel } from '../DetailsItemModel';
15
+
16
+ it.each([
17
+ ['DetailsBlockModel', true, 'horizontal', 'DisplayTextFieldModel', 'text', '3px', '29px', true],
18
+ ['GridCardBlockModel', true, 'horizontal', 'DisplayTextFieldModel', 'text', '8px', '24px', true],
19
+ ['GridCardBlockModel', true, 'horizontal', 'DisplayTextFieldModel', 'tag', '8px', '24px', false],
20
+ ['DetailsBlockModel', true, 'horizontal', 'DisplayHtmlFieldModel', 'text', '3px', '29px', false],
21
+ ['CCTaskCardDetailsModel', true, 'horizontal', 'DisplayTextFieldModel', 'text', '', '', false],
22
+ ['DetailsBlockModel', false, 'horizontal', 'DisplayTextFieldModel', 'text', '', '', false],
23
+ ['GridCardBlockModel', true, 'vertical', 'DisplayTextFieldModel', 'text', '', '', false],
24
+ ] as const)(
25
+ 'selects phone styles for %s, mobile=%s, %s, %s (%s)',
26
+ (block, mobile, layout, field, displayStyle, margin, minHeight, plainText) => {
27
+ const engine = new FlowEngine();
28
+ engine.registerModels({ [field]: FlowModel });
29
+ const model = new DetailsItemModel({ uid: 'detail-field', flowEngine: engine });
30
+ model.context.defineProperty('blockModel', { value: { use: block, props: { layout } } });
31
+ model.context.defineProperty('isMobileLayout', { value: mobile });
32
+ model.setProps('label', 'Name');
33
+ model.setStepParams('fieldSettings', 'init', { fieldPath: 'name' });
34
+ model.setSubModel('field', { use: field, props: { displayStyle } });
35
+
36
+ const { container } = render(React.cloneElement(model.renderItem(), {}, <span>Value</span>));
37
+ const item = container.querySelector<HTMLElement>('.ant-form-item');
38
+ const value = item.querySelector('.ant-form-item-control-input-content');
39
+ const rules = Array.from(document.styleSheets).flatMap((sheet) => Array.from(sheet.cssRules));
40
+ const narrowRules = rules.flatMap((rule) =>
41
+ rule instanceof CSSMediaRule && rule.conditionText === '(max-width: 575px)' ? Array.from(rule.cssRules) : [],
42
+ );
43
+ const declarations = (element: Element, property: string) =>
44
+ narrowRules
45
+ .flatMap((rule) =>
46
+ rule instanceof CSSStyleRule && element.matches(rule.selectorText)
47
+ ? [rule.style.getPropertyValue(property)]
48
+ : [],
49
+ )
50
+ .filter(Boolean);
51
+
52
+ expect(item.style.marginBottom).toBe(margin ? '' : '12px');
53
+ expect(declarations(item, 'margin-bottom')).toEqual(margin ? [margin] : []);
54
+ expect(declarations(item, 'min-height')).toEqual(minHeight ? [minHeight] : []);
55
+ expect(declarations(value, 'line-height')).toEqual(plainText ? ['max(20px, 1.4em)'] : []);
56
+ },
57
+ );
58
+
59
+ it('does not subscribe the grid card item to field renderer prop writes', () => {
60
+ const engine = new FlowEngine();
61
+ engine.registerModels({ DisplayTextFieldModel: FlowModel });
62
+ const item = new DetailsItemModel({ uid: 'card-field', flowEngine: engine });
63
+ item.context.defineProperty('blockModel', { value: { use: 'GridCardBlockModel', props: { layout: 'horizontal' } } });
64
+ item.context.defineProperty('isMobileLayout', { value: true });
65
+ item.context.defineProperty('fieldIndex', { value: 0 });
66
+ item.setStepParams('fieldSettings', 'init', { fieldPath: 'name' });
67
+ const field = item.setSubModel('field', { use: 'DisplayTextFieldModel' });
68
+ const invalidate = vi.fn();
69
+ const tracker = new Tracker(invalidate);
70
+ try {
71
+ tracker.track(() => item.renderItem());
72
+ field.getFork('0').setProps({ value: 'First row' });
73
+ expect(invalidate).not.toHaveBeenCalled();
74
+ } finally {
75
+ tracker.dispose();
76
+ }
77
+ });
@@ -0,0 +1,42 @@
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 { useRequest } from 'ahooks';
11
+ import type { FlowModel } from '@nocobase/flow-engine';
12
+ import React, { useEffect } from 'react';
13
+ import { isRouteContentConfirmed } from './FlowModelRepository';
14
+
15
+ // Keep the current renderer mounted while the first editor confirms the stored page or grid.
16
+ export function useRouteContentRequest(
17
+ load: (forEditing: boolean) => Promise<FlowModel>,
18
+ editing: boolean,
19
+ refreshDeps: unknown[],
20
+ ) {
21
+ const { data, error, loading, refresh } = useRequest(
22
+ async () => ({ model: await load(editing), confirmed: editing, refreshDeps }),
23
+ { refreshDeps },
24
+ );
25
+ const current = data && refreshDeps.every((dep, i) => Object.is(dep, data.refreshDeps[i])) ? data : undefined;
26
+ const needsConfirmation =
27
+ editing && !!current?.model && !current.confirmed && !isRouteContentConfirmed(current.model);
28
+ useEffect(() => {
29
+ if (needsConfirmation && !loading && !error) refresh();
30
+ }, [needsConfirmation, loading, error, refresh]);
31
+
32
+ return { model: current?.model, error, loading, needsConfirmation };
33
+ }
34
+
35
+ export function RouteContent({ pending, children }: React.PropsWithChildren<{ pending: boolean }>) {
36
+ // React 18 forwards inert as a string attribute. Keep the same DOM and component state during initialization.
37
+ return (
38
+ <div style={{ display: 'contents' }} {...(pending ? { inert: '' } : {})}>
39
+ {children}
40
+ </div>
41
+ );
42
+ }