@nocobase/client-v2 2.1.0-beta.27 → 2.1.0-beta.30

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.
Files changed (68) hide show
  1. package/es/components/form/JsonTextArea.d.ts +18 -0
  2. package/es/components/index.d.ts +1 -0
  3. package/es/flow/actions/dateRangeLimit.d.ts +9 -0
  4. package/es/flow/actions/index.d.ts +2 -1
  5. package/es/flow/actions/linkageRules.d.ts +2 -0
  6. package/es/flow/admin-shell/admin-layout/AdminLayoutMenuModels.d.ts +4 -0
  7. package/es/flow/admin-shell/admin-layout/AdminLayoutModel.d.ts +7 -0
  8. package/es/flow/admin-shell/admin-layout/resolveAdminRouteRuntimeTarget.d.ts +5 -0
  9. package/es/flow/models/base/PageModel/PageModel.d.ts +4 -0
  10. package/es/flow/models/base/PageModel/RootPageModel.d.ts +9 -0
  11. package/es/flow/models/blocks/form/value-runtime/runtime.d.ts +7 -0
  12. package/es/flow/models/fields/AssociationFieldModel/SubTableFieldModel/SubTableColumnModel.d.ts +5 -0
  13. package/es/flow/models/fields/DateTimeFieldModel/dateLimit.d.ts +20 -0
  14. package/es/flow/models/fields/JSEditableFieldModel.d.ts +4 -0
  15. package/es/index.mjs +79 -67
  16. package/lib/index.js +80 -68
  17. package/package.json +6 -5
  18. package/src/__tests__/nocobase-buildin-plugin-auth.test.tsx +67 -46
  19. package/src/__tests__/settings-center.test.tsx +30 -0
  20. package/src/components/form/JsonTextArea.tsx +129 -0
  21. package/src/components/index.ts +1 -0
  22. package/src/flow/__tests__/FlowRoute.test.tsx +4 -5
  23. package/src/flow/actions/__tests__/actionLinkageRules.race.repro.test.ts +199 -0
  24. package/src/flow/actions/__tests__/fieldLinkageRules.scopeDepth.test.ts +478 -0
  25. package/src/flow/actions/__tests__/linkageRules.formValueDrivenRefresh.test.ts +6 -1
  26. package/src/flow/actions/__tests__/linkageRules.menu.test.ts +90 -0
  27. package/src/flow/actions/__tests__/pattern.test.ts +190 -0
  28. package/src/flow/actions/dateRangeLimit.tsx +66 -0
  29. package/src/flow/actions/index.ts +3 -0
  30. package/src/flow/actions/linkageRules.tsx +194 -42
  31. package/src/flow/actions/linkageRulesFormValueRefresh.ts +2 -8
  32. package/src/flow/actions/openView.tsx +2 -1
  33. package/src/flow/actions/pattern.tsx +25 -2
  34. package/src/flow/admin-shell/AdminLayoutRouteCoordinator.ts +7 -1
  35. package/src/flow/admin-shell/__tests__/AdminLayoutRouteCoordinator.test.ts +117 -0
  36. package/src/flow/admin-shell/admin-layout/AdminLayoutComponent.tsx +8 -1
  37. package/src/flow/admin-shell/admin-layout/AdminLayoutMenuModels.tsx +70 -12
  38. package/src/flow/admin-shell/admin-layout/AdminLayoutMenuUtils.tsx +26 -87
  39. package/src/flow/admin-shell/admin-layout/AdminLayoutModel.tsx +11 -0
  40. package/src/flow/admin-shell/admin-layout/AdminLayoutSlotModels.tsx +5 -1
  41. package/src/flow/admin-shell/admin-layout/__tests__/AdminLayoutMenuModels.test.ts +292 -31
  42. package/src/flow/admin-shell/admin-layout/resolveAdminRouteRuntimeTarget.test.ts +50 -12
  43. package/src/flow/admin-shell/admin-layout/resolveAdminRouteRuntimeTarget.ts +77 -56
  44. package/src/flow/components/AdminLayout.tsx +2 -2
  45. package/src/flow/components/FlowRoute.tsx +17 -4
  46. package/src/flow/models/base/PageModel/PageModel.tsx +15 -3
  47. package/src/flow/models/base/PageModel/RootPageModel.tsx +37 -2
  48. package/src/flow/models/base/PageModel/__tests__/PageModel.test.ts +73 -0
  49. package/src/flow/models/base/PageModel/__tests__/RootPageModel.test.ts +116 -0
  50. package/src/flow/models/blocks/form/value-runtime/__tests__/runtime.test.ts +167 -1
  51. package/src/flow/models/blocks/form/value-runtime/runtime.ts +103 -11
  52. package/src/flow/models/fields/AssociationFieldModel/PopupSubTableFieldModel/PopupSubTableFieldModel.tsx +4 -0
  53. package/src/flow/models/fields/AssociationFieldModel/SubTableFieldModel/SubTableColumnModel.tsx +34 -3
  54. package/src/flow/models/fields/AssociationFieldModel/SubTableFieldModel/SubTableField.tsx +47 -0
  55. package/src/flow/models/fields/AssociationFieldModel/SubTableFieldModel/__tests__/SubTableColumnModel.rowRecord.test.ts +42 -0
  56. package/src/flow/models/fields/AssociationFieldModel/SubTableFieldModel/__tests__/SubTableField.refresh.test.tsx +122 -0
  57. package/src/flow/models/fields/AssociationFieldModel/SubTableFieldModel/index.tsx +6 -1
  58. package/src/flow/models/fields/ClickableFieldModel.tsx +21 -9
  59. package/src/flow/models/fields/DateTimeFieldModel/DateOnlyFieldModel.tsx +9 -0
  60. package/src/flow/models/fields/DateTimeFieldModel/DateTimeFieldModel.tsx +4 -0
  61. package/src/flow/models/fields/DateTimeFieldModel/DateTimeNoTzFieldModel.tsx +9 -0
  62. package/src/flow/models/fields/DateTimeFieldModel/DateTimeTzFieldModel.tsx +9 -0
  63. package/src/flow/models/fields/DateTimeFieldModel/__tests__/DateTimeNoTzFieldModel.dateLimit.test.tsx +242 -0
  64. package/src/flow/models/fields/DateTimeFieldModel/dateLimit.ts +152 -0
  65. package/src/flow/models/fields/JSEditableFieldModel.tsx +110 -14
  66. package/src/flow/models/fields/__tests__/ClickableFieldModel.test.ts +87 -0
  67. package/src/flow/models/fields/__tests__/JSEditableFieldModel.test.tsx +210 -0
  68. package/src/flow/system-settings/useSystemSettings.tsx +36 -1
@@ -159,12 +159,141 @@ describe('FormValueRuntime (default rules)', () => {
159
159
  await runtime.setFormValues(fieldCtx, [{ path: ['b'], value: 'Y' }], { source: 'user' });
160
160
  await waitFor(() => expect(formStub.getFieldValue(['a'])).toBe('Y'));
161
161
 
162
+ // change dependency again -> default keeps following while target is still the last default
163
+ await runtime.setFormValues(fieldCtx, [{ path: ['b'], value: 'Z' }], { source: 'user' });
164
+ await waitFor(() => expect(formStub.getFieldValue(['a'])).toBe('Z'));
165
+
162
166
  // user changes target -> default should be disabled permanently
163
167
  await runtime.setFormValues(fieldCtx, [{ path: ['a'], value: 'user' }], { source: 'user' });
164
- await runtime.setFormValues(fieldCtx, [{ path: ['b'], value: 'Z' }], { source: 'user' });
168
+ await runtime.setFormValues(fieldCtx, [{ path: ['b'], value: 'W' }], { source: 'user' });
165
169
  expect(formStub.getFieldValue(['a'])).toBe('user');
166
170
  });
167
171
 
172
+ it('allows direct default patches to keep following until target is explicitly changed', async () => {
173
+ const engineEmitter = new EventEmitter();
174
+ const blockEmitter = new EventEmitter();
175
+ const formStub = createFormStub({ roleUid: 'role-uid-1', roleName: '' });
176
+
177
+ const blockModel: any = {
178
+ uid: 'form-direct-default-patch',
179
+ flowEngine: { emitter: engineEmitter },
180
+ emitter: blockEmitter,
181
+ dispatchEvent: vi.fn(),
182
+ getAclActionName: () => 'create',
183
+ };
184
+
185
+ const runtime = new FormValueRuntime({ model: blockModel, getForm: () => formStub as any });
186
+ runtime.mount({ sync: true });
187
+
188
+ const blockCtx = createFieldContext(runtime);
189
+ blockModel.context = blockCtx;
190
+
191
+ expect(runtime.canApplyDefaultValuePatch(['roleName'], 'role-uid-1')).toBe(true);
192
+ await runtime.setFormValues(blockCtx, [{ path: ['roleName'], value: 'role-uid-1' }], {
193
+ source: 'linkage',
194
+ txId: 'tx-linkage-1',
195
+ linkageTxId: 'tx-linkage-1',
196
+ });
197
+ runtime.recordDefaultValuePatch(['roleName'], 'role-uid-1');
198
+
199
+ await runtime.setFormValues(blockCtx, [{ path: ['roleUid'], value: 'role-uid-2' }], { source: 'user' });
200
+ expect(runtime.canApplyDefaultValuePatch(['roleName'], 'role-uid-2')).toBe(true);
201
+ await runtime.setFormValues(blockCtx, [{ path: ['roleName'], value: 'role-uid-2' }], {
202
+ source: 'linkage',
203
+ txId: 'tx-linkage-2',
204
+ linkageTxId: 'tx-linkage-2',
205
+ });
206
+ runtime.recordDefaultValuePatch(['roleName'], 'role-uid-2');
207
+
208
+ await runtime.setFormValues(blockCtx, [{ path: ['roleUid'], value: 'role-uid-3' }], { source: 'user' });
209
+ expect(runtime.canApplyDefaultValuePatch(['roleName'], 'role-uid-3')).toBe(true);
210
+
211
+ await runtime.setFormValues(blockCtx, [{ path: ['roleName'], value: 'manual' }], { source: 'user' });
212
+ expect(runtime.canApplyDefaultValuePatch(['roleName'], 'role-uid-4')).toBe(false);
213
+ });
214
+
215
+ it('keeps direct default patches active when an unchanged default value is carried by a row change', async () => {
216
+ const engineEmitter = new EventEmitter();
217
+ const blockEmitter = new EventEmitter();
218
+ const formStub = createFormStub({ roles: [{ uid: '1', title: '' }] });
219
+
220
+ const blockModel: any = {
221
+ uid: 'form-direct-default-patch-row',
222
+ flowEngine: { emitter: engineEmitter },
223
+ emitter: blockEmitter,
224
+ dispatchEvent: vi.fn(),
225
+ getAclActionName: () => 'create',
226
+ };
227
+
228
+ const runtime = new FormValueRuntime({ model: blockModel, getForm: () => formStub as any });
229
+ runtime.mount({ sync: true });
230
+
231
+ const blockCtx = createFieldContext(runtime);
232
+ blockModel.context = blockCtx;
233
+
234
+ expect(runtime.canApplyDefaultValuePatch(['roles', 0, 'title'], '1')).toBe(true);
235
+ await runtime.setFormValues(blockCtx, [{ path: ['roles', 0, 'title'], value: '1' }], {
236
+ source: 'linkage',
237
+ txId: 'tx-linkage-row-1',
238
+ linkageTxId: 'tx-linkage-row-1',
239
+ });
240
+ runtime.recordDefaultValuePatch(['roles', 0, 'title'], '1');
241
+
242
+ lodashSet((runtime as any).valuesMirror, ['roles', 0, 'title'], undefined);
243
+ runtime.handleFormFieldsChange([{ name: ['roles', 0, 'title'], touched: true } as any]);
244
+ expect((runtime as any).findExplicitHit('roles[0].title')).toBeNull();
245
+ expect(runtime.canApplyDefaultValuePatch(['roles', 0, 'title'], '12')).toBe(true);
246
+
247
+ (runtime as any).markExplicit('roles');
248
+ expect((runtime as any).findExplicitHit('roles[0].title')).toBeNull();
249
+ expect(runtime.canApplyDefaultValuePatch(['roles', 0, 'title'], '12')).toBe(true);
250
+
251
+ lodashSet((runtime as any).valuesMirror, ['roles', 0, 'title'], undefined);
252
+
253
+ lodashSet((formStub as any).__store, ['roles', 0, 'uid'], '12');
254
+ runtime.handleFormValuesChange({ roles: formStub.getFieldValue(['roles']) }, formStub.getFieldsValue());
255
+
256
+ expect((runtime as any).findExplicitHit('roles[0].title')).toBeNull();
257
+ expect(runtime.canApplyDefaultValuePatch(['roles', 0, 'title'], '12')).toBe(true);
258
+ await runtime.setFormValues(blockCtx, [{ path: ['roles', 0, 'title'], value: '12' }], {
259
+ source: 'linkage',
260
+ txId: 'tx-linkage-row-2',
261
+ linkageTxId: 'tx-linkage-row-2',
262
+ });
263
+ runtime.recordDefaultValuePatch(['roles', 0, 'title'], '12');
264
+ expect(formStub.getFieldValue(['roles', 0, 'title'])).toBe('12');
265
+
266
+ await runtime.setFormValues(blockCtx, [{ path: ['roles', 0, 'title'], value: 'manual' }], { source: 'user' });
267
+ expect(runtime.canApplyDefaultValuePatch(['roles', 0, 'title'], '13')).toBe(false);
268
+ });
269
+
270
+ it('does not mark omitted sibling fields from partial top-level changedValues as explicit', async () => {
271
+ const engineEmitter = new EventEmitter();
272
+ const blockEmitter = new EventEmitter();
273
+ const formStub = createFormStub({
274
+ roles: [{ __is_new__: true, __index__: 'row-1', name: '1', title: '1' }],
275
+ });
276
+
277
+ const blockModel: any = {
278
+ uid: 'form-direct-default-patch-partial-row',
279
+ flowEngine: { emitter: engineEmitter },
280
+ emitter: blockEmitter,
281
+ dispatchEvent: vi.fn(),
282
+ getAclActionName: () => 'create',
283
+ };
284
+
285
+ const runtime = new FormValueRuntime({ model: blockModel, getForm: () => formStub as any });
286
+ runtime.mount({ sync: true });
287
+
288
+ runtime.recordDefaultValuePatch(['roles', 0, 'title'], '1');
289
+
290
+ lodashSet((formStub as any).__store, ['roles', 0, 'name'], '12');
291
+ runtime.handleFormValuesChange({ roles: [{ name: '12' }] }, formStub.getFieldsValue());
292
+
293
+ expect((runtime as any).findExplicitHit('roles[0].title')).toBeNull();
294
+ expect(runtime.canApplyDefaultValuePatch(['roles', 0, 'title'], '12')).toBe(true);
295
+ });
296
+
168
297
  it('handles onFieldsChange name as string and triggers default recompute', async () => {
169
298
  const engineEmitter = new EventEmitter();
170
299
  const blockEmitter = new EventEmitter();
@@ -3267,4 +3396,41 @@ describe('FormValueRuntime (form assign rules)', () => {
3267
3396
  expect(payload.txId).toBe('tx-current');
3268
3397
  expect(payload.linkageTxId).toBe('tx-root');
3269
3398
  });
3399
+
3400
+ it('does not mark linkage writes explicit so later user edits can keep following default linkage', async () => {
3401
+ const engineEmitter = new EventEmitter();
3402
+ const blockEmitter = new EventEmitter();
3403
+ const formStub = createFormStub({ roleUid: 'role-uid-1', roleName: '' });
3404
+
3405
+ const blockModel: any = {
3406
+ uid: 'form-linkage-linkage-not-explicit',
3407
+ flowEngine: { emitter: engineEmitter },
3408
+ emitter: blockEmitter,
3409
+ dispatchEvent: vi.fn(),
3410
+ getAclActionName: () => 'create',
3411
+ };
3412
+
3413
+ const runtime = new FormValueRuntime({ model: blockModel, getForm: () => formStub as any });
3414
+ runtime.mount({ sync: true });
3415
+
3416
+ const blockCtx = createFieldContext(runtime);
3417
+ blockModel.context = blockCtx;
3418
+
3419
+ await runtime.setFormValues(blockCtx, [{ path: ['roleName'], value: 'role-uid-1' }], {
3420
+ source: 'linkage',
3421
+ txId: 'tx-linkage-1',
3422
+ linkageTxId: 'tx-linkage-1',
3423
+ linkageScopeDepth: 0,
3424
+ });
3425
+
3426
+ expect(formStub.getFieldValue(['roleName'])).toBe('role-uid-1');
3427
+ expect((runtime as any).findExplicitHit('roleName')).toBeNull();
3428
+
3429
+ await runtime.setFormValues(blockCtx, [{ path: ['roleUid'], value: 'role-uid-2' }], {
3430
+ source: 'user',
3431
+ txId: 'tx-user-1',
3432
+ });
3433
+ expect(formStub.getFieldValue(['roleUid'])).toBe('role-uid-2');
3434
+ expect((runtime as any).findExplicitHit('roleName')).toBeNull();
3435
+ });
3270
3436
  });
@@ -137,6 +137,42 @@ export class FormValueRuntime {
137
137
  return this.getForm().getFieldsValue(true);
138
138
  }
139
139
 
140
+ canApplyDefaultValuePatch(namePath: NamePath, resolved: any) {
141
+ if (!namePath?.length) return false;
142
+ if (typeof resolved === 'undefined') return false;
143
+
144
+ const pathKey = namePathToPathKey(namePath);
145
+ const current = this.getFormValueAtPath(namePath);
146
+ const last = this.lastDefaultValueByPathKey.get(pathKey);
147
+ const nextSnapshot = isObservable(resolved) ? toJS(resolved) : resolved;
148
+ const currentSnapshot = isObservable(current) ? toJS(current) : current;
149
+ const currentEqualsLastDefault = typeof last !== 'undefined' && _.isEqual(currentSnapshot, last);
150
+ const explicitHit = this.findExplicitHit(pathKey);
151
+
152
+ if (explicitHit && !currentEqualsLastDefault) return false;
153
+
154
+ const canOverwrite = isEmptyValue(current) || currentEqualsLastDefault;
155
+ if (!canOverwrite && _.isEqual(current, nextSnapshot)) {
156
+ this.lastDefaultValueByPathKey.set(pathKey, nextSnapshot);
157
+ return false;
158
+ }
159
+
160
+ return canOverwrite;
161
+ }
162
+
163
+ recordDefaultValuePatch(namePath: NamePath, value?: any) {
164
+ if (!namePath?.length) return;
165
+ const pathKey = namePathToPathKey(namePath);
166
+ const snapshot =
167
+ arguments.length >= 2 ? (isObservable(value) ? toJS(value) : value) : this.getFormValueAtPath(namePath);
168
+ this.lastDefaultValueByPathKey.set(pathKey, snapshot);
169
+ const current = this.getFormValueAtPath(namePath);
170
+ const currentSnapshot = isObservable(current) ? toJS(current) : current;
171
+ if (_.isEqual(currentSnapshot, snapshot)) {
172
+ this.clearExplicitForDefaultPatch(pathKey);
173
+ }
174
+ }
175
+
140
176
  private getFormValueAtPath(namePath: NamePath) {
141
177
  const form: any = this.getForm?.();
142
178
  if (form && typeof form.getFieldValue === 'function') {
@@ -247,11 +283,7 @@ export class FormValueRuntime {
247
283
  let bumpedWriteSeq = false;
248
284
  for (const field of changedFields || []) {
249
285
  const name = field?.name;
250
- const namePath: NamePath | null = Array.isArray(name)
251
- ? (name as NamePath)
252
- : typeof name === 'string' || typeof name === 'number'
253
- ? ([name] as NamePath)
254
- : null;
286
+ const namePath = this.normalizeObservedNamePath(name);
255
287
  if (!namePath?.length) continue;
256
288
  const nextValue = form.getFieldValue(namePath as any);
257
289
  const prevValue = _.get(this.valuesMirror, namePath);
@@ -265,8 +297,11 @@ export class FormValueRuntime {
265
297
  const isMeaningfulTouched =
266
298
  field?.touched === true && !this.shouldIgnoreSyntheticTouchedInit(namePath, prevValue, nextValue);
267
299
  if (isMeaningfulTouched) {
268
- touchedChangedPathKeys.add(namePathToPathKey(namePath));
269
- hasMeaningfulTouchedChange = true;
300
+ const pathKey = namePathToPathKey(namePath);
301
+ if (!this.shouldKeepDefaultPathValueEnabled(namePath, nextValue)) {
302
+ touchedChangedPathKeys.add(pathKey);
303
+ hasMeaningfulTouchedChange = true;
304
+ }
270
305
  }
271
306
  }
272
307
 
@@ -526,6 +561,10 @@ export class FormValueRuntime {
526
561
  }
527
562
 
528
563
  private getObservedChangedValue(path: NamePath, changedValues: any, snapshot: any) {
564
+ if (_.has(snapshot, path as any)) {
565
+ return _.get(snapshot, path as any);
566
+ }
567
+
529
568
  if (path?.length === 1) {
530
569
  const key = path[0];
531
570
  if (
@@ -546,6 +585,7 @@ export class FormValueRuntime {
546
585
 
547
586
  let observed = snapshot;
548
587
  for (const key of Object.keys(changedValues)) {
588
+ if (_.has(observed, [key])) continue;
549
589
  if (observed === snapshot) {
550
590
  observed = Array.isArray(snapshot) ? [...snapshot] : { ...snapshot };
551
591
  }
@@ -573,7 +613,15 @@ export class FormValueRuntime {
573
613
  this.lastObservedChangedPaths = null;
574
614
  this.lastObservedSource = null;
575
615
 
576
- const rawSnapshot = allValues && typeof allValues === 'object' ? allValues : this.getFormValuesSnapshot();
616
+ // 子表格的 changedValues 可能只包含局部行对象,diff 必须以 form 当前完整快照为准,
617
+ // 否则缺失的 sibling 字段会被误判为用户清空。
618
+ const formSnapshot = this.getFormValuesSnapshot();
619
+ const rawSnapshot =
620
+ formSnapshot && typeof formSnapshot === 'object'
621
+ ? formSnapshot
622
+ : allValues && typeof allValues === 'object'
623
+ ? allValues
624
+ : changedValues;
577
625
  const snapshot = this.getObservedSnapshot(changedValues, rawSnapshot);
578
626
  this.reconcileArrayItemState([...rawChangedPaths, ...changedValuePaths], changedValues, snapshot);
579
627
  this.pruneDeletedArrayItemState(snapshot);
@@ -602,8 +650,16 @@ export class FormValueRuntime {
602
650
  this.bumpChangeTick();
603
651
  }
604
652
 
605
- // default 来源写入:需要使默认值永久失效(explicit)
653
+ const explicitPathsToMark: NamePath[] = [];
606
654
  for (const p of explicitPaths) {
655
+ if (this.shouldKeepDefaultPathEnabled(p, snapshot)) {
656
+ continue;
657
+ }
658
+ explicitPathsToMark.push(p);
659
+ }
660
+
661
+ // 非 default 来源写入:需要使默认值永久失效(explicit)
662
+ for (const p of explicitPathsToMark) {
607
663
  this.markExplicit(namePathToPathKey(p));
608
664
  }
609
665
 
@@ -733,7 +789,7 @@ export class FormValueRuntime {
733
789
  const source: ValueSource = options?.source ?? 'system';
734
790
  const triggerEvent = options?.triggerEvent !== false;
735
791
  const txId = options?.txId ?? createTxId();
736
- const markExplicit = options?.markExplicit ?? source !== 'default';
792
+ const markExplicit = options?.markExplicit ?? (source !== 'default' && source !== 'linkage');
737
793
  const ownsTxId = typeof options?.txId === 'undefined';
738
794
 
739
795
  const linkageScopeDepth =
@@ -1071,10 +1127,12 @@ export class FormValueRuntime {
1071
1127
  private markExplicit(pathKey: string) {
1072
1128
  if (this.explicitSet.has(pathKey)) return;
1073
1129
  this.explicitSet.add(pathKey);
1130
+ const preserveDescendantDefaults = this.shouldPreserveDescendantDefaultsOnExplicit(pathKey);
1074
1131
 
1075
1132
  // explicit 后默认值永远失效:清理该路径及其子路径的 lastDefault 记录,避免误判“仍是默认值”
1076
1133
  for (const k of Array.from(this.lastDefaultValueByPathKey.keys())) {
1077
- if (k === pathKey || k.startsWith(`${pathKey}.`) || k.startsWith(`${pathKey}[`)) {
1134
+ const isDescendant = k.startsWith(`${pathKey}.`) || k.startsWith(`${pathKey}[`);
1135
+ if (k === pathKey || (!preserveDescendantDefaults && isDescendant)) {
1078
1136
  this.lastDefaultValueByPathKey.delete(k);
1079
1137
  }
1080
1138
  }
@@ -1087,6 +1145,40 @@ export class FormValueRuntime {
1087
1145
  }
1088
1146
  }
1089
1147
 
1148
+ private normalizeObservedNamePath(name: NamePath | string | number | undefined): NamePath | null {
1149
+ if (Array.isArray(name)) return name as NamePath;
1150
+ if (typeof name === 'number') return [name];
1151
+ if (typeof name !== 'string' || !name) return null;
1152
+ const parsed = pathKeyToNamePath(name);
1153
+ return parsed.length ? parsed : [name];
1154
+ }
1155
+
1156
+ private clearExplicitForDefaultPatch(pathKey: string) {
1157
+ for (const key of Array.from(this.explicitSet)) {
1158
+ if (key === pathKey || key.startsWith(`${pathKey}.`) || key.startsWith(`${pathKey}[`)) {
1159
+ this.explicitSet.delete(key);
1160
+ }
1161
+ }
1162
+ }
1163
+
1164
+ private shouldPreserveDescendantDefaultsOnExplicit(pathKey: string) {
1165
+ const value = this.getFormValueAtPath(pathKeyToNamePath(pathKey));
1166
+ return Array.isArray(value);
1167
+ }
1168
+
1169
+ private shouldKeepDefaultPathEnabled(namePath: NamePath, snapshot: any) {
1170
+ return this.shouldKeepDefaultPathValueEnabled(namePath, _.get(snapshot, namePath as any));
1171
+ }
1172
+
1173
+ private shouldKeepDefaultPathValueEnabled(namePath: NamePath, value: any) {
1174
+ const pathKey = namePathToPathKey(namePath);
1175
+ const last = this.lastDefaultValueByPathKey.get(pathKey);
1176
+ if (typeof last === 'undefined') return false;
1177
+
1178
+ const nextSnapshot = isObservable(value) ? toJS(value) : value;
1179
+ return _.isEqual(nextSnapshot, last);
1180
+ }
1181
+
1090
1182
  private isExplicit(pathKey: string) {
1091
1183
  return !!this.findExplicitHit(pathKey);
1092
1184
  }
@@ -30,6 +30,7 @@ import { useTranslation } from 'react-i18next';
30
30
  import { buildRecordPickerPopupContextInputArgs, RecordPickerContent } from '../RecordPickerFieldModel';
31
31
  import { AssociationFieldModel } from '../AssociationFieldModel';
32
32
  import { adjustColumnOrder } from '../../../blocks/table/utils';
33
+ import { isSubTableColumnFieldComponentContext } from '../SubTableFieldModel/SubTableColumnModel';
33
34
  import { EditFormContent } from './actions/PopupSubTableEditActionModel';
34
35
  import { QuickEditFormModel } from '../../../blocks/form/QuickEditFormModel';
35
36
  import { ActionWithoutPermission } from '../../../base/ActionModel';
@@ -901,6 +902,9 @@ PopupSubTableFieldModel.define({
901
902
  EditableItemModel.bindModelToInterface('PopupSubTableFieldModel', ['m2m', 'o2m', 'mbm'], {
902
903
  order: 300,
903
904
  when: (ctx, field) => {
905
+ if (isSubTableColumnFieldComponentContext(ctx)) {
906
+ return false;
907
+ }
904
908
  if (field.targetCollection) {
905
909
  return field.targetCollection.template !== 'file';
906
910
  }
@@ -36,6 +36,12 @@ import { FieldDeletePlaceholder, CustomWidth } from '../../../blocks/table/Table
36
36
  import { buildDynamicNamePath } from '../../../blocks/form/dynamicNamePath';
37
37
  import { getSubTableRowIdentity } from './rowIdentity';
38
38
 
39
+ export const SUB_TABLE_COLUMN_FIELD_COMPONENT_CONTEXT = 'subTableColumn';
40
+
41
+ export function isSubTableColumnFieldComponentContext(ctx) {
42
+ return (ctx?.model?.constructor as any)?.fieldComponentContext === SUB_TABLE_COLUMN_FIELD_COMPONENT_CONTEXT;
43
+ }
44
+
39
45
  const SubTableRowRuleBinder: React.FC<{ model: any }> = ({ model }) => {
40
46
  React.useEffect(() => {
41
47
  const emitter = model?.flowEngine?.emitter;
@@ -177,6 +183,25 @@ const MemoFieldRenderer = React.memo(FieldModelRenderer, (prev, next) => {
177
183
  return prev.value === next.value && prev.model === next.model;
178
184
  });
179
185
 
186
+ export function buildRowPathFromFieldIndex(fieldIndex: unknown): Array<string | number> | null {
187
+ if (!Array.isArray(fieldIndex) || !fieldIndex.length) return null;
188
+ const out: Array<string | number> = [];
189
+ for (const entry of fieldIndex) {
190
+ if (typeof entry !== 'string') continue;
191
+ const [fieldName, indexStr] = entry.split(':');
192
+ const index = Number(indexStr);
193
+ if (!fieldName || !Number.isFinite(index)) continue;
194
+ out.push(fieldName, index);
195
+ }
196
+ return out.length ? out : null;
197
+ }
198
+
199
+ export function getLatestSubTableRowRecord(form: any, fieldIndex: unknown, fallbackRecord: any): any {
200
+ const latestRowPath = buildRowPathFromFieldIndex(fieldIndex);
201
+ const latestRecord = latestRowPath ? form?.getFieldValue?.(latestRowPath) : undefined;
202
+ return typeof latestRecord === 'undefined' ? fallbackRecord : latestRecord;
203
+ }
204
+
180
205
  function shouldCommitImmediately(value: any) {
181
206
  if (Array.isArray(value)) {
182
207
  return true;
@@ -382,6 +407,7 @@ export class SubTableColumnModel<
382
407
  T extends SubTableColumnModelStructure = SubTableColumnModelStructure,
383
408
  > extends EditableItemModel<T> {
384
409
  static renderMode = ModelRenderMode.RenderFunction;
410
+ static fieldComponentContext = SUB_TABLE_COLUMN_FIELD_COMPONENT_CONTEXT;
385
411
 
386
412
  renderHiddenInConfig() {
387
413
  return <FieldWithoutPermissionPlaceholder targetModel={this} />;
@@ -574,6 +600,9 @@ export class SubTableColumnModel<
574
600
  const rowForkKey = `row:${baseIndexKey}:${rowIdentity}:${String(rowIdx)}`;
575
601
  const rowFork: any = (() => {
576
602
  const fork = this.createFork({}, rowForkKey);
603
+ fork.context.defineProperty('subTableRowFork', {
604
+ value: true,
605
+ });
577
606
  const associationFieldPath =
578
607
  (this.parent as any)?.fieldPath ??
579
608
  (this.parent as any)?.context?.fieldPath ??
@@ -592,9 +621,11 @@ export class SubTableColumnModel<
592
621
  }
593
622
  fork.context.defineProperty('item', {
594
623
  get: () => {
624
+ const form = (fork.context as any)?.form || (this.context?.blockModel as any)?.context?.form;
625
+ const rowRecord = getLatestSubTableRowRecord(form, fork.context.fieldIndex, record);
595
626
  const parentItemCtx = (parentItem ?? this.context?.item) as any;
596
- const isNew = record?.__is_new__;
597
- const isStored = record?.__is_stored__;
627
+ const isNew = rowRecord?.__is_new__;
628
+ const isStored = rowRecord?.__is_stored__;
598
629
  const list = (this.parent as any)?.props?.value;
599
630
  const length = Array.isArray(list) ? list.length : undefined;
600
631
  return {
@@ -602,7 +633,7 @@ export class SubTableColumnModel<
602
633
  length,
603
634
  __is_new__: isNew,
604
635
  __is_stored__: isStored,
605
- value: record,
636
+ value: rowRecord,
606
637
  parentItem: parentItemCtx,
607
638
  };
608
639
  },
@@ -14,8 +14,41 @@ import { useTranslation } from 'react-i18next';
14
14
  import { PlusOutlined } from '@ant-design/icons';
15
15
  import React, { useEffect, useMemo, useState } from 'react';
16
16
  import { ActionWithoutPermission } from '../../../base/ActionModel';
17
+ import { parsePathString } from '../../../blocks/form/value-runtime/path';
17
18
  import { getSubTableRowIdentity, normalizeSubTableRows } from './rowIdentity';
18
19
 
20
+ type NamePath = Array<string | number>;
21
+
22
+ function isSamePathPrefix(prefix: NamePath, path: NamePath) {
23
+ if (!prefix.length || prefix.length > path.length) return false;
24
+ return prefix.every((seg, index) => seg === path[index]);
25
+ }
26
+
27
+ function isRelatedPath(a: NamePath, b: NamePath) {
28
+ return isSamePathPrefix(a, b) || isSamePathPrefix(b, a);
29
+ }
30
+
31
+ function normalizeChangedPath(path: unknown): NamePath | null {
32
+ const rawPath = Array.isArray(path) ? path : typeof path === 'string' ? [path] : null;
33
+ if (!rawPath) return null;
34
+ const normalized = rawPath.flatMap((seg) => {
35
+ if (typeof seg === 'number') return [seg];
36
+ if (typeof seg !== 'string') return [];
37
+ return parsePathString(seg).filter((parsed): parsed is string | number => typeof parsed !== 'object');
38
+ });
39
+ return normalized.length ? normalized : null;
40
+ }
41
+
42
+ function shouldRefreshForChangedPaths(fieldPath: unknown, changedPaths: unknown) {
43
+ const currentFieldPath = normalizeChangedPath(fieldPath);
44
+ if (!currentFieldPath) return false;
45
+ const paths = Array.isArray(changedPaths) ? changedPaths : [];
46
+ return paths.some((path) => {
47
+ const changedPath = normalizeChangedPath(path);
48
+ return changedPath ? isRelatedPath(currentFieldPath, changedPath) : false;
49
+ });
50
+ }
51
+
19
52
  export function SubTableField(props) {
20
53
  const { t } = useTranslation();
21
54
  const {
@@ -35,9 +68,12 @@ export function SubTableField(props) {
35
68
  resetPage,
36
69
  filterTargetKey = 'id',
37
70
  getCurrentValue,
71
+ fieldPathArray,
72
+ formValuesChangeEmitter,
38
73
  } = props;
39
74
  const [currentPage, setCurrentPage] = useState(1);
40
75
  const [currentPageSize, setCurrentPageSize] = useState(pageSize);
76
+ const [, forceRefresh] = useState(0);
41
77
  const rawCurrentValue = getCurrentValue();
42
78
  const currentValue = useMemo(() => normalizeSubTableRows(rawCurrentValue), [rawCurrentValue]);
43
79
  const getRecordIdentity = React.useCallback(
@@ -50,6 +86,17 @@ export function SubTableField(props) {
50
86
  useEffect(() => {
51
87
  resetPage && setCurrentPage(1);
52
88
  }, [resetPage]);
89
+ useEffect(() => {
90
+ if (!formValuesChangeEmitter?.on || !formValuesChangeEmitter?.off) return;
91
+ const listener = (payload: any) => {
92
+ if (!shouldRefreshForChangedPaths(fieldPathArray, payload?.changedPaths)) return;
93
+ forceRefresh((v) => v + 1);
94
+ };
95
+ formValuesChangeEmitter.on('formValuesChange', listener);
96
+ return () => {
97
+ formValuesChangeEmitter.off('formValuesChange', listener);
98
+ };
99
+ }, [fieldPathArray, formValuesChangeEmitter]);
53
100
  const applyValue = React.useCallback((nextValue: any) => onChange?.(normalizeSubTableRows(nextValue)), [onChange]);
54
101
  const getLatestValue = React.useCallback(() => normalizeSubTableRows(getCurrentValue()), [getCurrentValue]);
55
102
  useEffect(() => {
@@ -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 { describe, expect, it, vi } from 'vitest';
11
+ import { getLatestSubTableRowRecord, buildRowPathFromFieldIndex } from '../SubTableColumnModel';
12
+
13
+ describe('SubTableColumnModel row record helpers', () => {
14
+ it('builds the row path from fieldIndex entries', () => {
15
+ expect(buildRowPathFromFieldIndex(['roles:0'])).toEqual(['roles', 0]);
16
+ expect(buildRowPathFromFieldIndex(['users:1', 'roles:2'])).toEqual(['users', 1, 'roles', 2]);
17
+ });
18
+
19
+ it('prefers the latest row value from form over the fallback record', () => {
20
+ const form = {
21
+ getFieldValue: vi.fn((path: any) => {
22
+ if (JSON.stringify(path) === JSON.stringify(['roles', 0])) {
23
+ return { uid: 'role-uid-1', __is_new__: true };
24
+ }
25
+ }),
26
+ };
27
+ const fallback = { uid: 'stale-role', __is_new__: false };
28
+
29
+ expect(getLatestSubTableRowRecord(form, ['roles:0'], fallback)).toEqual({
30
+ uid: 'role-uid-1',
31
+ __is_new__: true,
32
+ });
33
+ expect(form.getFieldValue).toHaveBeenCalledWith(['roles', 0]);
34
+ });
35
+
36
+ it('falls back to the record when latest row value is unavailable', () => {
37
+ const form = { getFieldValue: vi.fn(() => undefined) };
38
+ const fallback = { uid: 'stale-role', __is_new__: false };
39
+
40
+ expect(getLatestSubTableRowRecord(form, ['roles:0'], fallback)).toBe(fallback);
41
+ });
42
+ });