Skip to content

Commit 99a0e4f

Browse files
fix(ui): a lookup's group headers and filter options read the target's nameField, and the empty group is translated (#35140)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8AJJJRiYjshMUNgyMZSqBsr)_ Fixes #35053 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - **改了什么**:列表按查找字段分组时的分组标题(服务端分组与客户端分组)、筛选器里查找字段的候选值,在查找字段未声明 `displayField` 时改用目标对象声明的 `nameField` 命名,不再显示原始记录 id;空值分组的标题改用网格已有的「空」文案(`grid.empty`),随语言翻译。 - **为什么改**:spec 对 `displayField` 的默认值写明是「被引用对象的 name/title」,单元格与记录页头早已这样做;这三处却只猜 `name/label/title`,目标对象以自动编号等字段为标题时(如 `DEAL-2026-0001`),中文用户看到的是一串 id 和英文的 `(empty)`。 - **风险与回滚**:只改显示文案,分组与筛选仍按 id;新增读取目标对象定义(每个目标对象一次,适配器有元数据缓存)。英文空分组从 `(empty)` 变为 `Empty`,位置不变。回滚即 revert 本 PR。 - **先看**:`ui/packages/plugin-grid/src/useServerGrouping.ts`(标题读取处并行读目标定义)、`ui/packages/components/src/custom/filter-builder.tsx`(`LookupValuePicker` 改为存记录、渲染时算标签)、`ui/packages/core/src/utils/record-title.ts`(新增 `referencedRecordTitle`,从 `getRecordDisplayName` 拆出无兜底的一段)。 - **两分钟验证**:`pnpm --dir ui exec vitest run packages/plugin-grid/src/__tests__/lookupGroupNameField-35053.test.tsx packages/components/src/__tests__/filter-builder-lookup-namefield-35053.test.tsx`,预期 10 个用例全绿(含 zh-CN 空分组显示「空」)。 - **需要你做的**:无,席位落地。 ## What changes - **One resolver.** `@object-ui/core` adds `referencedRecordTitle(targetDef, record, displayField?)`: the lookup's own `displayField`, then the target object's `getRecordDisplayName` ladder (declared `nameField` first, ADR-0079), stopping short of the `Record #ID` / `Untitled` floor and answering `undefined` there, so each caller keeps its own face for an unnamed record. `getRecordDisplayName` is split into the rungs above the floor (`recordTitleAboveFloor`, module-private) plus the floor, so the two cannot drift; its behaviour is unchanged. - **Server-grouped headers** (`useServerGroupHeaders`): the label read now reads the target's definition in parallel with the record read (`readLookupTargetDef`) and names each id through `referencedRecordTitle`. Before: `displayField`, else `name ?? label ?? title`, else the raw id. - **Client grouping** (`useObjectGridGrouping`'s `groupValueFormatter`): a lookup grouping field's expanded record is named through `referencedRecordTitle` with the target definition (`useLookupTargetDefs`, enabled only on the client path) and the field's `displayField`. Before: the `displayField` was ignored and the `name ?? label ?? title ...` guess ran. `buildSegmentLabel`'s object arm, used by the published `useGroupedData` with no formatter, now runs the same resolver with no target definition (record-only ladder) instead of its own key list. - **Filter value picker** (`LookupValuePicker`): `displayField` no longer defaults to `"name"`; the target definition is read through `@object-ui/react`'s `useSettledSchema` (one read per picker mount), and options plus the chosen value's chip are labelled at render through `referencedRecordTitle`, so a definition that lands after the search still names them. Options and selections stay keyed and written by id. - **Empty group heading**: the literal `(empty)` is replaced by the grid's existing empty-value key `grid.empty` (translated in all twelve packs: `Empty`, `空`, ...), read inside `useGroupedDataInOptionOrder` through `useGridTranslation`. No new locale key. The empty group keeps its place in label order by its KEY, not its heading (`compareGroupLabels`): first ascending, last descending, as the untranslated heading always sorted. ## Tests - New `ui/packages/plugin-grid/src/__tests__/lookupGroupNameField-35053.test.tsx`: per producer (server-grouped, client-grouped) a target with `nameField: 'deal_number'` and no name/label/title heads its groups with the deal numbers; CONTROL that an explicit `displayField` still wins; two records sharing one title stay two groups; zh-CN empty group reads `空` and keeps its place. - New `ui/packages/components/src/__tests__/filter-builder-lookup-namefield-35053.test.tsx`: options read the deal numbers and the picked value written is the id; the chosen value's chip reads the deal number; CONTROL that an explicit `displayField` wins. - `record-title.test.ts`: four pins on `referencedRecordTitle` (nameField, displayField wins, undefined where `getRecordDisplayName` floors, record-only ladder without a definition). - Updated pinned headings `'(empty)'` to `'Empty'` in `groupSelectOptionOrder-11809`, `groupDateHeading-13234` and `serverGroupingFieldSwitch-11574` (the ascending order controls there stay green, which is the order-preservation evidence). ## Acceptance notes - PM mechanism assumption measured: none of the three producers had the target object's definition in hand. The grid loads only the grouped object's definition (`objectFields`, which carries `reference` and `displayField`, not the target's `nameField`); the lookup cell's target-schema cache is private to `@object-ui/fields`, which `@object-ui/components` cannot import (cycle). Cheapest correct path taken: `dataSource.getObjectSchema(target)`, one per target per header load / per change of the client grouping's target list / per picker mount. The ObjectStack adapter serves repeat reads from its metadata cache, and the lookup cells on the same screen already read the same targets, so in the Console this is normally zero extra network requests. - The published `useGroupedData` with no formatter now names an expanded record by `referencedRecordTitle`'s record-only ladder: `name`, `full_name`, `fullName`, `display_name`, `displayName`, `title`, `subject`, `label`, then the `*_name` / `*_title` affix scan. The old list put `label` before `title` and had no `subject` or affix leg. - English readers now see `Empty` where they saw `(empty)`; that is the grid's existing empty-value string, chosen over minting a new key per the dispatch. - Observation, not filed: `@object-ui/fields`' private `resolveLookupRecordName` performs the same operation by calling `getRecordDisplayName` and string-matching the floor; it could call `referencedRecordTitle` instead. Outside this claim's file surface. ## Verification <details><summary>Ablation, one leg per producer plus the empty label (scripts/ablation-replace.mjs, restore proven blob == HEAD each time; vitest resolves the ui packages from src)</summary> - server: `referencedRecordTitle(targetDef, rec, ...)` replaced by the old `displayField ?? name ?? label ?? title` read: 2 failed (the nameField pin and the zh-CN pin, which also reads the deal numbers); the `displayField` CONTROL stayed green. - client: `lookupTargetDefs?.get(meta.target)` replaced by `undefined`: 3 failed (nameField, same-title, zh-CN); CONTROL green. - picker: `targetDef` replaced by `undefined`: 2 failed (options, chip); CONTROL green. - empty label: `t('grid.empty')` replaced by `'(empty)'`: 6 failed (every heading list that includes the empty group); the picker file green. </details> <details><summary>Local runs at head 2e944be</summary> - Targeted: 8 files, 162 tests passed. - `@object-ui/core`, `@object-ui/plugin-grid`, `@object-ui/components` whole packages (`pnpm --dir ui exec vitest run packages/core/ packages/plugin-grid/ packages/components/`): Test Files 1017 passed, 1 skipped; Tests 11601 passed, 51 skipped; lock VERDICT command-exit 0. - `type-check` for the same three packages: exit 0. - `pnpm --dir ui exec vitest run scripts/`: 171 files passed, 2 skipped; exit 0. - `dispatch-gates --commands` derived 38 families; all 38 run with exit 0; `--ran` reconciliation: 38 accounted, 0 NOT-MEASURED (derived zero). - `ui` `check:new-line-citations`: 0 new citations. `overlap-check`: clean against origin/main b1eb500, 0 PR heads. - Not run locally, declared to CI: `test:repo`, the lint farm, `Lint UI`, `Test UI` shards, dogfood (no `!`, no narrowing arm). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi)_ <!-- signed: repo:objectstack#1 · os-warren · session_01JQwxbYRqkDAGuse5Wqbohi --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent f54fc93 commit 99a0e4f

13 files changed

Lines changed: 625 additions & 72 deletions
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@object-ui/core': patch
3+
'@object-ui/plugin-grid': patch
4+
'@object-ui/components': patch
5+
---
6+
7+
fix(ui): grouping headers and the filter value picker name a lookup by its target's `nameField`, and the empty group is translated
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: none
11+
12+
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`:
13+
14+
- **Group headers of a list grouped by the lookup**, both server-grouped and client-grouped.
15+
- **Filter builder value picker options** for the lookup, and the chip of the chosen value.
16+
17+
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.
18+
19+
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.
20+
21+
`@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.
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
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+
* objectstack#35053 — the filter value picker names a lookup's candidate
11+
* records by the TARGET object's declared `nameField` when the lookup declares
12+
* no `displayField`, the default the spec's `FieldSchema.displayField` states.
13+
* The target here is titled by an autonumber `deal_number` and has no `name`,
14+
* `label` or `title`, so the old `displayField || "name"` read printed every
15+
* option, and the chosen value's chip, as the raw record id.
16+
*
17+
* The control: an explicit `displayField` on the lookup still wins. The value
18+
* the picker writes stays the record's id.
19+
*/
20+
import { describe, it, expect, vi } from 'vitest';
21+
import React from 'react';
22+
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
23+
import '@testing-library/jest-dom';
24+
import { SchemaRendererContext } from '@object-ui/react';
25+
import { FilterBuilder } from '../custom/filter-builder';
26+
27+
const TARGET = 'crm_deal_confirmation';
28+
29+
const TARGET_DEF = {
30+
name: TARGET,
31+
nameField: 'deal_number',
32+
fields: {
33+
deal_number: { type: 'autonumber', label: 'Deal Number' },
34+
code: { type: 'text', label: 'Code' },
35+
},
36+
};
37+
38+
const DEALS = [
39+
{ id: 'KC3TKTKQPLwGVqsJ', deal_number: 'DEAL-2026-0002', code: 'C-2' },
40+
{ id: 'T1lF9T1kq45KAN06', deal_number: 'DEAL-2026-0001', code: 'C-1' },
41+
];
42+
43+
function fakeDataSource() {
44+
return {
45+
find: vi.fn(async (_object: string, params: Record<string, any>) => {
46+
const ids: string[] | undefined = params.$filter?.id?.$in;
47+
return { data: ids ? DEALS.filter((d) => ids.includes(d.id)) : DEALS };
48+
}),
49+
getObjectSchema: vi.fn(async (name: string) => (name === TARGET ? TARGET_DEF : undefined)),
50+
};
51+
}
52+
53+
function renderRow(lookupExtra: Record<string, unknown>, value: unknown, dataSource: unknown) {
54+
const onChange = vi.fn();
55+
const fields = [
56+
{ value: 'deal_confirmation', label: 'Deal', type: 'lookup', referenceTo: TARGET, ...lookupExtra },
57+
];
58+
const tree = {
59+
id: 'root',
60+
logic: 'and',
61+
conditions: [{ id: 'c1', field: 'deal_confirmation', operator: 'equals', value }],
62+
};
63+
render(
64+
<SchemaRendererContext.Provider value={{ dataSource } as any}>
65+
<FilterBuilder fields={fields as any} value={tree as any} onChange={onChange} />
66+
</SchemaRendererContext.Provider>,
67+
);
68+
return onChange;
69+
}
70+
71+
describe('filter value picker names lookup options by the target nameField (objectstack#35053)', () => {
72+
it('lists the deal numbers, not the record ids, and writes the id it picks', async () => {
73+
const dataSource = fakeDataSource();
74+
const onChange = renderRow({}, '', dataSource);
75+
fireEvent.click(screen.getByTestId('lookup-picker-deal_confirmation'));
76+
const option = await screen.findByText('DEAL-2026-0001');
77+
expect(screen.getByText('DEAL-2026-0002')).toBeInTheDocument();
78+
expect(screen.queryByText(DEALS[1].id)).not.toBeInTheDocument();
79+
expect(dataSource.getObjectSchema).toHaveBeenCalledWith(TARGET);
80+
81+
fireEvent.click(option);
82+
const calls = onChange.mock.calls;
83+
expect(calls[calls.length - 1][0].conditions[0]).toMatchObject({ value: DEALS[1].id });
84+
});
85+
86+
it('the chosen value\'s chip reads the deal number', async () => {
87+
renderRow({}, DEALS[1].id, fakeDataSource());
88+
await waitFor(() =>
89+
expect(screen.getByTestId('lookup-picker-deal_confirmation')).toHaveTextContent('DEAL-2026-0001'),
90+
);
91+
});
92+
93+
it('CONTROL — an explicit `displayField` on the lookup still wins over the nameField', async () => {
94+
renderRow({ displayField: 'code' }, '', fakeDataSource());
95+
fireEvent.click(screen.getByTestId('lookup-picker-deal_confirmation'));
96+
expect(await screen.findByText('C-1')).toBeInTheDocument();
97+
expect(screen.getByText('C-2')).toBeInTheDocument();
98+
expect(screen.queryByText('DEAL-2026-0001')).not.toBeInTheDocument();
99+
});
100+
});

‎ui/packages/components/src/custom/filter-builder.tsx‎

Lines changed: 38 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import {
1717
type ViewFilterRule,
1818
} from "@objectstack/spec/ui"
1919
import { DATE_RANGE_PRESETS, expandEmptyOperator, type DateRangePreset } from "@objectstack/spec/data"
20-
import { SchemaRendererContext } from "@object-ui/react"
20+
import { SchemaRendererContext, useSettledSchema } from "@object-ui/react"
2121
import {
2222
FILTER_DATE_LIKE_TYPES,
2323
FILTER_LOOKUP_LIKE_TYPES,
@@ -36,6 +36,7 @@ import {
3636
ComponentRegistry,
3737
isRealCalendarDate,
3838
isRetiredFieldType,
39+
referencedRecordTitle,
3940
reportRetiredFieldType,
4041
toDateTimeInputValue,
4142
} from "@object-ui/core"
@@ -2712,17 +2713,27 @@ function LookupValuePicker({ field, value, multiple, onChange }: LookupValuePick
27122713
// list that disagrees with the gate about what is live.
27132714
const referenceTo =
27142715
field.referenceTo || (field.type === "user" ? "users" : undefined)
2715-
const displayField = field.displayField || "name"
2716+
// The lookup's own `displayField` when it declares one; otherwise the target
2717+
// object's declared `nameField` names each option (objectstack#35053), read
2718+
// from the target's definition: one schema read per picker, which the
2719+
// ObjectStack adapter serves from its metadata cache after the first.
2720+
const displayField = field.displayField || undefined
27162721
const idField = field.idField || "id"
2722+
const { def: targetDef } = useSettledSchema(
2723+
referenceTo ?? "",
2724+
referenceTo && dataSource && typeof dataSource.find === "function" ? dataSource : undefined,
2725+
)
27172726

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

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

2750+
// Grouped and filtered by id: two records with one title stay two options.
27392751
const recordToOption = React.useCallback(
27402752
(r: any): LookupOption => {
27412753
const id = r?.[idField] ?? r?.id ?? r?._id
2742-
const label = r?.[displayField] ?? r?.label ?? r?.name ?? String(id)
2743-
return { value: id, label: String(label) }
2754+
const label = referencedRecordTitle(targetDef, r, displayField) ?? String(id)
2755+
return { value: id, label }
27442756
},
2745-
[displayField, idField],
2757+
[targetDef, displayField, idField],
27462758
)
2759+
const options = React.useMemo(() => optionRecords.map(recordToOption), [optionRecords, recordToOption])
2760+
const resolved = React.useMemo(() => {
2761+
const labels: Record<string, string> = {}
2762+
for (const [id, r] of Object.entries(resolvedRecords)) labels[id] = recordToOption(r).label
2763+
return labels
2764+
}, [resolvedRecords, recordToOption])
27472765

27482766
const fetchData = React.useCallback(
27492767
async (search?: string) => {
@@ -2755,30 +2773,29 @@ function LookupValuePicker({ field, value, multiple, onChange }: LookupValuePick
27552773
if (search && search.trim()) params.$search = search.trim()
27562774
const result = await dataSource.find(referenceTo, params)
27572775
const records: any[] = result?.data ?? result ?? []
2758-
const mapped = records.map(recordToOption)
2759-
setOptions(mapped)
2760-
// Cache resolved labels for any matching selected ids
2761-
if (mapped.length > 0) {
2762-
setResolved((prev) => {
2776+
setOptionRecords(records)
2777+
// Keep the records of any matching selected ids
2778+
if (records.length > 0) {
2779+
setResolvedRecords((prev) => {
27632780
const next = { ...prev }
2764-
for (const opt of mapped) next[String(opt.value)] = opt.label
2781+
for (const r of records) next[String(r?.[idField] ?? r?.id ?? r?._id)] = r
27652782
return next
27662783
})
27672784
}
27682785
} catch (err) {
27692786
setError(err instanceof Error ? err.message : String(err))
2770-
setOptions([])
2787+
setOptionRecords([])
27712788
} finally {
27722789
setLoading(false)
27732790
}
27742791
},
2775-
[dataSource, referenceTo, hasDataSource, recordToOption],
2792+
[dataSource, referenceTo, hasDataSource, idField],
27762793
)
27772794

27782795
// Resolve labels for already-selected ids that we haven't seen yet
27792796
React.useEffect(() => {
27802797
if (!hasDataSource || selectedIds.length === 0) return
2781-
const missing = selectedIds.filter((id) => !(id in resolved))
2798+
const missing = selectedIds.filter((id) => !(id in resolvedRecords))
27822799
if (missing.length === 0) return
27832800
let cancelled = false
27842801
;(async () => {
@@ -2789,12 +2806,9 @@ function LookupValuePicker({ field, value, multiple, onChange }: LookupValuePick
27892806
})
27902807
const records: any[] = result?.data ?? result ?? []
27912808
if (cancelled) return
2792-
setResolved((prev) => {
2809+
setResolvedRecords((prev) => {
27932810
const next = { ...prev }
2794-
for (const r of records) {
2795-
const opt = recordToOption(r)
2796-
next[String(opt.value)] = opt.label
2797-
}
2811+
for (const r of records) next[String(r?.[idField] ?? r?.id ?? r?._id)] = r
27982812
return next
27992813
})
28002814
} catch {
@@ -2804,7 +2818,7 @@ function LookupValuePicker({ field, value, multiple, onChange }: LookupValuePick
28042818
return () => {
28052819
cancelled = true
28062820
}
2807-
}, [selectedIds, hasDataSource, dataSource, referenceTo, idField, recordToOption, resolved])
2821+
}, [selectedIds, hasDataSource, dataSource, referenceTo, idField, resolvedRecords])
28082822

28092823
// Fetch initial data when popover opens
28102824
React.useEffect(() => {

‎ui/packages/core/src/utils/__tests__/record-title.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
deriveTitleField,
1313
isTitleEligibleField,
1414
formatTitleTemplate,
15+
referencedRecordTitle,
1516
} from '../record-title';
1617

1718
describe('getRecordDisplayName — ADR-0079 repro', () => {
@@ -519,3 +520,29 @@ describe('formatTitleTemplate — the empty-placeholder sentinel', () => {
519520
expect(isPrintable(out)).toBe(true);
520521
});
521522
});
523+
524+
describe('referencedRecordTitle — a lookup target named by its nameField (objectstack#35053)', () => {
525+
const target = {
526+
nameField: 'deal_number',
527+
fields: { deal_number: { type: 'autonumber' }, code: { type: 'text' } },
528+
};
529+
const deal = { id: 'T1lF9T1kq45KAN06', deal_number: 'DEAL-2026-0001', code: 'C-1' };
530+
531+
it('reads the target nameField when the lookup declares no displayField', () => {
532+
expect(referencedRecordTitle(target, deal)).toBe('DEAL-2026-0001');
533+
});
534+
535+
it('an explicit displayField wins over the nameField', () => {
536+
expect(referencedRecordTitle(target, deal, 'code')).toBe('C-1');
537+
});
538+
539+
it('answers undefined where getRecordDisplayName would fall to its floor', () => {
540+
expect(referencedRecordTitle(target, { id: 'x1' })).toBeUndefined();
541+
expect(getRecordDisplayName(target, { id: 'x1' })).toBe('Record #x1');
542+
expect(referencedRecordTitle(target, 'x1')).toBeUndefined();
543+
});
544+
545+
it('with no target definition, reads the record alone', () => {
546+
expect(referencedRecordTitle(undefined, { id: 'a', name: 'Acme' })).toBe('Acme');
547+
});
548+
});

‎ui/packages/core/src/utils/record-title.ts‎

Lines changed: 45 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -560,6 +560,50 @@ export function getRecordDisplayName(
560560
record: any,
561561
options?: RecordDisplayNameOptions,
562562
): string {
563+
const named = recordTitleAboveFloor(objectDef, record, options);
564+
if (named !== undefined) return named;
565+
566+
// 5. Record-#id floor; only a truly id-less record hits the bare fallback.
567+
const id = record?.id ?? record?._id;
568+
if (id !== null && id !== undefined && String(id).trim() !== '') {
569+
return `Record #${id}`;
570+
}
571+
return options?.fallback ?? 'Untitled';
572+
}
573+
574+
/**
575+
* The title of a record that a LOOKUP points at — a group header keyed by a
576+
* lookup, a filter value option, any surface that names the referenced record
577+
* from the record it read: the lookup field's own `displayField` (the
578+
* caller's declared pointer, {@link RecordDisplayNameOptions.titleField}),
579+
* then the target object's ladder from {@link getRecordDisplayName}, with its
580+
* declared `nameField` above every heuristic. That is the default the spec
581+
* states for a lookup with no `displayField` ("the referenced object's
582+
* name/title").
583+
*
584+
* Stops short of the `Record #<id>` / `Untitled` floor and answers
585+
* `undefined` instead, so each caller keeps its own face for a record nothing
586+
* names (a raw key, an id chip). `targetDef` may be absent while the target's
587+
* schema is unknown; the ladder then reads the record alone.
588+
*/
589+
export function referencedRecordTitle(
590+
targetDef: any,
591+
record: any,
592+
displayField?: string,
593+
): string | undefined {
594+
if (!record || typeof record !== 'object') return undefined;
595+
return recordTitleAboveFloor(targetDef, record, { titleField: displayField });
596+
}
597+
598+
/**
599+
* Every rung of {@link getRecordDisplayName} above its floor: the title, or
600+
* `undefined` when no rung names the record.
601+
*/
602+
function recordTitleAboveFloor(
603+
objectDef: any,
604+
record: any,
605+
options?: RecordDisplayNameOptions,
606+
): string | undefined {
563607
// 0. Explicit title field — the caller's option, if it actually resolves on
564608
// the record. This is a DECLARED key: every view config that offers a
565609
// title pointer (`ui/CalendarConfig`, `ui/GalleryConfig`, `ui/GanttConfig`,
@@ -632,10 +676,5 @@ export function getRecordDisplayName(
632676
}
633677
}
634678

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

0 commit comments

Comments
 (0)