Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.

Commit fde4caf

Browse files
fix(fields): a lookup value hydrated from a bare id is labelled from the schema once it arrives (objectui#10487) (#10557)
Fixes #10487 Clause-②: no A lookup that mounts already holding a bare id now labels its chip from the referenced object's schema once that schema arrives. Before, when the record fetch won the race against `getObjectSchema`, the chip kept the no-schema label (the `name` guess) for good, while the dropdown option for the same record read the declared `nameField`. ## Reproduction (base `db3896c4c`, the card's fixture) Value `'c1'`; the object's `nameField` is `contract_no`; the row is `{ id: 'c1', name: 'Acme', contract_no: 'HT-001' }`. The pin's backend holds `getObjectSchema` open until the chip is labelled, then releases it. | reading | base | head | |---|---|---| | mounted chip, before the schema | `Acme` | `Acme` | | mounted chip, after the schema | `Acme` | `HT-001` | | dropdown option for `c1` | `HT-001` | `HT-001` | | chip after picking `c1` again | `HT-001` | `HT-001` | The mechanism, confirmed at source: the hydration effect built each option with `recordToOption` inside its async fetch, using the `refObjectSchema` of the render it ran in (`null`), and cached the BUILT option in `pickerResolvedRecords`. `findOption` then found the id in that cache, so every later run of the effect returned early and nothing rebuilt the label. ## The change: keep the RECORD, derive the label (one derivation) `packages/fields/src/widgets/LookupField.tsx` only. - The hydration effect fetches rows and builds no option. It merges them into a new `hydratedRecords` state, keyed by `recordValue` (the value expression `recordToOption` already used, now one helper both read). - `hydratedOptions` is a memo that maps those rows through `recordToOption` with the same inputs the dropdown's `fetchedOptions` uses: the declared `displayField`, `idField`, the description field, `refObjectSchema`, and the field-read gate of the current policy. It re-derives when any of them changes, so the chip follows the schema when it arrives. - `findOption` and `findOptionLoose` consult static, fetched, picked (`pickerResolvedRecords`), then hydrated options. A pick outranks the hydrated row for the same value, as it did when the two shared one cache and the later write won. - The effect's dependency list drops `declaredDisplayField` and `effectiveDescriptionField`, which the effect no longer reads. The eslint disable stays. The reads it hides shrank from `dataSource`, `findOption`, `perms`, `refObjectSchema` to `dataSource`, `findOption` (the `--no-inline-config` message, base vs head). No `key=` remount, and no re-fetch on the schema's arrival. ### Why this route and not the other two - Relabel on arrival (an effect on `refObjectSchema` that rebuilds the cached options) needs the rows anyway. An option cannot be rebuilt from itself: `recordToOption` spreads the record over `label`, so the old label would win the spread. That route is this change plus an effect, and an extra render that still shows the stale label. - Defer labelling until the schema is known needs a "schema settled" state (`getObjectSchema` can be absent, can reject, or can be slow). Every chip would wait on the metadata call, and it still needs a re-run path. It is larger, and slower for the user. - Keeping the record is the pattern the recents rail in the same file already uses (`recentRows` state, `recentOptions` memo). ### Fetch count, measured | ordering | base `findOne` calls | head | |---|---|---| | record first, schema later (the card) | 1 | 1 | | schema arrives while the record fetch is in flight | 2 | 1 | On base the second ordering got the right label only by accident. The schema's arrival changed `effectiveDescriptionField` (it derives from the schema's columns), which re-ran the effect, cancelled the fetch in flight and issued a second one after the schema was known. ### `handleSelect` and the hydrated path Both build the label through `recordToOption` with the same inputs, so they agree once the schema is known: the pin's pick control and the mounted chip both read `HT-001`. The pick path still caches a BUILT option, so a pick made before the schema arrives keeps the no-schema label. That is measured and reported under Acceptance notes; it is not changed here. ### A second input follows too: the policy The effect used to capture the field-read gate of the policy in force when it ran (objectui#10373). The memo reads the current one. So a field the policy denies after the chip is labelled (a policy that loads late) leaves the chip's label, as it leaves the dropdown's. Pinned as row 4. ## Pin: `LookupField.hydratedLabel-10487.test.tsx` | # | row | base | head | |---|---|---|---| | 1 | single hydrated id: the chip reads `HT-001` after the schema; `findOne` once | red, `Acme` | green | | 2 | batched `$in` path: the chips read `HT-001`, `HT-002`; one `$in` query | red, `Acme`, `Initech` | green | | 3 | the schema arrives while the fetch is in flight: chip `HT-001`, `findOne` once | red, 2 calls | green | | 4 | a field denied after the chip is labelled leaves the label (`c1`) | red, `Acme` | green | | 5 | control: the dropdown option reads `HT-001` | green | green | | 6 | control: picking `c1` leaves the chip on `HT-001` | green | green | Rows 1 and 2 also assert the chip read `Acme` before the schema was released, so the fixture's ordering is proven, not assumed. ## Ablations (one-shot, at `011676680`, restored by blob) A1 and A3 ran through `../objectstack/scripts/ablation-replace.mjs`: the anchor hit exactly once, the blob changed, and the restore was proven (blob equal to HEAD's, `git diff HEAD` empty). A2 checked out the base blob and restored the HEAD blob under a trap, proven the same way. The pin imports `./LookupField` directly, so no `dist` is involved. - A1, the derivation frozen: the `hydratedOptions` memo keyed on the rows alone, so the label is built once, when the rows land. Predicted and observed: rows 1, 2 and 4 red; rows 3, 5 and 6 green (3 failed, 3 passed). - A3, the dependency list: the effect's deps regain `declaredDisplayField` and `effectiveDescriptionField`. Predicted and observed: row 3 red (`findOne` called 2 times), the rest green (1 failed, 5 passed). - A2, the whole file at base `db3896c4c` (blob `7593aeb`; restored to HEAD blob `3054087`): rows 1 to 4 red, the two controls green (4 failed, 2 passed). ## Verification (HEAD `011676680`) - `pnpm exec vitest run packages/fields/` from the repo root: 198 files passed and 1 skipped, of 199 (the tracked test files under `packages/fields` also number 199); 3272 tests passed, 7 skipped. - `pnpm --workspace-concurrency=2 --filter '@object-ui/fields^...' run build`, then `pnpm --filter @object-ui/fields run type-check` (`tsc --noEmit && tsc -p tsconfig.test.json`): exit 0. `tsc -p tsconfig.test.json --listFiles` lists the pin. - eslint on the two touched files, per rule, base vs head: `LookupField.tsx` is equal in every rule (`react-hooks/exhaustive-deps` 3 and 3, or 5 and 5 with `--no-inline-config`; `no-explicit-any` 37 and 37). The pin has no messages. - `pnpm check:control-bytes`, `pnpm check:new-line-citations` (0 new citations), `node scripts/check-changeset-presence.mjs`, `pnpm check:changeset-claims` (nothing flagged; its born-false leg found no line address to judge), `node scripts/check-changeset-no-major.mjs`, and `check:test-path-roots`, `check:phantom-deps`, `check:pending-changeset-literals`, `check:unreferenced-sources`, `check:shell-escape-residue`: all exit 0. - NOT MEASURED: CI, and a browser run (the pin drives the real widget in happy-dom). Changeset: `@object-ui/fields` patch. ## Acceptance notes - A behaviour change beyond the chip label: a browse-all (`RecordPickerDialog`) pick replaced `pickerResolvedRecords` wholesale, and that also dropped the hydrated entries. Hydrated rows now live in their own state and survive it. The dialog's records still win for the ids they carry. - A finding, reported to the seat and not filed here: a pick made in the dropdown BEFORE the schema arrives keeps the no-schema label. Measured on head `011676680` with a throwaway probe: options before the schema `Acme`, `Initech`; the chip after the pick `Acme`; the chip after the schema `Acme`; the options after the schema `HT-001`, `HT-002`. `handleSelect` caches the built option it is handed, and the row behind it is not kept, so changing that is a design step, not a mechanical one. The browse-all dialog path (`handlePickerSelectRecords`) builds options the same way and was not measured. Session: `https://claude.ai/code/session_01BA3nKVUwKQJf8DBxrSVtNC` --- _Generated by [Claude Code](https://claude.ai/code/session_01BA3nKVUwKQJf8DBxrSVtNC)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent aa6be30 commit fde4caf

3 files changed

Lines changed: 351 additions & 20 deletions

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
'@object-ui/fields': patch
3+
---
4+
5+
fix(fields): a lookup value hydrated from a bare id is labelled from the referenced object's schema once it arrives (objectui#10487)
6+
7+
A lookup that mounts already holding a value (an edit form opening an existing
8+
record) fetches the referenced record to label its chip. It also asks for the
9+
referenced object's schema, and nothing orders the two. When the record came
10+
back first, the chip was labelled without the schema, on the `name` guess, and
11+
it kept that label. The hydration cached a built option with its label frozen,
12+
and the schema's arrival never rebuilt it. The dropdown, the read cell and the
13+
record page read the object's declared `nameField` for the same record. So the
14+
chip read `Acme` while its own dropdown option read `HT-001`, until the user
15+
picked the record again, and a reload brought `Acme` back.
16+
17+
The hydration now keeps the fetched rows and builds no label. The chip's option
18+
is derived from those rows on every render through the same `recordToOption`
19+
call, with the same inputs, that the dropdown uses. So its label follows the
20+
schema when it arrives. It also follows the permission policy in force: a field
21+
the policy denies after the chip was labelled (a policy that loads late) leaves
22+
the chip's label as it leaves the dropdown's. The record is still fetched once,
23+
and no remount is involved. When
24+
the schema arrived while the record fetch was still in flight, the fetch used to
25+
be cancelled and issued a second time; it is issued once now.
Lines changed: 263 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,263 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* A lookup value hydrated from a bare id takes its label from the referenced
11+
* object's schema once that schema arrives — objectui#10487.
12+
*
13+
* A lookup that mounts holding a stored id fetches that record to label its
14+
* chip, and asks for the referenced object's schema at the same time. Nothing
15+
* orders the two. When the record came back first, the chip was labelled on
16+
* the no-schema path (the `name` guess) and kept that label for good: the
17+
* hydration cached a BUILT option, its label frozen, and the schema's arrival
18+
* never rebuilt it. The dropdown derives its options from their rows on every
19+
* render, so it read the object's declared `nameField` for the same record,
20+
* and one record read two ways side by side — the common edit-form state.
21+
*
22+
* The fixture forces that order: the record fetch resolves while the schema
23+
* request is held open, and the schema is released only after the chip has
24+
* been labelled. Every row carries a `name` value, so a label frozen on the
25+
* no-schema path cannot pass. Pinned:
26+
*
27+
* - the mounted chip reads the declared `nameField` once the schema
28+
* resolves, on the single-id `findOne` path and on the batched `$in` path;
29+
* the record is fetched once — the schema's arrival relabels, it does not
30+
* re-fetch;
31+
* - the other order, the schema arriving while the record fetch is still in
32+
* flight: the chip reads the same text from one fetch. It used to take two
33+
* — the schema's arrival changed a field the hydration effect listed but no
34+
* longer reads, which cancelled the fetch in flight and issued another;
35+
* - the same derivation reads the permission policy in force now: a field the
36+
* policy denies after the chip is labelled leaves the label, as it leaves
37+
* the dropdown's (objectui#10373);
38+
* - control: the dropdown option for the same record reads the same text;
39+
* - control: picking the same record from the dropdown leaves the chip on the
40+
* same text.
41+
*/
42+
43+
import * as React from 'react';
44+
import { describe, it, expect, vi, afterEach } from 'vitest';
45+
import { render, screen, cleanup, waitFor, act, fireEvent } from '@testing-library/react';
46+
import '@testing-library/jest-dom';
47+
import { SchemaRendererContext } from '@object-ui/react';
48+
import { PermissionProvider } from '@object-ui/permissions';
49+
import { LookupField } from './LookupField';
50+
51+
const CONTRACT_FIELDS: Record<string, unknown> = {
52+
contract_no: { type: 'text', label: 'Contract No' },
53+
name: { type: 'text', label: 'Name' },
54+
};
55+
56+
const ROWS: Record<string, unknown>[] = [
57+
{ id: 'c1', name: 'Acme', contract_no: 'HT-001' },
58+
{ id: 'c2', name: 'Initech', contract_no: 'HT-002' },
59+
];
60+
61+
/**
62+
* A backend whose `getObjectSchema` answers only when `releaseSchema()` is
63+
* called — so the test, not the scheduler, decides which of the two requests
64+
* wins. With `holdRecord`, `findOne` also answers only on `releaseRecord()`.
65+
*/
66+
function makeBackend({ holdRecord = false }: { holdRecord?: boolean } = {}) {
67+
let releaseSchema!: () => void;
68+
const schemaHeld = new Promise<void>((resolve) => {
69+
releaseSchema = resolve;
70+
});
71+
let releaseRecord!: () => void;
72+
const recordHeld = new Promise<void>((resolve) => {
73+
releaseRecord = resolve;
74+
});
75+
const find = vi.fn(async (objectName: string, params?: { $filter?: { id?: { $in?: unknown[] } } }) => {
76+
if (objectName !== 'contract') return { data: [], total: 0 };
77+
const wanted = params?.$filter?.id?.$in;
78+
const rows = wanted ? ROWS.filter((r) => wanted.includes(r.id)) : ROWS;
79+
return { data: rows.map((r) => ({ ...r })), total: rows.length };
80+
});
81+
const findOne = vi.fn(async (objectName: string, id: string) => {
82+
if (holdRecord) await recordHeld;
83+
const row = objectName === 'contract' ? ROWS.find((r) => r.id === id) : undefined;
84+
return row ? { ...row } : null;
85+
});
86+
const getObjectSchema = vi.fn(async (objectName: string) => {
87+
await schemaHeld;
88+
return objectName === 'contract'
89+
? { name: 'contract', nameField: 'contract_no', fields: CONTRACT_FIELDS }
90+
: undefined;
91+
});
92+
return { ds: { find, findOne, getObjectSchema }, releaseSchema, releaseRecord };
93+
}
94+
95+
type Backend = ReturnType<typeof makeBackend>['ds'];
96+
97+
/** Holds the value, so a pick commits and the chip re-resolves from it. */
98+
function Host({ ds, initial, multiple = false }: { ds: Backend; initial: unknown; multiple?: boolean }) {
99+
const [value, setValue] = React.useState<unknown>(initial);
100+
return (
101+
<SchemaRendererContext.Provider value={{ dataSource: ds } as never}>
102+
<LookupField
103+
value={value}
104+
onChange={setValue}
105+
dataSource={ds as never}
106+
field={{ reference_to: 'contract', multiple } as never}
107+
/>
108+
</SchemaRendererContext.Provider>
109+
);
110+
}
111+
112+
/**
113+
* `Host` under the real role-based provider. The "Deny name" button makes
114+
* `name` a field the viewer may not read on `contract`, so the test can change
115+
* the policy in force after the chip is labelled, as a policy that loads late
116+
* does.
117+
*/
118+
function PolicyHost({ ds }: { ds: Backend }) {
119+
const [deny, setDeny] = React.useState<string[]>([]);
120+
return (
121+
<PermissionProvider
122+
roles={[]}
123+
userRoles={['viewer']}
124+
permissions={[
125+
{
126+
object: 'contract',
127+
roles: {
128+
viewer: { actions: ['read'], fieldPermissions: deny.map((field) => ({ field, read: false })) },
129+
},
130+
},
131+
]}
132+
>
133+
<button type="button" onClick={() => setDeny(['name'])}>
134+
Deny name
135+
</button>
136+
<Host ds={ds} initial="c1" />
137+
</PermissionProvider>
138+
);
139+
}
140+
141+
async function settle(): Promise<void> {
142+
for (let i = 0; i < 6; i++) {
143+
await act(async () => {
144+
await new Promise((r) => setTimeout(r, 0));
145+
});
146+
}
147+
}
148+
149+
/** Each selected-value chip's label, read from its remove control's name. */
150+
function chipLabels(): string[] {
151+
return screen
152+
.queryAllByRole('button', { name: /^Remove / })
153+
.map((b) => (b.getAttribute('aria-label') ?? '').replace(/^Remove /, ''));
154+
}
155+
156+
/**
157+
* Mount holding `initial`, let the record fetch label the chip while the schema
158+
* is held, then release the schema. Returns the chip labels read at each
159+
* moment.
160+
*/
161+
async function mountHydrated(initial: unknown, multiple = false) {
162+
const { ds, releaseSchema } = makeBackend();
163+
render(<Host ds={ds} initial={initial} multiple={multiple} />);
164+
await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalledWith('contract'));
165+
await waitFor(() => expect(chipLabels().length).toBeGreaterThan(0));
166+
await settle();
167+
const beforeSchema = chipLabels();
168+
await act(async () => {
169+
releaseSchema();
170+
});
171+
await settle();
172+
return { ds, beforeSchema, afterSchema: chipLabels() };
173+
}
174+
175+
afterEach(() => {
176+
cleanup();
177+
try {
178+
localStorage.clear();
179+
} catch {
180+
/* no storage in this environment */
181+
}
182+
});
183+
184+
describe('LookupField — a hydrated value is labelled from the schema once it arrives (objectui#10487)', () => {
185+
it('a single hydrated id: the mounted chip reads the declared nameField after the schema resolves', async () => {
186+
const { ds, beforeSchema, afterSchema } = await mountHydrated('c1');
187+
// The fixture's order held: the chip was labelled before the schema existed.
188+
expect(beforeSchema).toEqual(['Acme']);
189+
expect(afterSchema).toEqual(['HT-001']);
190+
// The schema's arrival relabels the record already fetched; it does not
191+
// fetch it again.
192+
expect(ds.findOne).toHaveBeenCalledTimes(1);
193+
expect(ds.findOne).toHaveBeenCalledWith('contract', 'c1');
194+
});
195+
196+
it('several hydrated ids (the batched $in path): every chip reads the declared nameField after the schema resolves', async () => {
197+
const { ds, beforeSchema, afterSchema } = await mountHydrated(['c1', 'c2'], true);
198+
expect(beforeSchema).toEqual(['Acme', 'Initech']);
199+
expect(afterSchema).toEqual(['HT-001', 'HT-002']);
200+
const batched = ds.find.mock.calls.filter(([, params]) => params?.$filter?.id?.$in);
201+
expect(batched).toHaveLength(1);
202+
});
203+
204+
it('the schema arrives while the record fetch is in flight: one fetch, and the chip reads the declared nameField', async () => {
205+
const { ds, releaseSchema, releaseRecord } = makeBackend({ holdRecord: true });
206+
render(<Host ds={ds} initial="c1" />);
207+
await waitFor(() => expect(ds.findOne).toHaveBeenCalledTimes(1));
208+
await act(async () => {
209+
releaseSchema();
210+
});
211+
await settle();
212+
await act(async () => {
213+
releaseRecord();
214+
});
215+
await settle();
216+
expect(chipLabels()).toEqual(['HT-001']);
217+
// The schema's arrival does not cancel the fetch in flight to issue another.
218+
expect(ds.findOne).toHaveBeenCalledTimes(1);
219+
});
220+
221+
it('the same derivation follows the policy: a field denied after the chip is labelled leaves the label', async () => {
222+
// The schema is never released, so this row reads the no-schema path.
223+
const { ds } = makeBackend();
224+
render(<PolicyHost ds={ds} />);
225+
await waitFor(() => expect(chipLabels()).toEqual(['Acme']));
226+
await settle();
227+
await act(async () => {
228+
fireEvent.click(screen.getByRole('button', { name: 'Deny name' }));
229+
});
230+
await settle();
231+
// Nothing else on the row is nameable on this path, so the label falls
232+
// through to the id — the label the dropdown builds for the same row.
233+
expect(chipLabels()).toEqual(['c1']);
234+
expect(ds.findOne).toHaveBeenCalledTimes(1);
235+
});
236+
237+
it('control: the dropdown option for the same record reads the declared nameField', async () => {
238+
await mountHydrated('c1');
239+
await act(async () => {
240+
fireEvent.click(screen.getByTestId('lookup-trigger'));
241+
});
242+
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(2));
243+
await settle();
244+
expect(screen.getAllByRole('option').map((el) => el.getAttribute('title'))).toEqual(['HT-001', 'HT-002']);
245+
});
246+
247+
it('control: picking the same record from the dropdown leaves the chip on the declared nameField', async () => {
248+
await mountHydrated('c1');
249+
await act(async () => {
250+
fireEvent.click(screen.getByTestId('lookup-trigger'));
251+
});
252+
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(2));
253+
await settle();
254+
await act(async () => {
255+
fireEvent.click(screen.getAllByRole('option')[0]);
256+
});
257+
await settle();
258+
// The popover closed on the pick, so no option row supplies the text: the
259+
// chip reads the option the pick cached.
260+
expect(screen.queryAllByRole('option')).toHaveLength(0);
261+
expect(chipLabels()).toEqual(['HT-001']);
262+
});
263+
});

0 commit comments

Comments
 (0)