Skip to content

Commit 37512a4

Browse files
committed
feat(fields): resolve { $record } lookupFilters only where a record form says a record is being edited
A record form stamps withRecordBeingEdited on a lookup whose lookupFilters read { $record }; the picker resolves the references only on that stamp. Every other host, such as a bulk action dialog handing the widget its sibling parameters, leaves every { $record } entry out. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ADHkmTKRu1t68jcJGgRYi3
1 parent 34d869b commit 37512a4

7 files changed

Lines changed: 146 additions & 53 deletions

File tree

‎ui/packages/fields/src/index.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5383,7 +5383,7 @@ export { PERMISSION_SET_GRANT_COLUMNS } from './widgets/permissionSetHolders.js'
53835383
// name column by its object and its column, not by its column name alone.
53845384
export { FORM_OBJECT_KEY, withFormObject } from './widgets/permissionSetHolders.js';
53855385
// A lookup whose `lookupFilters` read a `{ $record }` hop carries the object each hop points at.
5386-
export { RECORD_HOP_OBJECTS_KEY, withRecordHopObjects } from './widgets/lookupRecordReference.js';
5386+
export { RECORD_BEING_EDITED_KEY, withRecordBeingEdited } from './widgets/lookupRecordReference.js';
53875387
// New widgets according to @objectstack/spec
53885388
export * from './widgets/ColorField.js';
53895389
export * from './widgets/SliderField.js';

‎ui/packages/fields/src/widgets/LookupField.recordReference-34197.test.tsx‎

Lines changed: 67 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,19 @@
1616
* value is empty, re-queries when a referenced field changes, and sends
1717
* `orEmpty: true` as an `$or` with a null match on the same column. Literal
1818
* entries and `dependsOn` query exactly as before.
19+
*
20+
* Resolution is opt-in by the host: only a field a record form stamped
21+
* (`withRecordBeingEdited`) reads the values it is handed. A host that edits
22+
* no single record — a bulk action dialog handing the widget its sibling
23+
* parameters — leaves every `{ $record }` entry out.
1924
*/
2025

2126
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
2227
import '@testing-library/jest-dom';
2328
import { describe, it, expect, vi, beforeEach } from 'vitest';
2429
import { LookupField } from './LookupField';
2530
import { lookupFiltersToRecord } from './RecordPickerDialog';
26-
import { resolveLookupFilters, withRecordHopObjects } from './lookupRecordReference';
31+
import { RECORD_BEING_EDITED_KEY, resolveLookupFilters, withRecordBeingEdited } from './lookupRecordReference';
2732

2833
const books = [{ id: 'b1', name: 'Standard 2026' }];
2934

@@ -42,6 +47,11 @@ function priceBookField(lookupFilters: unknown[], extra: Record<string, unknown>
4247
return { name: 'price_book', label: 'Price Book', reference: 'price_book', lookupFilters, ...extra } as any;
4348
}
4449

50+
/** The field as a record form hands it: stamped as drawn for a single record being edited. */
51+
function formField(lookupFilters: unknown[], objectFields: Record<string, unknown> = {}) {
52+
return withRecordBeingEdited(priceBookField(lookupFilters), objectFields);
53+
}
54+
4555
async function openPopover() {
4656
await act(async () => {
4757
fireEvent.click(screen.getByRole('button', { name: /select/i }));
@@ -61,7 +71,7 @@ describe('LookupField — { $record } lookupFilters values (#34197)', () => {
6171
const ds = makeDataSource();
6272
render(
6373
<LookupField
64-
field={priceBookField([{ field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' } }])}
74+
field={formField([{ field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' } }])}
6575
value={undefined}
6676
onChange={vi.fn()}
6777
dataSource={ds}
@@ -75,8 +85,8 @@ describe('LookupField — { $record } lookupFilters values (#34197)', () => {
7585

7686
it('reads a one-hop path off the row the lookup points at, and queries once with its value', async () => {
7787
const ds = makeDataSource({ 'account:a1': { id: 'a1', cb_market: 'm9' } });
78-
const field = withRecordHopObjects(
79-
priceBookField([{ field: 'cb_market', operator: 'eq', value: { $record: 'account.cb_market' } }]),
88+
const field = formField(
89+
[{ field: 'cb_market', operator: 'eq', value: { $record: 'account.cb_market' } }],
8090
{ account: { type: 'lookup', reference: 'account' } },
8191
);
8292
render(
@@ -92,7 +102,7 @@ describe('LookupField — { $record } lookupFilters values (#34197)', () => {
92102
const ds = makeDataSource();
93103
render(
94104
<LookupField
95-
field={priceBookField([{ field: 'cb_market', operator: 'eq', value: { $record: 'account.cb_market' } }])}
105+
field={formField([{ field: 'cb_market', operator: 'eq', value: { $record: 'account.cb_market' } }])}
96106
value={undefined}
97107
onChange={vi.fn()}
98108
dataSource={ds}
@@ -114,7 +124,7 @@ describe('LookupField — { $record } lookupFilters values (#34197)', () => {
114124
const ds = makeDataSource();
115125
const { unmount } = render(
116126
<LookupField
117-
field={priceBookField(filters)}
127+
field={formField(filters)}
118128
value={undefined}
119129
onChange={vi.fn()}
120130
dataSource={ds}
@@ -127,15 +137,15 @@ describe('LookupField — { $record } lookupFilters values (#34197)', () => {
127137
unmount();
128138

129139
const bare = makeDataSource();
130-
render(<LookupField field={priceBookField(filters)} value={undefined} onChange={vi.fn()} dataSource={bare} />);
140+
render(<LookupField field={formField(filters)} value={undefined} onChange={vi.fn()} dataSource={bare} />);
131141
await openPopover();
132142
await waitFor(() => expect(candidateFilters(bare)).toHaveLength(1));
133143
expect(candidateFilters(bare)[0]).toEqual({ is_active: true });
134144
});
135145

136146
it('re-queries once when a referenced field changes, and not when another field does', async () => {
137147
const ds = makeDataSource();
138-
const field = priceBookField([{ field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' } }]);
148+
const field = formField([{ field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' } }]);
139149
const { rerender } = render(
140150
<LookupField field={field} value={undefined} onChange={vi.fn()} dataSource={ds} dependentValues={{ quote_date: '2026-11-01', subject: 'a' }} />,
141151
);
@@ -163,7 +173,7 @@ describe('LookupField — { $record } lookupFilters values (#34197)', () => {
163173
const ds = makeDataSource();
164174
render(
165175
<LookupField
166-
field={priceBookField([
176+
field={formField([
167177
{ field: 'is_active', operator: 'eq', value: true },
168178
{ field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' }, orEmpty: true },
169179
{ field: 'valid_to', operator: 'gte', value: { $record: 'quote_date' }, orEmpty: true },
@@ -189,7 +199,7 @@ describe('LookupField — { $record } lookupFilters values (#34197)', () => {
189199
const ds = makeDataSource();
190200
render(
191201
<LookupField
192-
field={priceBookField([{ field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' }, orEmpty: true }])}
202+
field={formField([{ field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' }, orEmpty: true }])}
193203
value={undefined}
194204
onChange={vi.fn()}
195205
dataSource={ds}
@@ -207,6 +217,53 @@ describe('LookupField — { $record } lookupFilters values (#34197)', () => {
207217
}
208218
});
209219

220+
it('a host that does not say a record is being edited leaves every { $record } entry out, even when its values hold one of that name', async () => {
221+
// The bulk action dialog's shape: the widget is handed the dialog's sibling
222+
// parameter values, and its field carries no record-form stamp.
223+
const filters = [
224+
{ field: 'is_active', operator: 'eq', value: true },
225+
{ field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' } },
226+
{ field: 'cb_market', operator: 'eq', value: { $record: 'account.cb_market' } },
227+
];
228+
const ds = makeDataSource({ 'account:a1': { id: 'a1', cb_market: 'm9' } });
229+
render(
230+
<LookupField
231+
field={priceBookField(filters)}
232+
value={undefined}
233+
onChange={vi.fn()}
234+
dataSource={ds}
235+
dependentValues={{ quote_date: '2026-11-01', account: { id: 'a1', cb_market: 'm7' } }}
236+
/>,
237+
);
238+
await openPopover();
239+
await waitFor(() => expect(candidateFilters(ds)).toHaveLength(1));
240+
expect(candidateFilters(ds)[0]).toEqual({ is_active: true });
241+
expect(ds.findOne).not.toHaveBeenCalled();
242+
});
243+
244+
it('CONTROL: the same field and values on a record-form host resolve', async () => {
245+
const filters = [
246+
{ field: 'is_active', operator: 'eq', value: true },
247+
{ field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' } },
248+
{ field: 'cb_market', operator: 'eq', value: { $record: 'account.cb_market' } },
249+
];
250+
const ds = makeDataSource();
251+
const field = formField(filters, { account: { type: 'lookup', reference: 'account' } });
252+
expect(field[RECORD_BEING_EDITED_KEY]).toEqual({ hopObjects: { account: 'account' } });
253+
render(
254+
<LookupField
255+
field={field}
256+
value={undefined}
257+
onChange={vi.fn()}
258+
dataSource={ds}
259+
dependentValues={{ quote_date: '2026-11-01', account: { id: 'a1', cb_market: 'm7' } }}
260+
/>,
261+
);
262+
await openPopover();
263+
await waitFor(() => expect(candidateFilters(ds)).toHaveLength(1));
264+
expect(candidateFilters(ds)[0]).toEqual({ is_active: true, valid_from: { $lte: '2026-11-01' }, cb_market: 'm7' });
265+
});
266+
210267
it('CONTROL: a literal entry and a dependsOn entry query exactly as before', async () => {
211268
const ds = makeDataSource();
212269
render(

‎ui/packages/fields/src/widgets/LookupField.tsx‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,16 @@ import { PHONE_TOUCH_HEIGHT, PHONE_TOUCH_SQUARE } from './touchTarget.js';
1616
import type { DataSource, FormField, QueryParams, LookupColumnDef, LookupFieldMetadata } from '@object-ui/types';
1717
import { RecordPickerDialog, lookupFiltersToRecord } from './RecordPickerDialog.js';
1818
import {
19-
readRecordHopObjects,
19+
readRecordBeingEdited,
2020
readsRecord,
2121
resolveLookupFilters,
2222
useRecordHopRows,
2323
type LookupFilterEntry,
2424
} from './lookupRecordReference.js';
2525
import type { RecordPickerFilterColumn } from './RecordPickerDialog.js';
26+
27+
/** The record a host that edits none hands `{ $record }` resolution: nothing to read. */
28+
const NO_EDITED_RECORD: Readonly<Record<string, unknown>> = Object.freeze({});
2629
import { PeoplePicker } from './PeoplePicker.js';
2730
import { useRecordQuery } from './useRecordQuery.js';
2831
import { objectResolvesSearch } from './searchOffer.js';
@@ -550,18 +553,26 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro
550553
* values, so the candidates re-query; a change to any other field of the
551554
* record leaves the resolved list, and so every query, as it was.
552555
*
556+
* Opt-in by the host: only a field a record form stamped
557+
* (`withRecordBeingEdited`) resolves against the values it is handed. On any
558+
* other host — a bulk action over selected rows, an action's parameter
559+
* dialog — those values are not the record the path names, so every
560+
* `{ $record }` entry is left out, as on a picker given no record at all.
561+
*
553562
* Filters that read no record pass through as authored, the same array.
554563
*/
555564
const filtersReadRecord = readsRecord(lookupFilters);
565+
const recordBeingEdited = readRecordBeingEdited(fieldMeta);
566+
const editedRecord = recordBeingEdited ? resolvedDependentValues : NO_EDITED_RECORD;
556567
const recordHops = useRecordHopRows(
557568
filtersReadRecord ? lookupFilters : undefined,
558-
resolvedDependentValues,
559-
readRecordHopObjects(fieldMeta),
569+
editedRecord,
570+
recordBeingEdited?.hopObjects,
560571
dataSource,
561572
);
562573
const recordReadsPending = recordHops.pending;
563574
const resolvedFiltersKey = filtersReadRecord && lookupFilters
564-
? JSON.stringify(resolveLookupFilters(lookupFilters, resolvedDependentValues, recordHops.rows))
575+
? JSON.stringify(resolveLookupFilters(lookupFilters, editedRecord, recordHops.rows))
565576
: '';
566577
const resolvedRecordFilters = useMemo<LookupFilterEntry[] | undefined>(
567578
() => (resolvedFiltersKey ? (JSON.parse(resolvedFiltersKey) as LookupFilterEntry[]) : undefined),

‎ui/packages/fields/src/widgets/lookupRecordReference.ts‎

Lines changed: 42 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,15 @@
1616
* Invariants:
1717
* - A path is a field of the edited record (`quote_date`) or one lookup hop
1818
* from it (`account.cb_market`).
19+
* - The picker resolves a reference only where its host SAYS a single record
20+
* is being edited: a record form stamps that on the field it hands the
21+
* widget (`withRecordBeingEdited`). Every other host — a bulk action over
22+
* selected rows, an action's parameter dialog, a filter panel — leaves every
23+
* `{ $record }` entry out, whatever values it passes the widget: the values
24+
* such a host passes are not the record the author's path names.
1925
* - An entry whose referenced value is empty — null, unset, `''`, an empty
2026
* list, a hop whose lookup is unset — is left out of the query, the rule an
21-
* unset `dependsOn` parent follows. A host that holds no single record
22-
* passes none, so every `{ $record }` entry is left out there.
27+
* unset `dependsOn` parent follows.
2328
* - A hop whose row cannot be read is left out the same way: the picker
2429
* narrows the choice only, and the save is the server's to judge.
2530
* - ⛔ No `{ $record }` value ever reaches the wire: `lookupFiltersToRecord`
@@ -33,13 +38,22 @@ import type { Field as SpecField, LookupFilterRecordReference } from '@objectsta
3338
export type LookupFilterEntry = NonNullable<SpecField['lookupFilters']>[number];
3439

3540
/**
36-
* The key a record form stamps, on a lookup field it hands a widget, the
37-
* object each `{ $record }` hop's lookup points at (`{ account: 'account' }`):
38-
* a widget receives one field, not the object it is drawn for, so it could
39-
* not otherwise name the object to read `account`'s id from. The same
40-
* hand-off shape as `FOLLOWED_PARENT_OBJECT_KEY` (`currency.ts`).
41+
* The key a record form stamps on a lookup field whose `lookupFilters` read
42+
* `{ $record }`, the host's statement that a single record is being edited
43+
* here. Its value names the object each hop's lookup points at
44+
* (`{ hopObjects: { account: 'account' } }`): a widget receives one field,
45+
* not the object it is drawn for, so it could not otherwise name the object
46+
* to read `account`'s row from. The same hand-off shape as
47+
* `FOLLOWED_PARENT_OBJECT_KEY` (`currency.ts`) and `FORM_OBJECT_KEY`.
48+
*
49+
* ⛔ Opt-in: a widget whose field carries no stamp resolves no `{ $record }`.
4150
*/
42-
export const RECORD_HOP_OBJECTS_KEY = 'recordHopObjects';
51+
export const RECORD_BEING_EDITED_KEY = 'recordBeingEdited';
52+
53+
/** What a record form stamps under {@link RECORD_BEING_EDITED_KEY}. */
54+
export interface RecordBeingEdited {
55+
hopObjects: Readonly<Record<string, string>>;
56+
}
4357

4458
/** One `{ $record }` hop: the lookup on the edited record and the field read on its target. */
4559
export interface RecordReferenceHop {
@@ -101,28 +115,33 @@ function referencedId(v: unknown): string | undefined {
101115
}
102116

103117
/**
104-
* `def` with the object each `{ $record }` hop's lookup references stamped
105-
* under {@link RECORD_HOP_OBJECTS_KEY}, or `def` itself when its filters name
106-
* no hop or the object declares none of the hop fields as a relation.
118+
* `def` stamped under {@link RECORD_BEING_EDITED_KEY}: the record form's
119+
* statement that the widget is drawn for a single record being edited, with
120+
* the object each `{ $record }` hop's lookup references (read off `fields`,
121+
* the edited object's field map). `def` itself when its filters read no
122+
* record. Only a host that edits one record calls this.
107123
*/
108-
export function withRecordHopObjects<T extends object>(
124+
export function withRecordBeingEdited<T extends object>(
109125
def: T,
110126
fields: Readonly<Record<string, unknown>> | null | undefined,
111127
): T {
112-
const hops = recordReferenceHops((def as { lookupFilters?: LookupFilterEntry[] }).lookupFilters);
113-
if (hops.length === 0) return def;
114-
const objects: Record<string, string> = {};
115-
for (const { via } of hops) {
128+
const filters = (def as { lookupFilters?: LookupFilterEntry[] }).lookupFilters;
129+
if (!readsRecord(filters)) return def;
130+
const hopObjects: Record<string, string> = {};
131+
for (const { via } of recordReferenceHops(filters)) {
116132
const reference = (fields?.[via] as { reference?: unknown } | undefined)?.reference;
117-
if (typeof reference === 'string' && reference !== '') objects[via] = reference;
133+
if (typeof reference === 'string' && reference !== '') hopObjects[via] = reference;
118134
}
119-
return Object.keys(objects).length > 0 ? { ...def, [RECORD_HOP_OBJECTS_KEY]: objects } : def;
135+
const stamp: RecordBeingEdited = { hopObjects };
136+
return { ...def, [RECORD_BEING_EDITED_KEY]: stamp };
120137
}
121138

122-
/** The hop objects a form stamped on `field`, or `undefined`. */
123-
export function readRecordHopObjects(field: unknown): Readonly<Record<string, string>> | undefined {
124-
const value = (field as Record<string, unknown> | null | undefined)?.[RECORD_HOP_OBJECTS_KEY];
125-
return isRow(value) ? (value as Record<string, string>) : undefined;
139+
/** The record-being-edited stamp a form put on `field`, or `undefined` when none did. */
140+
export function readRecordBeingEdited(field: unknown): RecordBeingEdited | undefined {
141+
const value = (field as Record<string, unknown> | null | undefined)?.[RECORD_BEING_EDITED_KEY];
142+
if (!isRow(value)) return undefined;
143+
const hopObjects = isRow(value.hopObjects) ? (value.hopObjects as Record<string, string>) : {};
144+
return { hopObjects };
126145
}
127146

128147
/**
@@ -190,7 +209,7 @@ function warnUnreadableHop(via: string, field: string, object: string | undefine
190209
+ (object
191210
? `no data source here can read ${object} rows.`
192211
: `the record holds "${via}" as an id, and this host did not name the object it points at `
193-
+ `(a record form stamps it with withRecordHopObjects).`),
212+
+ `(a record form stamps it with withRecordBeingEdited).`),
194213
);
195214
}
196215

‎ui/packages/plugin-form/src/ObjectForm.tsx‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import type { ObjectFormSchema, FormField, FormSchema, DataSource } from '@objec
1818
import { SchemaRenderer, useSafeFieldLabel } from '@object-ui/react';
1919
import { pickLocalized, useObjectTranslation, useLocalization, withHomeAmountSource } from '@object-ui/i18n';
2020
import { useRecordInvalidation } from './recordInvalidation';
21-
import { mapFieldTypeToFormType, buildValidationRules, formatFileSize, fieldHelpText, withFollowedParentObject, withFormObject, withRecordHopObjects, PERMISSION_SET_GRANT_COLUMNS } from '@object-ui/fields';
21+
import { mapFieldTypeToFormType, buildValidationRules, formatFileSize, fieldHelpText, withFollowedParentObject, withFormObject, withRecordBeingEdited, PERMISSION_SET_GRANT_COLUMNS } from '@object-ui/fields';
2222
import { isExpressionComputedField } from '@object-ui/core';
2323
import { useIsMobile, toast } from '@object-ui/components';
2424
import { resolveSuccessNavigate } from './successBehavior';
@@ -1021,11 +1021,13 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource
10211021
// A `permission-ref` field also carries the object this form edits
10221022
// (objectstack#32795), so the widget tells the grant's name column
10231023
// from a column of the same name on another object.
1024-
// A lookup whose `lookupFilters` read a `{ $record }` hop also
1025-
// carries the object each hop's lookup points at, so its picker can
1026-
// read the hop for the id the form holds.
1024+
// A lookup whose `lookupFilters` read `{ $record }` also carries the
1025+
// form's statement that one record is being edited here, with the
1026+
// object each hop's lookup points at: its picker resolves the
1027+
// references only on that stamp, and reads a hop for the id the
1028+
// form holds.
10271029
field: withFormObject(
1028-
withRecordHopObjects(
1030+
withRecordBeingEdited(
10291031
withFollowedParentObject(withHomeAmountSource(field, objectSchema.fields, name), objectSchema.fields),
10301032
objectSchema.fields,
10311033
),

0 commit comments

Comments
 (0)