Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .changeset/35053-lookup-label-namefield.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
'@object-ui/core': patch
'@object-ui/plugin-grid': patch
'@object-ui/components': patch
---

fix(ui): grouping headers and the filter value picker name a lookup by its target's `nameField`, and the empty group is translated

Clause-②: yes (widening)
Metadata-protocol: none

A lookup with no `displayField` is now named by the target object's declared `nameField`, the default the spec states for `displayField` ("the referenced object's name/title"). This is the same title the lookup's grid cell and the record header already show. Before, three places guessed a `name`, `label` or `title` key, and showed the raw record id when the target had none, for example a target titled by an autonumber such as `DEAL-2026-0001`:

- **Group headers of a list grouped by the lookup**, both server-grouped and client-grouped.
- **Filter builder value picker options** for the lookup, and the chip of the chosen value.

An explicit `displayField` on the lookup still wins. Grouping and filtering stay keyed by record id, so two records with the same title stay separate groups and separate options. The picker reads the target object's definition once per picker. The ObjectStack adapter serves later reads of it from its metadata cache.

The group of rows with no value now reads the grid's own empty-value string (`grid.empty`, for example "Empty" in English and "空" in Chinese) instead of the untranslated `(empty)`. It keeps its place in the group order: first when ascending and last when descending.

`@object-ui/core` adds `referencedRecordTitle(targetDef, record, displayField?)` to its public entry, a new export. It gives the title of a referenced record using the lookup's `displayField`, then the record-title ladder of `getRecordDisplayName`, and returns `undefined` instead of the `Record #<id>` floor.
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/**
* 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.
*/

/**
* objectstack#35053 — the filter value picker names a lookup's candidate
* records by the TARGET object's declared `nameField` when the lookup declares
* no `displayField`, the default the spec's `FieldSchema.displayField` states.
* The target here is titled by an autonumber `deal_number` and has no `name`,
* `label` or `title`, so the old `displayField || "name"` read printed every
* option, and the chosen value's chip, as the raw record id.
*
* The control: an explicit `displayField` on the lookup still wins. The value
* the picker writes stays the record's id.
*/
import { describe, it, expect, vi } from 'vitest';
import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import { SchemaRendererContext } from '@object-ui/react';
import { FilterBuilder } from '../custom/filter-builder';

const TARGET = 'crm_deal_confirmation';

const TARGET_DEF = {
name: TARGET,
nameField: 'deal_number',
fields: {
deal_number: { type: 'autonumber', label: 'Deal Number' },
code: { type: 'text', label: 'Code' },
},
};

const DEALS = [
{ id: 'KC3TKTKQPLwGVqsJ', deal_number: 'DEAL-2026-0002', code: 'C-2' },
{ id: 'T1lF9T1kq45KAN06', deal_number: 'DEAL-2026-0001', code: 'C-1' },
];

function fakeDataSource() {
return {
find: vi.fn(async (_object: string, params: Record<string, any>) => {
const ids: string[] | undefined = params.$filter?.id?.$in;
return { data: ids ? DEALS.filter((d) => ids.includes(d.id)) : DEALS };
}),
getObjectSchema: vi.fn(async (name: string) => (name === TARGET ? TARGET_DEF : undefined)),
};
}

function renderRow(lookupExtra: Record<string, unknown>, value: unknown, dataSource: unknown) {
const onChange = vi.fn();
const fields = [
{ value: 'deal_confirmation', label: 'Deal', type: 'lookup', referenceTo: TARGET, ...lookupExtra },
];
const tree = {
id: 'root',
logic: 'and',
conditions: [{ id: 'c1', field: 'deal_confirmation', operator: 'equals', value }],
};
render(
<SchemaRendererContext.Provider value={{ dataSource } as any}>
<FilterBuilder fields={fields as any} value={tree as any} onChange={onChange} />
</SchemaRendererContext.Provider>,
);
return onChange;
}

describe('filter value picker names lookup options by the target nameField (objectstack#35053)', () => {
it('lists the deal numbers, not the record ids, and writes the id it picks', async () => {
const dataSource = fakeDataSource();
const onChange = renderRow({}, '', dataSource);
fireEvent.click(screen.getByTestId('lookup-picker-deal_confirmation'));
const option = await screen.findByText('DEAL-2026-0001');
expect(screen.getByText('DEAL-2026-0002')).toBeInTheDocument();
expect(screen.queryByText(DEALS[1].id)).not.toBeInTheDocument();
expect(dataSource.getObjectSchema).toHaveBeenCalledWith(TARGET);

fireEvent.click(option);
const calls = onChange.mock.calls;
expect(calls[calls.length - 1][0].conditions[0]).toMatchObject({ value: DEALS[1].id });
});

it('the chosen value\'s chip reads the deal number', async () => {
renderRow({}, DEALS[1].id, fakeDataSource());
await waitFor(() =>
expect(screen.getByTestId('lookup-picker-deal_confirmation')).toHaveTextContent('DEAL-2026-0001'),
);
});

it('CONTROL — an explicit `displayField` on the lookup still wins over the nameField', async () => {
renderRow({ displayField: 'code' }, '', fakeDataSource());
fireEvent.click(screen.getByTestId('lookup-picker-deal_confirmation'));
expect(await screen.findByText('C-1')).toBeInTheDocument();
expect(screen.getByText('C-2')).toBeInTheDocument();
expect(screen.queryByText('DEAL-2026-0001')).not.toBeInTheDocument();
});
});
62 changes: 38 additions & 24 deletions ui/packages/components/src/custom/filter-builder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
type ViewFilterRule,
} from "@objectstack/spec/ui"
import { DATE_RANGE_PRESETS, expandEmptyOperator, type DateRangePreset } from "@objectstack/spec/data"
import { SchemaRendererContext } from "@object-ui/react"
import { SchemaRendererContext, useSettledSchema } from "@object-ui/react"
import {
FILTER_DATE_LIKE_TYPES,
FILTER_LOOKUP_LIKE_TYPES,
Expand All @@ -36,6 +36,7 @@ import {
ComponentRegistry,
isRealCalendarDate,
isRetiredFieldType,
referencedRecordTitle,
reportRetiredFieldType,
toDateTimeInputValue,
} from "@object-ui/core"
Expand Down Expand Up @@ -2712,17 +2713,27 @@ function LookupValuePicker({ field, value, multiple, onChange }: LookupValuePick
// list that disagrees with the gate about what is live.
const referenceTo =
field.referenceTo || (field.type === "user" ? "users" : undefined)
const displayField = field.displayField || "name"
// The lookup's own `displayField` when it declares one; otherwise the target
// object's declared `nameField` names each option (objectstack#35053), read
// from the target's definition: one schema read per picker, which the
// ObjectStack adapter serves from its metadata cache after the first.
const displayField = field.displayField || undefined
const idField = field.idField || "id"
const { def: targetDef } = useSettledSchema(
referenceTo ?? "",
referenceTo && dataSource && typeof dataSource.find === "function" ? dataSource : undefined,
)

const [open, setOpen] = React.useState(false)
const [searchQuery, setSearchQuery] = React.useState("")
const [options, setOptions] = React.useState<LookupOption[]>([])
// The records the search answered; their labels are derived at render, so
// a target definition that lands after them still names them.
const [optionRecords, setOptionRecords] = React.useState<any[]>([])
const [loading, setLoading] = React.useState(false)
const [error, setError] = React.useState<string | null>(null)
// Resolved labels for currently selected ids (so we can render chips even
// when the selection isn't part of the latest fetched page).
const [resolved, setResolved] = React.useState<Record<string, string>>({})
// The records of the currently selected ids, by id (so we can render chips
// even when the selection isn't part of the latest fetched page).
const [resolvedRecords, setResolvedRecords] = React.useState<Record<string, any>>({})
const debounceRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)

const selectedIds: string[] = React.useMemo(() => {
Expand All @@ -2736,14 +2747,21 @@ function LookupValuePicker({ field, value, multiple, onChange }: LookupValuePick
const hasDataSource =
dataSource != null && typeof dataSource.find === "function" && !!referenceTo

// Grouped and filtered by id: two records with one title stay two options.
const recordToOption = React.useCallback(
(r: any): LookupOption => {
const id = r?.[idField] ?? r?.id ?? r?._id
const label = r?.[displayField] ?? r?.label ?? r?.name ?? String(id)
return { value: id, label: String(label) }
const label = referencedRecordTitle(targetDef, r, displayField) ?? String(id)
return { value: id, label }
},
[displayField, idField],
[targetDef, displayField, idField],
)
const options = React.useMemo(() => optionRecords.map(recordToOption), [optionRecords, recordToOption])
const resolved = React.useMemo(() => {
const labels: Record<string, string> = {}
for (const [id, r] of Object.entries(resolvedRecords)) labels[id] = recordToOption(r).label
return labels
}, [resolvedRecords, recordToOption])

const fetchData = React.useCallback(
async (search?: string) => {
Expand All @@ -2755,30 +2773,29 @@ function LookupValuePicker({ field, value, multiple, onChange }: LookupValuePick
if (search && search.trim()) params.$search = search.trim()
const result = await dataSource.find(referenceTo, params)
const records: any[] = result?.data ?? result ?? []
const mapped = records.map(recordToOption)
setOptions(mapped)
// Cache resolved labels for any matching selected ids
if (mapped.length > 0) {
setResolved((prev) => {
setOptionRecords(records)
// Keep the records of any matching selected ids
if (records.length > 0) {
setResolvedRecords((prev) => {
const next = { ...prev }
for (const opt of mapped) next[String(opt.value)] = opt.label
for (const r of records) next[String(r?.[idField] ?? r?.id ?? r?._id)] = r
return next
})
}
} catch (err) {
setError(err instanceof Error ? err.message : String(err))
setOptions([])
setOptionRecords([])
} finally {
setLoading(false)
}
},
[dataSource, referenceTo, hasDataSource, recordToOption],
[dataSource, referenceTo, hasDataSource, idField],
)

// Resolve labels for already-selected ids that we haven't seen yet
React.useEffect(() => {
if (!hasDataSource || selectedIds.length === 0) return
const missing = selectedIds.filter((id) => !(id in resolved))
const missing = selectedIds.filter((id) => !(id in resolvedRecords))
if (missing.length === 0) return
let cancelled = false
;(async () => {
Expand All @@ -2789,12 +2806,9 @@ function LookupValuePicker({ field, value, multiple, onChange }: LookupValuePick
})
const records: any[] = result?.data ?? result ?? []
if (cancelled) return
setResolved((prev) => {
setResolvedRecords((prev) => {
const next = { ...prev }
for (const r of records) {
const opt = recordToOption(r)
next[String(opt.value)] = opt.label
}
for (const r of records) next[String(r?.[idField] ?? r?.id ?? r?._id)] = r
return next
})
} catch {
Expand All @@ -2804,7 +2818,7 @@ function LookupValuePicker({ field, value, multiple, onChange }: LookupValuePick
return () => {
cancelled = true
}
}, [selectedIds, hasDataSource, dataSource, referenceTo, idField, recordToOption, resolved])
}, [selectedIds, hasDataSource, dataSource, referenceTo, idField, resolvedRecords])

// Fetch initial data when popover opens
React.useEffect(() => {
Expand Down
27 changes: 27 additions & 0 deletions ui/packages/core/src/utils/__tests__/record-title.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
deriveTitleField,
isTitleEligibleField,
formatTitleTemplate,
referencedRecordTitle,
} from '../record-title';

describe('getRecordDisplayName — ADR-0079 repro', () => {
Expand Down Expand Up @@ -519,3 +520,29 @@ describe('formatTitleTemplate — the empty-placeholder sentinel', () => {
expect(isPrintable(out)).toBe(true);
});
});

describe('referencedRecordTitle — a lookup target named by its nameField (objectstack#35053)', () => {
const target = {
nameField: 'deal_number',
fields: { deal_number: { type: 'autonumber' }, code: { type: 'text' } },
};
const deal = { id: 'T1lF9T1kq45KAN06', deal_number: 'DEAL-2026-0001', code: 'C-1' };

it('reads the target nameField when the lookup declares no displayField', () => {
expect(referencedRecordTitle(target, deal)).toBe('DEAL-2026-0001');
});

it('an explicit displayField wins over the nameField', () => {
expect(referencedRecordTitle(target, deal, 'code')).toBe('C-1');
});

it('answers undefined where getRecordDisplayName would fall to its floor', () => {
expect(referencedRecordTitle(target, { id: 'x1' })).toBeUndefined();
expect(getRecordDisplayName(target, { id: 'x1' })).toBe('Record #x1');
expect(referencedRecordTitle(target, 'x1')).toBeUndefined();
});

it('with no target definition, reads the record alone', () => {
expect(referencedRecordTitle(undefined, { id: 'a', name: 'Acme' })).toBe('Acme');
});
});
51 changes: 45 additions & 6 deletions ui/packages/core/src/utils/record-title.ts
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,50 @@ export function getRecordDisplayName(
record: any,
options?: RecordDisplayNameOptions,
): string {
const named = recordTitleAboveFloor(objectDef, record, options);
if (named !== undefined) return named;

// 5. Record-#id floor; only a truly id-less record hits the bare fallback.
const id = record?.id ?? record?._id;
if (id !== null && id !== undefined && String(id).trim() !== '') {
return `Record #${id}`;
}
return options?.fallback ?? 'Untitled';
}

/**
* The title of a record that a LOOKUP points at — a group header keyed by a
* lookup, a filter value option, any surface that names the referenced record
* from the record it read: the lookup field's own `displayField` (the
* caller's declared pointer, {@link RecordDisplayNameOptions.titleField}),
* then the target object's ladder from {@link getRecordDisplayName}, with its
* declared `nameField` above every heuristic. That is the default the spec
* states for a lookup with no `displayField` ("the referenced object's
* name/title").
*
* Stops short of the `Record #<id>` / `Untitled` floor and answers
* `undefined` instead, so each caller keeps its own face for a record nothing
* names (a raw key, an id chip). `targetDef` may be absent while the target's
* schema is unknown; the ladder then reads the record alone.
*/
export function referencedRecordTitle(
targetDef: any,
record: any,
displayField?: string,
): string | undefined {
if (!record || typeof record !== 'object') return undefined;
return recordTitleAboveFloor(targetDef, record, { titleField: displayField });
}

/**
* Every rung of {@link getRecordDisplayName} above its floor: the title, or
* `undefined` when no rung names the record.
*/
function recordTitleAboveFloor(
objectDef: any,
record: any,
options?: RecordDisplayNameOptions,
): string | undefined {
// 0. Explicit title field — the caller's option, if it actually resolves on
// the record. This is a DECLARED key: every view config that offers a
// title pointer (`ui/CalendarConfig`, `ui/GalleryConfig`, `ui/GanttConfig`,
Expand Down Expand Up @@ -632,10 +676,5 @@ export function getRecordDisplayName(
}
}

// 5. Record-#id floor; only a truly id-less record hits the bare fallback.
const id = record?.id ?? record?._id;
if (id !== null && id !== undefined && String(id).trim() !== '') {
return `Record #${id}`;
}
return options?.fallback ?? 'Untitled';
return undefined;
}
Loading
Loading