Repository navigation
Expand file tree
/
Copy pathMasterDetailForm.tsx
More file actions
2321 lines (2246 loc) · 112 KB
/
Copy pathMasterDetailForm.tsx
File metadata and controls
2321 lines (2246 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* MasterDetailForm — enter a parent record together with its child "line
* items" in a single screen, and persist them as one client-orchestrated
* transaction (see ADR-0001).
*
* The parent fields are rendered by the existing <ObjectForm>; the child
* collection(s) by <LineItemsField>. On submit we build ONE ordered
* cross-object operation list — parent create/update as op 0, each child a
* create/update/delete linked to it (via `{ $ref: 0 }` on create, or the
* known parent id on edit) — and hand it to `dataSource.batchTransaction`
* through {@link runBatchTransaction}. Client-side rollups are folded into the
* parent payload so they commit in the same batch.
*
* The form is deliberately ignorant of atomicity: a server with the
* transactional `/api/v1/batch` endpoint commits all-or-nothing, while an
* adapter without one emulates the batch internally (sequential writes with
* best-effort compensation, see `emulateBatchTransaction` in `@object-ui/core`).
* Either way there is no master-detail-specific cleanup code here (ObjectStack
* objectui #2679 / framework ADR-0034 item 4).
*
* No `@objectstack/spec` change: the relationship is a `master_detail` (or
* `lookup`) FK on the child object.
*/
import React, { startTransition, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import type { BatchTransactionOperation, DataSource, GridFieldMetadata, I18nLabel } from '@object-ui/types';
import { resolveAffordance, runBatchTransaction } from '@object-ui/core';
import { LineItemsField, lookupAutofillByField, useBooleanValueLabel, type BooleanValueLabel, type GridColumn, type LookupAutofillByField } from '@object-ui/fields';
import { Button, Card, CardContent, CardHeader, CardTitle, cn, toast } from '@object-ui/components';
import {
formatDisplayNumber,
pickLocalized,
resolveFieldCurrency,
useDisplayLocale,
useLocalization,
useObjectTranslation,
} from '@object-ui/i18n';
import { usePermissions } from '@object-ui/permissions';
import { dataChangeMatches, subscribeDataChanges } from '@object-ui/react';
import { ObjectForm } from './ObjectForm';
import { applyColumnPermissions } from './fieldWriteGate';
import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploadGate';
import { FormDirtyReportContext } from './formDirtyReport';
import { useFormChromeTranslation } from './formChrome';
import {
buildMasterDetailBatch,
buildMasterDetailEditBatch,
idOf,
isBlankRow,
sumRows,
type BatchEditDetailInput,
type ChildSchema,
} from './masterDetailTx';
import { isSameStoredValue } from './sanitize';
import { resolveInitialRecord } from './initialRecord';
import { sectionEntryName } from './sectionFields';
import { deriveDetail } from './deriveMasterDetail';
import { parentCurrencyFieldsOf, followedColumnCurrencies } from './parentCurrencyColumns';
// objectui#11428 — the per-row form's offer test is the spec's rule.
import { isInlineRowFormOffered } from '@objectstack/spec/data';
// objectui#11396 — one `details` entry, by reference: the spec's own type for
// `ComponentPropsMap['object-master-detail-form'].details[]`. Type-only.
import type { ObjectMasterDetailFormProps } from '@objectstack/spec/ui';
/**
* One detail collection: the `details` entry of
* `ComponentPropsMap['object-master-detail-form']` in `@objectstack/spec`, on
* its authoring face (`z.input`, what a document writes), taken by reference
* rather than restated here (objectui#11396). Since 17.6.0 the spec judges that
* entry as a closed shape (objectstack-ai/objectstack#21215): `childObject`
* required, every other member optional, `columns` the spec's inline grid
* column (the type the line grid's `GridColumn` is), an undeclared key refused
* by name. `@object-ui/types` takes the whole props row by reference, so
* `objectui validate` gives the spec's verdict on an entry; this is the
* TypeScript face of that entry, and
* `__tests__/masterDetailDetailsMembers-8071.test.tsx` holds the two equal at
* compile time.
*
* ONE key is left off, and it is no longer a fork: `sortField`. This form
* reads no such member — objectui#11070 round 9 retired the authored override:
* the child field the grid stamps with each line's position is DERIVED from
* the child object (`deriveDetail` picks its `position` / `sort_order` / …
* field) and carried on the resolved entry, and row 2c of that test pins that a
* written `sortField` is read by nothing. Through 17.6.0 the spec entry still
* declared it; `@objectstack/spec` 17.7.0 retires it — a `retiredKey()`
* tombstone on the entry (objectstack-ai/objectstack#21589, landed by PR
* objectstack-ai/objectstack#21632 as `6ec54f00`) — so both published zod faces
* refuse an authored `sortField` with the spec's retired-key message
* (objectui#11717). The entry still LISTS the key as that tombstone, and the
* omission below keeps it off this face rather than offer a member whose only
* legal value is absence. That omission is the whole of what is hand-written
* about the shape.
*
* Where each member lands — the renderer's reading, which the spec's
* description does not carry:
* - `childObject` names the child object; `relationshipField` is the FK on the
* child back to the parent, auto-detected from the child's `master_detail` /
* `lookup` field that references the parent when omitted.
* - `columns` are the line grid's editable columns, derived from the child's
* fields (via `DataSource.getObjectSchema`) when omitted; `formFields` are
* the per-row expand form's field names (broader than `columns`: rich types
* included), derived likewise.
* - `inlineMode`: `grid` = editable cells, `form` = read-only list + per-row
* full form; resolved from the relationship's `inlineEdit` (incl. the smart
* default) when omitted.
* - `amountField` is the CHILD column summed, and reaches the grid as its
* `totalField`; `totalField` is the PARENT field the sum is saved to, and is
* not forwarded to the grid.
* - `title` heads the collection's section (`Line Items` when unset);
* `minRows`, `maxRows` and `addLabel` reach the grid under the same names.
*/
export type MasterDetailDetailConfig = Omit<
NonNullable<ObjectMasterDetailFormProps['details']>[number],
'sortField'
>;
export interface MasterDetailFormSchema {
type?: 'object-master-detail-form';
/** Parent object name, e.g. 'expense_claim'. */
objectName: string;
mode?: 'create' | 'edit';
/**
* `string | number` to match `ObjectFormSchema` and the drawer/modal/
* tabbed/wizard envelopes that hand a record straight through to this form —
* a numeric primary key is a real backend shape. Narrowed to a string only at
* the batch-transaction boundary, whose `BatchTransactionOperation.id` is a
* string by protocol.
*/
recordId?: string | number;
/** Prefilled parent header values (create mode) — seeds the parent form's
* initial values, e.g. a conversion wizard carrying the lead/account over. */
initialValues?: Record<string, any>;
initialData?: Record<string, any>;
/** Parent form sections/fields — passed straight through to ObjectForm. */
sections?: any[];
fields?: any[];
formType?: 'simple' | 'tabbed';
/**
* The parent header form's initially active tab (a section name) and tab
* strip position, read when `formType` is `'tabbed'`, and its field layout —
* passed straight through to the header `ObjectForm`, as `sections` are
* (objectstack-ai/objectstack#26843).
*/
defaultTab?: string;
tabPosition?: 'top' | 'bottom' | 'left' | 'right';
layout?: 'vertical' | 'horizontal';
/**
* `title`, `submitText` and `cancelText` are the spec's `I18nLabel`, as
* `ComponentPropsMap['object-master-detail-form']` in `@objectstack/spec`
* declares them: a plain string or an inline per-locale map such as
* `{ en: 'Purchase order', 'zh-CN': '采购单' }`. The form resolves each one
* with `pickLocalized` against the active UI language
* (`useObjectTranslation().language`) before it reaches the screen
* (objectui#10935).
*
* `title` names the record in the built-in edit-save toast ("… saved",
* pack key `form.savedNamed`), which shows only when the host supplies no
* `onSuccess`.
*/
title?: I18nLabel;
/** Label of the Save button. Defaults to the session locale's `common.save`
* (edit) or `form.create` ('Save' / 'Create' in English). */
submitText?: I18nLabel;
/** Label for the Cancel button in the action bar, which renders only when the
* host supplies `onCancel`. Defaults to the session locale's `common.cancel`
* ('Cancel' in English); an authored label, a string or a per-locale map,
* always wins (objectui#11039). */
cancelText?: I18nLabel;
/** Hide the bottom Save/Cancel action bar — e.g. a non-persisting design
* preview. Defaults to shown (the form owns the only Save in this layout). */
showSubmit?: boolean;
/** One or more child collections. */
details: MasterDetailDetailConfig[];
/** Parent header field holding a tax rate (percent). When the parent form has
* this field, a live Subtotal / Tax / Total stack renders under the lines.
* Defaults to `tax_rate`; the stack only appears if the field is present. */
taxRateField?: string;
onSuccess?: (parent: any) => void | Promise<void>;
/**
* Called after a refused save, for bookkeeping only (logging, custom focus
* handling, …) — NOT for showing the failure to the user. The form
* renderer already toasts every rejected write for any host `submitHandler`
* (objectui#7354); a host that also toasts here puts the same refusal on
* screen twice.
*/
onError?: (err: Error) => void;
onCancel?: () => void;
className?: string;
}
/** Rows keyed by their persisted id (when known), for edit-mode diffing. */
interface RowState {
rows: Record<string, any>[];
/**
* Snapshot of the persisted rows (edit mode) for diffing on submit. Two
* writers: the children-fetch effect sets it from the read, and every
* successful edit save advances it to what that save wrote
* ({@link childRowsAfterSave}, objectui#10564).
*/
original: Record<string, any>[];
}
/** One detail collection as the edit batch was built from it. */
interface SavedDetailInput {
entryId: string;
/** The exact input handed to `buildMasterDetailEditBatch`. */
input: BatchEditDetailInput;
}
/**
* What one SUCCESSFUL edit batch wrote to one detail collection: the child-row
* form of `advanceLoadedRecord`, the parent record's baseline advance
* (objectui#10156 / objectui#10564).
*/
interface SavedChildRows {
entryId: string;
/**
* The `original` the batch diffed against. The advance lands only while it
* is still the collection's baseline: a reload that replaced the row state
* while the save was in flight has set a newer one.
*/
diffedAgainst: Record<string, unknown>[];
/** Each row the batch CREATED (the row object it was built from) → the id the server gave it. */
createdIds: Map<object, unknown>;
/** The baseline after the save: every persisted row, laid over with what this batch wrote to it. */
original: Record<string, unknown>[];
}
/**
* Whether a `create` operation's payload was built from `row`: every field it
* writes, other than the parent link the builder sets, holds the row's value.
* The builder only drops keys from a row (sanitize) and never rewrites one.
*/
function isBuiltFrom(
data: Record<string, unknown> | undefined,
row: Record<string, unknown>,
relationshipField: string,
): boolean {
return Object.entries(data ?? {}).every(
([k, v]) => k === relationshipField || isSameStoredValue(v, row[k]),
);
}
/**
* The child rows' baseline after an edit batch COMMITTED (objectui#10564).
*
* A form that stays mounted after a save must not diff its next save against
* the rows as FIRST read. Against that stale baseline a row the save created
* is still id-less and is created again; a row the save deleted is deleted
* again; and a cell changed back to its first-read value compares clean and is
* dropped while the server keeps the saved value.
*
* Two facts come from the batch, and nothing is inferred beyond them:
*
* - **Ids.** `batchTransaction` answers `results` index-aligned with the
* operations, a create echoing the record it wrote (`DataSource`'s contract;
* the server's `/batch` and `emulateBatchTransaction` both do). The edit
* builder puts the parent at index 0 and then, collection by collection in
* the order it was handed them, one `create` per non-blank row without an
* id, in row order. Each such row is paired with the next create operation,
* and the pair is checked ({@link isBuiltFrom}) before it is trusted. A pair
* that does not check out stops the pairing: the rows left unpaired stay
* creates, which is the behaviour before this advance, never a row updating
* another row's record. A create echo without an id leaves its row a create
* too.
* - **Written values.** What the batch sent, laid over the row as read — the
* same rule `advanceLoadedRecord` applies to the parent. A row the batch
* deleted leaves the baseline; a row it did not touch keeps its snapshot.
*
* Pure, and it does not throw: it runs between a committed batch and the
* parent's own advance, where a throw would report a save that landed as a
* failure.
*/
function childRowsAfterSave(
ops: BatchTransactionOperation[],
results: unknown,
details: SavedDetailInput[],
): SavedChildRows[] {
const echoes = Array.isArray(results) ? results : [];
const creates: Array<{ op: BatchTransactionOperation; echo: unknown }> = [];
ops.forEach((op, k) => {
if (k > 0 && op.action === 'create') creates.push({ op, echo: echoes[k] });
});
let nextCreate = 0;
let pairingLost = false;
const saved = details.map(({ entryId, input }): SavedChildRows => {
const { childObject, relationshipField } = input;
const rows = input.rows || [];
const original = input.original || [];
const createdIds = new Map<object, unknown>();
const written = new Map<unknown, Record<string, unknown>>();
for (const row of rows) {
if (pairingLost) break;
if (idOf(row) != null || isBlankRow(row, relationshipField)) continue;
const pair = creates[nextCreate];
if (!pair || pair.op.object !== childObject || !isBuiltFrom(pair.op.data, row, relationshipField)) {
pairingLost = true;
break;
}
nextCreate += 1;
const id = idOf(pair.echo);
if (id == null) continue;
createdIds.set(row, id);
written.set(id, pair.op.data ?? {});
}
for (let k = 1; k < ops.length; k++) {
const op = ops[k];
if (op.action === 'update' && op.object === childObject && op.id != null) {
written.set(op.id, op.data ?? {});
}
}
const before = new Map<unknown, Record<string, unknown>>();
for (const r of original) {
const id = idOf(r);
if (id != null) before.set(id, r);
}
const next: Record<string, unknown>[] = [];
for (const row of rows) {
const id = idOf(row) ?? createdIds.get(row);
if (id == null) continue;
const was = before.get(id);
const wrote = written.get(id);
if (!was && !wrote) continue;
const entry: Record<string, unknown> = { ...(was ?? {}), ...(wrote ?? {}) };
if (idOf(entry) == null) entry.id = id;
next.push(entry);
}
return { entryId, diffedAgainst: input.original, createdIds, original: next };
});
if (pairingLost || nextCreate !== creates.length) {
console.warn(
'[MasterDetailForm] could not pair every row created by this save with its create operation; an unpaired row keeps no id, and the next save creates it again.',
);
}
return saved;
}
/**
* What happened to one detail entry's schema resolution (objectui#6372).
*
* A plain `MasterDetailDetailConfig[]` cannot express this. An entry whose
* fetch FAILED and one that is STILL IN FLIGHT are represented identically —
* both are simply an entry with no `columns` — so the renderer showed the same
* "Loading columns…" for both. For the failed one that message never ends: the
* fetch that would have supplied those columns has already failed and is not
* retried, so nothing can ever replace it.
*/
type DetailResolution =
/** The schema fetch has not settled yet — "Loading columns…" is TRUE here. */
| 'pending'
/** No `childObject` was authored, so no fetch was made (objectui#5940). */
| 'declined'
/** Columns are hydrated, or were fully authored to begin with. */
| 'ready'
/** The schema fetch THREW — columns can never arrive (objectui#6372). */
| 'failed'
/**
* The schema LOADED FINE, but `deriveDetail` threw on it (objectui#6394) —
* almost always "no lookup/master_detail field on the child references the
* parent". A CONFIGURATION error, not a load error, which is why it is a
* state of its own rather than a second reading of `failed`: the remedy is a
* key the author writes (`relationshipField`), not a reload, and the two
* placeholders must not borrow each other's copy.
*/
| 'underivable';
/**
* One authored detail collection, plus the two pieces of per-entry metadata a
* bare `MasterDetailDetailConfig[]` could not carry: WHICH entry this is, and
* WHAT happened to it.
*
* ⭐ Both defects this record closes came from the same absence. With no
* per-entry metadata, "what happened to this entry" (objectui#6372) and "which
* entry is this" (objectui#6371) were BOTH inferred from the entry's position
* in the array. One record answers both, which is why they land together:
* either one alone would have reshaped this structure and the second would
* then have rewritten the first.
*/
interface DetailEntry {
/**
* Stable identity, synthesized ONCE from the incoming config — never the map
* index of the rendered array. See {@link synthesizeDetailIds}.
*/
id: string;
/** The authored config, with derived columns / FK folded in once resolved. */
config: MasterDetailDetailConfig;
status: DetailResolution;
/**
* The child field the line grid stamps with each line's position, so a
* drag-reorder persists: `deriveDetail`'s pick (the child object's
* `position` / `sort_order` / … field), handed to the grid as `sortField`.
* Derived only, never authored (objectui#11070 round 9), so it lives here
* beside the other resolved state rather than on the authored config. Absent
* when the entry was not derived (a fully configured entry loads no child
* schema) or the child has no such field.
*/
sortField?: string;
/**
* The child object's own definition of `config.amountField`, kept from the
* schema the resolve effect loaded, so the document totals stack can read the
* amount's currency off the FIELD (objectui#11132). Absent when no schema was
* loaded for this entry (a fully configured entry skips the fetch) or the
* child declares no such field; the stack then resolves to the tenant's
* currency. Internal state, never part of the authored config.
*/
amountFieldDef?: CurrencyFieldDef;
/**
* The resolve effect's column derivation for this entry, re-runnable with
* another `booleanLabel` (objectui#12924): the same `deriveDetail` call over
* the same child schema and authored config. The line grid's columns are
* drawn through it at render, keyed on the session's two boolean words, so
* a catalogue that lands after the child schema re-labels a derived
* `boolean` / `toggle` column's options without re-running the effect.
* Absent when the entry was not derived. Internal state, never part of the
* authored config.
*/
columnsWith?: (booleanLabel: BooleanValueLabel) => GridColumn[];
/**
* The child fields' declared `lookupAutofill` pairs, by lookup field name,
* read from the schema the resolve effect loaded and handed to the line grid
* (`GridField`'s `lookupAutofill`): a grid column carries no field
* definition. Absent when no schema was loaded for this entry (a fully
* configured entry skips the fetch). Internal state, never authored.
*/
lookupAutofill?: LookupAutofillByField;
/**
* The child fields whose currency follows the header through this entry's
* relationship (ADR-0144 D2 as amended), by name, read from the schema the
* resolve effect loaded (`parentCurrencyFieldsOf`). The line grid draws
* those columns, and the totals stack an amount among them, in the header's
* currency. Internal state, never authored.
*/
parentCurrencyFields?: ReturnType<typeof parentCurrencyFieldsOf>;
}
/** The field shape `resolveFieldCurrency` reads — the one currency resolver. */
type CurrencyFieldDef = Parameters<typeof resolveFieldCurrency>[0];
/**
* The child object's definition of `fieldName`, or `undefined` when the name is
* unset or the child declares no such field.
*/
function childFieldDef(
childSchema: { fields?: Record<string, unknown> } | undefined,
fieldName: string | undefined,
): CurrencyFieldDef {
if (!fieldName) return undefined;
const def = childSchema?.fields?.[fieldName];
return def && typeof def === 'object' ? (def as CurrencyFieldDef) : undefined;
}
/**
* The currency the document totals stack is denominated in (objectui#11132).
*
* Each entry that switches the stack on (one with an `amountField`) resolves its
* amount's currency through `resolveFieldCurrency`, the one precedence every
* currency face shares: the field's fixed currency, else the tenant default.
* ⛔ No constant: the stack used to print a literal `¥` whatever either said.
*
* The stack adds every entry's amounts into ONE subtotal, so it has one
* currency only when every entry resolves to the same code. When they differ,
* or none is known, this answers `undefined` and the stack shows plain numbers,
* the resolver's own answer for an amount with no known currency: never a
* guessed sign.
*/
function totalsCurrency(
entries: DetailEntry[],
tenantCurrency: string | undefined,
header?: Readonly<Record<string, unknown>>,
): string | undefined {
const codes = new Set(
entries
.filter((e) => !!e.config.amountField)
.map((e) =>
// An amount that follows the header's currency (ADR-0144 D2 as
// amended) is in the header's code; every other one keeps its own.
e.parentCurrencyFields && e.config.amountField && e.config.amountField in e.parentCurrencyFields
? followedColumnCurrencies(e.parentCurrencyFields, header, tenantCurrency)?.[e.config.amountField]
: resolveFieldCurrency(e.amountFieldDef, tenantCurrency),
),
);
return codes.size === 1 ? codes.values().next().value : undefined;
}
/**
* The fraction width of a totals line with no currency: the historical two
* places the stack always showed, which is also `CurrencyField`'s width when
* no currency resolves.
*/
const PLAIN_AMOUNT_DIGITS = 2;
/**
* One line of the document totals stack, in the display locale (objectui#9909).
*
* With a currency, the amount is `Intl`'s own currency format through
* `formatDisplayNumber`, the formatter the line grid's currency cells use. So
* the sign sits where the locale puts it (`$1,234.50`, `1.234,50 $` in de-DE)
* and the width is the currency's CLDR fraction digits, the default `Intl`
* applies to `style: 'currency'`: 2 for USD, 0 for JPY, 3 for KWD. A
* currency's decimal places are the currency's, not a setting.
*
* Without one, a plain number at {@link PLAIN_AMOUNT_DIGITS}. A code `Intl`
* refuses (`RangeError: Invalid currency code`) is shown as the code beside
* that plain number, as `CurrencyField` and the grid cells show one, rather
* than taking the form down; the digits stay in the display locale.
*/
function formatTotalsAmount(n: number, currency: string | undefined, locale: string): string {
const plain = () =>
formatDisplayNumber(n, { locale, minimumFractionDigits: PLAIN_AMOUNT_DIGITS, maximumFractionDigits: PLAIN_AMOUNT_DIGITS });
if (!currency) return plain();
try {
return formatDisplayNumber(n, { locale, currency });
} catch {
return `${currency} ${plain()}`;
}
}
/**
* Give every authored detail entry an identity that does not change when a
* SIBLING moves.
*
* ## The hazard, stated correctly
*
* ⛔ The old key — `${d.childObject}` joined to the map index — did NOT
* collide. The index is unique among siblings by construction, so two declined
* details keyed as `undefined-0` and `undefined-1`: distinct, no React
* duplicate-key warning, no remount collision. Anyone re-deriving this starts
* from the INDEX-IDENTITY hazard, never from a collision claim (objectui#6371
* corrects the record on that point).
*
* The real defect: for a declined entry the DATA half of that key is
* `undefined`, so the entry's identity was purely its POSITION — and the
* row-state store was addressed the same way. Reordering or removing an entry
* therefore re-associated a collection's DOM node, its rows, AND its
* contribution to the document subtotal with a different collection.
*
* ## What the identity is
*
* A named collection is identified by the child object it lists: the half of
* the old key that actually carried data, and the half that survives a
* reorder. A DECLINED entry has no such half — the decline is precisely the
* absence of one — so its identity is its AUTHORED POSITION in the incoming
* `details` array, synthesized here, once, at config time.
*
* Two collections may legitimately list the SAME child object, so an
* occurrence counter separates them without sending the named case back to
* position. Two entries indistinguishable in the config stay indistinguishable
* here: that ambiguity is authored, not introduced.
*/
function synthesizeDetailIds(raw: MasterDetailDetailConfig[]): string[] {
const seen = new Map<string, number>();
return raw.map((d, authoredPosition) => {
// The prefixes keep the two namespaces apart, so a child object literally
// named `pos:0` cannot take a declined entry's identity.
const base = d.childObject ? `obj:${d.childObject}` : `pos:${authoredPosition}`;
const nth = seen.get(base) ?? 0;
seen.set(base, nth + 1);
return nth === 0 ? base : `${base}~${nth}`;
});
}
/**
* objectui#10853 — `useDataInvalidation` (`@object-ui/react`) for a SET of
* objects: each name's nonce moves once per change the data-invalidation bus
* reports for it.
*
* The edit-mode lines read one child object per detail collection, and the
* collections are authored, so there is no fixed number of hook calls to make.
* This is the same bus and the same test, not a second channel:
* `subscribeDataChanges` is the listener set `useDataInvalidation` subscribes
* through, and `dataChangeMatches` its matcher. It is applied object-level (no
* `recordId`), because a collection is many records of its object.
*
* Keyed on the set's CONTENT, so a fresh array of the same names neither
* resubscribes nor resets a nonce (AGENTS.md #10).
*/
function useObjectsInvalidation(objectNames: readonly string[]): Readonly<Record<string, number>> {
const namesKey = JSON.stringify(Array.from(new Set(objectNames)).sort());
const [nonces, setNonces] = useState<Record<string, number>>({});
useEffect(() => {
const names = JSON.parse(namesKey) as string[];
if (names.length === 0) return;
const unsubscribe = subscribeDataChanges((change) => {
const hit = names.filter((name) => dataChangeMatches(change, name));
if (hit.length === 0) return;
setNonces((prev) => {
const next = { ...prev };
for (const name of hit) next[name] = (next[name] ?? 0) + 1;
return next;
});
});
return () => {
unsubscribe();
};
}, [namesKey]);
return nonces;
}
/**
* objectui#10853 — whether one collection holds lines the user has not saved:
* the edit save's own row diff (`buildMasterDetailEditBatch`) finds something
* to write to it OTHER than the parent link. A user's edit therefore reads as
* unsaved exactly when the save would send it, and a line changed back to its
* stored value (a revert) reads as saved again.
*
* The parent link is set aside on purpose, and it is the one place the two
* disagree. The save restates the link on every row it writes, as the parent
* id in string form, and a row read back can carry it in another form (a
* numeric id, an expanded lookup); against such a backend the save restates it
* on every row while this reads the lines as saved. That restatement is not the
* user's input, so it does not hold a re-read.
*/
function linesUnsaved(
state: RowState | undefined,
detail: MasterDetailDetailConfig,
parentId: string,
childSchema: ChildSchema,
): boolean {
if (!state || !detail.relationshipField) return false;
const relationshipField = detail.relationshipField;
const ops = buildMasterDetailEditBatch('', parentId, {}, [
{
childObject: detail.childObject,
relationshipField,
rows: state.rows,
original: state.original.map((row) => ({ ...row, [relationshipField]: parentId })),
childSchema,
},
]);
// Op 0 is the (empty) parent update the builder always leads with.
return ops.length > 1;
}
/**
* The header's RECORD, as the header itself obtained it (objectui#13062): the
* record its edit-mode read answered, or the record a create form opens on;
* and the header object's FIELD NAMES, as its schema read answered them.
*
* The line grids evaluate their `parent.*` rules against the record, and the
* totals stack asks whether the header carries the tax-rate field. Before
* #13062 both read a DOM scrape of the header taken at mount and on three
* timers (120 / 360 / 800 ms), so a header that answered later than the last
* tick left `parent` empty: a stored paid invoice opened with its locked line
* cells editable.
*
* A listener set, not React state in <MasterDetailForm>: a landing reaches only
* <MasterDetailLines>, and never re-renders the header <ObjectForm> (#1581).
*/
interface HeaderRecordFeed {
/** The latest record; read by a subscriber that mounts after a landing. */
record: Record<string, unknown>;
/** The header object's field names, once its schema read has answered. */
objectFields: readonly string[] | null;
/** Bumped per header record read started, so only the newest answer lands. */
seq: number;
listeners: Set<(landed: 'record' | 'objectFields') => void>;
}
function createHeaderRecordFeed(opening: Record<string, unknown>): HeaderRecordFeed {
return { record: opening, objectFields: null, seq: 0, listeners: new Set() };
}
/**
* The data source the header <ObjectForm> reads through, observing the two
* reads that ARE the header's record and field set: `findOne(objectName,
* recordId)` and `getObjectSchema(objectName)`. The header's own value channels
* do not carry them. <ObjectForm> forwards no value callback to its host, and
* the form renderer's `onChange` keeps a `defaultValues` reset (the record
* landing) off its channel by design (#2968, #5235). The read itself is the
* moment the record lands, and every re-read of it (a data-invalidation
* re-read, a remount) lands here too.
*
* Every call is passed through untouched: the same arguments, the same
* promise back (its rejection still reaches the header), with `this` the
* caller's own data source. A read of any other record or object (a lookup's
* display read, say) is not observed.
*/
function observeHeaderReads(
dataSource: DataSource | undefined,
objectName: string,
recordId: string | number | undefined,
feed: HeaderRecordFeed,
): DataSource | undefined {
if (!dataSource) return dataSource;
const readsRecord = recordId !== undefined && recordId !== null && recordId !== '';
const bound = new Map<PropertyKey, unknown>();
const observe = (answer: unknown, land: (value: unknown) => void) => {
// The header reports its own failed read; nothing lands here.
Promise.resolve(answer).then(land, () => undefined);
};
return new Proxy(dataSource, {
get(target, prop) {
const value = Reflect.get(target, prop, target);
if (typeof value !== 'function') return value;
if (!bound.has(prop)) {
const call = (args: unknown[]) => (value as (...a: unknown[]) => unknown).apply(target, args);
let wrapped: unknown;
if (prop === 'findOne' && readsRecord) {
wrapped = (...args: unknown[]) => {
const answer = call(args);
if (args[0] === objectName && String(args[1]) === String(recordId)) {
const seq = ++feed.seq;
observe(answer, (record) => {
if (seq !== feed.seq) return; // a newer read superseded this one
feed.record = (record ?? {}) as Record<string, unknown>;
feed.listeners.forEach((listener) => listener('record'));
});
}
return answer;
};
} else if (prop === 'getObjectSchema') {
wrapped = (...args: unknown[]) => {
const answer = call(args);
if (args[0] === objectName) {
observe(answer, (objectSchema) => {
const fields = (objectSchema as { fields?: Record<string, unknown> } | null)?.fields;
feed.objectFields = fields ? Object.keys(fields) : [];
feed.listeners.forEach((listener) => listener('objectFields'));
});
}
return answer;
};
} else {
wrapped = (value as (...a: unknown[]) => unknown).bind(target);
}
bound.set(prop, wrapped);
}
return bound.get(prop);
},
});
}
/**
* The header fields an author DECLARED for the form — its `sections`' members,
* else its `fields` — or null when it declares none and the header draws the
* object's own field set. The same precedence <ObjectForm> draws by.
*/
function declaredHeaderFields(schema: {
sections?: ReadonlyArray<{ fields?: unknown[] } | null | undefined>;
fields?: unknown[];
}): string[] | null {
const names = (entries: unknown[] | undefined) =>
(entries ?? []).map(sectionEntryName).filter((n): n is string => typeof n === 'string');
if (schema.sections?.length) return schema.sections.flatMap((section) => names(section?.fields));
if (schema.fields?.length) return names(schema.fields);
return null;
}
/**
* Read the header's controls as the user edits them, by scraping the named
* controls of the rendered parent-form host. It runs ONLY on the host's
* bubbling `input` / `change` events, overlaid on the header record above: the
* header is owned by react-hook-form (inside <ObjectForm>), which exposes no
* values callback to this host. Radix <Select> renders a visually-hidden native
* `<select name=...>` for form participation, so selects (e.g. an invoice
* `status`) are captured too, and a user's pick dispatches a bubbling `change`
* the host listener catches.
*/
function scrapeHeaderRecord(host: HTMLElement | null): Record<string, unknown> {
if (!host) return {};
const out: Record<string, unknown> = {};
const els = host.querySelectorAll<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>('[name]');
els.forEach((el) => {
const name = el.getAttribute('name');
if (!name) return;
if (el.tagName === 'INPUT') {
const input = el as HTMLInputElement;
if (input.type === 'checkbox') { out[name] = input.checked; return; }
if (input.type === 'radio') { if (input.checked) out[name] = input.value; return; }
if (input.type === 'number' || input.type === 'range') {
if (input.value === '') { out[name] = null; return; }
const n = Number(input.value);
out[name] = Number.isFinite(n) ? n : input.value;
return;
}
out[name] = input.value;
return;
}
// <select> (incl. Radix's hidden native select) and <textarea>.
out[name] = (el as HTMLSelectElement | HTMLTextAreaElement).value;
});
return out;
}
/**
* A configuration hint's pack sentence, with each `{{hole}}` rendered as code
* (objectui#11160).
*
* The three collection hints below name what the author has to find or set: a
* property (`childObject`, `relationshipField`) or an object's name. Those stay
* code and are never translated, so the pack sentence carries a hole for each.
* The caller asks `t` for the sentence with every hole filled by itself, and
* this splits the text on the holes and puts each one's value in its place, in
* whatever order the locale's word order puts them. `LineItemsPanel`'s
* `form.lineItems.noChildObject` split is the one-hole form of the same move.
*/
function withCodeHoles(sentence: string, holes: Record<string, string | undefined>): React.ReactNode[] {
const names = Object.keys(holes);
const pattern = new RegExp(`(${names.map((name) => `\\{\\{${name}\\}\\}`).join('|')})`);
return sentence.split(pattern).map((part, i) => {
const name = names.find((n) => part === `{{${n}}}`);
return name === undefined ? part : (
<code key={i} className="font-mono">{holes[name]}</code>
);
});
}
interface MasterDetailLinesProps {
entries: DetailEntry[];
/** Row state addressed by ENTRY ID, never by array position (objectui#6371). */
rowState: Record<string, RowState>;
setRows: (entryId: string, rows: Record<string, any>[]) => void;
/**
* A save is in flight: every grid takes no input (objectui#10631). A created
* row takes its echoed id by identity with the row object the batch was built
* from, and a grid with a sort field maps EVERY row to a new object on any
* change, so a single keystroke during the save would leave every row it
* created without its id.
*/
saving: boolean;
/** Host wrapping the header <ObjectForm> — scraped on the user's edits. */
formHostRef: React.RefObject<HTMLDivElement | null>;
taxRateField: string;
/**
* The header's record and object field set (objectui#13062). A new feed per
* record and per header remount (after create), which drops the edits
* scraped against the old one.
*/
headerRecord: HeaderRecordFeed;
/** The header fields the author declared, or null for the object's own set. */
declaredHeaderFieldNames: readonly string[] | null;
onRowExpand: (entryId: string, rowIdx: number) => void;
onAddViaForm: (entryId: string) => void;
/**
* The PARENT object's name, for the `underivable` config hint — "which parent
* this collection could not be linked to" is half the diagnosis, and the
* entry's own config cannot carry it (objectui#6394).
*/
parentObjectName: string;
/**
* The form's mode, which picks the question the child grids' cells ask
* (objectui#12082): every line of a CREATE form is a new child record, so its
* cells ask the create question (the server's insert rule); an edit form's
* lines may already exist, and a per-column lock cannot split per row, so
* they keep the edit question. For the same reason only an edit form's
* Remove asks the child's delete grant: a create form's lines are drafts.
*/
formMode: 'create' | 'edit';
}
/**
* The line-item grids + document totals, isolated from the header form.
*
* It owns `parentRecord` — the header's record (`headerRecord`) with the user's
* live edits scraped from the form host over it — and binds it to every grid as
* `contextRecord`, so a column's `readonlyWhen` / `requiredWhen` CEL rule can
* react to the header (the "paid invoice → lock lines" case,
* `parent.status == 'paid'`; see #1581 / ADR-0036).
*
* Holding `parentRecord` HERE rather than in <MasterDetailForm> is the whole
* point: a header keystroke re-renders only these lines, never the header
* <ObjectForm> whose react-hook-form state would otherwise reset mid-edit. The
* scrape is deduped by value so an identical re-read causes no state churn.
*/
const MasterDetailLines: React.FC<MasterDetailLinesProps> = ({
entries,
rowState,
setRows,
saving,
formHostRef,
taxRateField,
headerRecord,
declaredHeaderFieldNames,
onRowExpand,
onAddViaForm,
parentObjectName,
formMode,
}) => {
// The subtotal / tax / grand-total stack formats in the display locale; it
// used to pass `toLocaleString` an explicit `undefined`, i.e. the MACHINE's
// locale (objectui#9909).
const displayLocale = useDisplayLocale();
// The tenant default currency (ADR-0053): the totals stack's currency when
// the amount field fixes none (objectui#11132).
const { currency: tenantCurrency } = useLocalization();
// The collection placeholder, the document totals stack and the in-form
// collection's default add label, in the session locale (objectui#11071).
// Since objectui#11145 also a collection's heading when it authors no
// `title`: the key the record page's line-items panel reads for its own.
// Since objectui#11160 also the three collection hints (no `childObject`,
// a schema that failed to load, no relationship field to the parent).
const { t } = useFormChromeTranslation();
// The caller's field-level grants on each CHILD object. With no provider
// mounted this is the fail-open answer (`isLoaded` false) and every grid below
// renders exactly as it did before permissions existed (objectui#10163).
const perms = usePermissions();
// The header's record, whenever it lands (objectui#13062) — no timer bounds
// it, so a header that answers late still locks a paid invoice's lines.
const [loadedRecord, setLoadedRecord] = useState<Record<string, unknown>>(headerRecord.record);
const [objectFields, setObjectFields] = useState<readonly string[] | null>(headerRecord.objectFields);
// The user's edits, scraped from the host on its input/change events; null
// until the first one. A landing record replaces the form's values, so it
// drops them.
const [editedRecord, setEditedRecord] = useState<Record<string, unknown> | null>(null);
const editedKeyRef = useRef<string>('');
useEffect(() => {
const land = (landed: 'record' | 'objectFields') => {
if (landed === 'objectFields') {
setObjectFields(headerRecord.objectFields);
return;
}
editedKeyRef.current = '';
setEditedRecord(null);
setLoadedRecord(headerRecord.record);
};
// What landed before this subscription (or a new feed's opening).
land('record');
land('objectFields');
headerRecord.listeners.add(land);
return () => {
headerRecord.listeners.delete(land);
};
}, [headerRecord]);
useEffect(() => {
const host = formHostRef.current;
if (!host) return;
const onEvt = () => {
const next = scrapeHeaderRecord(host);
let key: string;
try { key = JSON.stringify(next); } catch { key = String(Math.random()); }
if (key === editedKeyRef.current) return; // value-identical → no re-render
editedKeyRef.current = key;
// A TRANSITION, never a plain update (objectstack#28471). This listener
// sits on the host, INSIDE the React root, so a keystroke reaches it
// before React's own root listener has handed the value to the
// header's react-hook-form. A plain update here is sync priority (the
// event is `input`), and the browser's microtask checkpoint between
// two listeners flushes it right there, together with whatever
// default-priority work the page has pending (a fetch that just
// landed): that render repaints the header input with its old
// controlled value, React's value tracker then sees no change, and the
// keystroke is dropped without a word — measured on the showcase
// master-detail page, where a Create then failed "Project Name is
// required" with the name visibly typed. A transition is not flushed
// in that checkpoint, so React reads the keystroke first.
startTransition(() => setEditedRecord(next));
};
host.addEventListener('input', onEvt);
host.addEventListener('change', onEvt);
return () => {
host.removeEventListener('input', onEvt);
host.removeEventListener('change', onEvt);
};
}, [formHostRef]);
const parentRecord = useMemo(
() => (editedRecord ? { ...loadedRecord, ...editedRecord } : loadedRecord),
[loadedRecord, editedRecord],
);
// Document totals: Subtotal (Σ line amounts) → Tax (header rate %) → Total.
// Shown only when the header carries the tax-rate field AND a detail has an
// amount column; otherwise each grid keeps its own footer total.
// "The header carries the field" is the header's field set, not whether the
// record happens to hold a value for it (objectui#13062).
const headerCarriesTax =
Object.prototype.hasOwnProperty.call(parentRecord, taxRateField) ||
(declaredHeaderFieldNames ?? objectFields ?? []).includes(taxRateField);
const taxRaw = parentRecord[taxRateField];
const taxRate = !headerCarriesTax ? null : (Number.isFinite(Number(taxRaw)) ? Number(taxRaw) : 0);
// ⚠️ Addressed by ENTRY ID. This reducer read `state[i]` — so a reorder did
// not merely show a collection the wrong grid, it MIS-COMPUTED the document
// total: each entry summed a different collection's rows, under its own
// `amountField` (objectui#6371).
const subtotal = entries.reduce(
(acc, e) => acc + sumRows(rowState[e.id]?.rows ?? [], e.config.amountField || 'amount'),
0,
);
const showTaxStack = taxRate !== null && entries.some((e) => !!e.config.amountField);
const taxPct = taxRate ?? 0;
const taxAmount = subtotal * (taxPct / 100);
const grandTotal = subtotal + taxAmount;
// The amounts' own currency, else the tenant's; never a constant sign
// (objectui#11132). See `totalsCurrency` and `formatTotalsAmount`.
const currency = totalsCurrency(entries, tenantCurrency, parentRecord);
const money = (n: number) => formatTotalsAmount(n, currency, displayLocale);