From 4f10ee2b44b67ec8c5a55e62db6ff975eb8b4f6c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 02:36:51 +0000 Subject: [PATCH 1/7] wip(ui): related tab keeps only open-in-list and one add entry; atomic picker add Claude-Session: https://claude.ai/code/session_01Utp6CZrgaiMgTJCnswR6jQ Co-authored-by: Claude --- .../fields/src/widgets/RecordPickerDialog.tsx | 25 + ui/packages/plugin-detail/src/RelatedList.tsx | 554 ++++++++++-------- 2 files changed, 327 insertions(+), 252 deletions(-) diff --git a/ui/packages/fields/src/widgets/RecordPickerDialog.tsx b/ui/packages/fields/src/widgets/RecordPickerDialog.tsx index b62beb73a88..e0d7fb95c4b 100644 --- a/ui/packages/fields/src/widgets/RecordPickerDialog.tsx +++ b/ui/packages/fields/src/widgets/RecordPickerDialog.tsx @@ -35,6 +35,7 @@ import { ArrowDown, SlidersHorizontal, X, + Plus, } from 'lucide-react'; import type { DataSource, LookupColumnDef } from '@object-ui/types'; // The repo's single filter sink (`packages/core/src/utils/filter-converter.ts`) @@ -526,6 +527,14 @@ export interface RecordPickerDialogProps { * )} */ renderGrid?: (props: RecordPickerGridSlotProps) => React.ReactNode; + + /** + * A first row above the records that creates one instead of picking one + * (objectstack#35601: a record page's related tab offers its 「新建」 here, + * so 「+ 添加」 is one entry). Choosing it is the host's to handle; the + * dialog only draws the row. Absent, nothing is drawn. + */ + createRow?: { label: string; onSelect: () => void }; } /** @@ -577,6 +586,7 @@ export function RecordPickerDialog({ filterColumns, renderFilterBar, renderGrid, + createRow, }: RecordPickerDialogProps) { // The column the record title stands in for. The `'name'` default only keys // that column; `declaredDisplayField` is what the title resolver ranks. @@ -1346,6 +1356,21 @@ export function RecordPickerDialog({ )} + {createRow && ( + + )} + {/* Grid area — external ObjectGrid via renderGrid slot, or built-in table */} {renderGrid ? ( /* External grid component (e.g. ObjectGrid from plugin-grid) */ diff --git a/ui/packages/plugin-detail/src/RelatedList.tsx b/ui/packages/plugin-detail/src/RelatedList.tsx index 2c8f50ed9b3..1e3fe594d08 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -45,8 +45,6 @@ import { ShieldAlert, RotateCw, Maximize2, - Search, - Download, } from 'lucide-react'; import type { LucideIcon } from 'lucide-react'; import type { DataSource, FieldMetadata } from '@object-ui/types'; @@ -1001,54 +999,179 @@ const BodyTableTotalsLine: React.FC<{ totals: readonly BodyTableTotal[] }> = ({ ); }; -/** A chip of the enlarged face's toolbar (objectstack#27524). */ -type EnlargedChip = 'all' | 'mine' | 'overdue'; +/** The add config of {@link RelatedListProps.add}, as `derivedAddOf` derives one. */ +type RelatedListAdd = NonNullable; -interface EnlargedChipDef { - id: EnlargedChip; - /** The narrowing it adds to the list's own rows; none for 全部. */ - filter?: Record; +interface RelationFieldDef { + name?: unknown; + type?: unknown; + reference?: unknown; + required?: unknown; + multiple?: unknown; + hidden?: unknown; + readonly?: unknown; } -const NO_ENLARGED_CHIPS: readonly EnlargedChipDef[] = []; +function relationFieldEntries(fields: unknown): Array<[string, RelationFieldDef]> { + const out: Array<[string, RelationFieldDef]> = []; + for (const [name, def] of fieldEntriesOf(fields)) { + if (typeof name === 'string' && name !== '' && def && typeof def === 'object') out.push([name, def as RelationFieldDef]); + } + return out; +} /** - * The chips of the enlarged face (objectstack#27524, the board's 全部 / 我的 / - * 逾期), each drawn only where the child object declares what it says: - * - 我的: the records the signed-in user owns — the object carries the - * platform's `owner_id` column; - * - 逾期: the records whose deadline has passed — the object declares a - * deadline (`dueLike: true` on a `date` / `datetime` field) with no - * `settledWhen`. A settled deadline is a per-record predicate no query can - * ask, and a chip that listed settled records as overdue would say what the - * cells do not. + * The related tab's 「+ 添加」 when the page authored no `add` + * (objectstack#35601), decided by the relationship this list hangs on: + * + * - `lookup`: the child is a record of its own, so the picker lists the + * child object and a pick re-parents it (`add` with no `linkField`); + * - `master_detail` with a source catalog: the picker lists the catalog and + * a pick creates a row of this list naming it (`linkField`). The catalog + * is the child's one other REQUIRED single-valued `lookup` (a line's + * product): the field every row must name, so a pick is a whole row; + * - `master_detail` with no catalog (none, or more than one required + * lookup): `undefined`, and 「+ 添加」 creates a new row directly. + * + * `undefined` too for any other field type and for a multi-valued + * relationship, whose membership a pick cannot write. */ -interface EnlargedChipField { - name?: unknown; - type?: unknown; - dueLike?: unknown; - settledWhen?: unknown; +export function derivedAddOf( + childFields: unknown, + referenceField: string | undefined, + childObject: string | undefined, +): RelatedListAdd | undefined { + if (!referenceField || !childObject) return undefined; + const entries = relationFieldEntries(childFields); + const rel = entries.find(([name]) => name === referenceField)?.[1]; + if (!rel || rel.multiple === true) return undefined; + if (rel.type === 'lookup') return { picker: { object: childObject } }; + if (rel.type !== 'master_detail') return undefined; + const catalogs = entries.filter(([name, def]) => + name !== referenceField + && def.type === 'lookup' + && def.required === true + && def.multiple !== true + && def.hidden !== true + && def.readonly !== true + && typeof def.reference === 'string' && def.reference !== ''); + if (catalogs.length !== 1) return undefined; + const [catalogField, catalogDef] = catalogs[0]; + return { picker: { object: catalogDef.reference as string }, linkField: catalogField }; } -function enlargedChipsOf(objectSchema: { fields?: unknown } | null | undefined): readonly EnlargedChipDef[] { - const chips: EnlargedChipDef[] = [{ id: 'all' }]; - const raw = objectSchema?.fields; - const fields: Array<[unknown, EnlargedChipField | undefined]> = Array.isArray(raw) - ? (raw as Array).map((f) => [f?.name, f]) - : raw && typeof raw === 'object' - ? Object.entries(raw as Record) - : []; - if (fields.some(([name]) => name === 'owner_id')) { - chips.push({ id: 'mine', filter: { owner_id: '{current_user_id}' } }); +/** One group of a stateful child list (`statusGroupsOf`). */ +export interface RelatedStatusGroup { + key: string; + label: string; + /** The status a settled (completed) row is in: these groups come last. */ + settled: boolean; + rows: any[]; +} + +interface StatusOptionDef { value?: unknown; label?: unknown } +interface DeadlineDef { name?: string; type?: unknown; dueLike?: unknown; settledWhen?: unknown } + +/** + * The status groups of a stateful child list (objectstack#35601 item 7), or + * `null` when the child object does not declare enough to group by. + * + * Stateful is DECLARED, never guessed from names: the object has a status + * field (`detectStatusField`, the record page's own rule) of type `select` + * with options, AND a deadline (`dueLike: true` on a date field) whose + * `settledWhen` says when a record is done. A status whose option settles + * that predicate is a completed group; the others are open groups. Open + * groups come first, completed last, each in its options' order; a row whose + * status names no option joins an open group of its own. Empty groups are + * not drawn. With no option settling the predicate there is nothing to tell + * open from done, so no grouping. + */ +export function statusGroupsOf( + objectSchema: { fields?: unknown; stageField?: unknown } | null | undefined, + rows: readonly any[], + scope: Record | undefined, +): RelatedStatusGroup[] | null { + if (!objectSchema) return null; + const statusField = detectStatusField(objectSchema as Parameters[0]); + if (!statusField) return null; + const entries = fieldEntriesOf(objectSchema.fields); + const statusDef = entries.find(([name]) => name === statusField)?.[1] as + | { type?: unknown; options?: unknown } + | undefined; + if (statusDef?.type !== 'select' || !Array.isArray(statusDef.options) || statusDef.options.length === 0) return null; + const deadlineEntry = entries.find(([, def]) => { + const d = def as DeadlineDef | undefined; + return d?.dueLike === true && d.settledWhen != null && (d.type === 'date' || d.type === 'datetime'); + }); + if (!deadlineEntry) return null; + const deadline = { ...(deadlineEntry[1] as DeadlineDef), name: deadlineEntry[0] }; + const options = (statusDef.options as StatusOptionDef[]).filter((o) => o && o.value != null); + const settledOf = (value: unknown) => + isDeadlineSettled(deadline as Parameters[0], { [statusField]: value }, { + scope, + fields: objectSchema.fields as never, + }); + const groups = options.map((o) => ({ + key: String(o.value), + label: typeof o.label === 'string' && o.label !== '' ? o.label : String(o.value), + settled: settledOf(o.value), + rows: [] as any[], + })); + if (!groups.some((g) => g.settled)) return null; + const byKey = new Map(groups.map((g) => [g.key, g])); + const unlisted: RelatedStatusGroup = { key: '', label: '—', settled: false, rows: [] }; + for (const row of rows) { + const raw = row?.[statusField]; + const group = raw == null ? undefined : byKey.get(String(raw)); + (group ?? unlisted).rows.push(row); } - const deadline = fields.find( - ([name, f]) => typeof name === 'string' && f?.dueLike === true && f?.settledWhen == null - && (f?.type === 'date' || f?.type === 'datetime'), - ); - if (deadline) chips.push({ id: 'overdue', filter: { [deadline[0] as string]: { $lt: '{today}' } } }); - return chips; + return [ + ...groups.filter((g) => !g.settled), + unlisted, + ...groups.filter((g) => g.settled), + ].filter((g) => g.rows.length > 0); } +/** The groups of `statusGroupsOf`, each collapsible under its header. */ +const RelatedStatusGroups: React.FC<{ + groups: readonly RelatedStatusGroup[]; + renderRows: (rows: any[]) => React.ReactNode; + actions: React.ContextType | null; +}> = ({ groups, renderRows, actions }) => { + const [closed, setClosed] = React.useState>(() => new Set()); + const toggle = (key: string) => + setClosed((prev) => { + const next = new Set(prev); + if (next.has(key)) next.delete(key); + else next.add(key); + return next; + }); + return ( +
+ {groups.map((group) => { + const open = !closed.has(group.key); + const body = renderRows(group.rows); + return ( +
+ + {open && (actions ? {body} : body)} +
+ ); + })} +
+ ); +}; + export const RelatedList: React.FC = ({ title, type, @@ -1069,7 +1192,7 @@ export const RelatedList: React.FC = ({ onRowAction, toolbarActions, onToolbarAction, - add, + add: authoredAdd, redactFields, maxColumns = 6, pageSize, @@ -1220,10 +1343,14 @@ export const RelatedList: React.FC = ({ // objectstack#27524 — drawn as the record page's active tab: the toolbar // face below (`RelatedListEnlargedContext`). const enlargedFace = React.useContext(RelatedListEnlargedContext) && !compact; - const [enlargedChip, setEnlargedChip] = React.useState('all'); - // The 全部 chip's count, taken while it is on and nothing narrows the rows. - const [allCount, setAllCount] = React.useState(null); - const [exportState, setExportState] = React.useState<{ busy: boolean; error: string | null }>({ busy: false, error: null }); + // objectstack#35601 — the related tab's add, decided by the relationship + // when the page authored none (`derivedAddOf`). The rest of this component + // reads `add` alone, so a derived add takes the authored one's path. + const derivedAdd = React.useMemo( + () => (enlargedFace && !authoredAdd && !schema ? derivedAddOf(objectSchema?.fields, referenceField, api) : undefined), + [enlargedFace, authoredAdd, schema, objectSchema, referenceField, api], + ); + const add = authoredAdd ?? derivedAdd; // objectstack#27056 — the card's count, asked up front with the column's // other cards (`RelatedCardStack`); `null` when nothing counted it. const cardCount = React.useContext(RelatedCardCountContext); @@ -1255,7 +1382,7 @@ export const RelatedList: React.FC = ({ // as a generic server filter. While the user is typing in it // (opt-in `filterable` consumers only) we drop back to the legacy // fetch-everything mode so the filter keeps seeing the whole collection. - const filterActive = (filterable || enlargedFace) && filterText !== ''; + const filterActive = filterable && filterText !== ''; // Windowed (server-paged) mode — issue #2711: on the auto-fetch path with // pagination enabled, ask the server for ONE page ($top/$skip) plus the // running total instead of dumping every child row into the browser. @@ -1315,21 +1442,6 @@ export const RelatedList: React.FC = ({ ); const filterRefusal = listFilterResult.ok ? undefined : listFilterResult.refusal; const listFilterNode = listFilterResult.ok ? listFilterResult.node : undefined; - // The enlarged face's chips (objectstack#27524): 我的 and 逾期 narrow the - // list's own rows, each only where the child object declares what it says - // (`enlargedChipsOf`). Resolved and lowered the way the list's filter is. - const chips = enlargedFace ? enlargedChipsOf(objectSchema) : NO_ENLARGED_CHIPS; - const chipFilter = chips.find((chip) => chip.id === enlargedChip)?.filter; - const scopeChipFilter = useResolvedFilter(chipFilter, filterScope); - const chipKey = JSON.stringify(scopeChipFilter ?? null); - const chipFilterNode = React.useMemo( - () => { - const lowered = toFilterNodeSafely(scopeChipFilter); - return lowered.ok ? lowered.node : undefined; - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [chipKey], - ); /** * The `$expand` roots for the auto-fetch below (objectui#10112). @@ -1868,9 +1980,9 @@ export const RelatedList: React.FC = ({ // freshly lowered AST that means the same thing (the difference is // invisible on screen and visible to every caller pinning the wire). const queryFilter = - listFilterNode === undefined && chipFilterNode === undefined + listFilterNode === undefined ? parentScope - : mergeFilterNodes(parentScope, listFilterNode, chipFilterNode); + : mergeFilterNodes(parentScope, listFilterNode); if (dataSource && typeof dataSource.find === 'function') { const params: Record = { $filter: queryFilter }; // Resolve reference columns server-side, the way every other list in @@ -2034,7 +2146,7 @@ export const RelatedList: React.FC = ({ // card's in-view / non-zero gate, a boolean. `compact` decides whether the // record page's payload may serve the read (objectstack#27627), a boolean. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [api, dataProvided, dataSource, referenceField, referenceFieldIsMultiValue, parentId, refreshNonce, windowed, effectivePageSize, fetchPage, fetchSortField, fetchSortDirection, defaultSortKey, filterKey, chipKey, expandKey, selectKey, wireExpandKey, wireSelectKey, rowsWanted, objectSchemaReady, compact]); + }, [api, dataProvided, dataSource, referenceField, referenceFieldIsMultiValue, parentId, refreshNonce, windowed, effectivePageSize, fetchPage, fetchSortField, fetchSortDirection, defaultSortKey, filterKey, expandKey, selectKey, wireExpandKey, wireSelectKey, rowsWanted, objectSchemaReady, compact]); // Windowed mode: a page beyond the (shrunken) collection — e.g. the last // row of the last page was just deleted — comes back empty. Step back one @@ -2232,32 +2344,63 @@ export const RelatedList: React.FC = ({ }).allowed; // Add existing records via picker → create link rows (junction) or re-parent - // (1:m). Server-side insert rules (e.g. the AI-seat cap) surface inline. + // (1:m), all of them in ONE transactional batch (objectstack#35601, ADR-0119 + // D4): the cross-object `POST /batch` commits every row or none, so a pick + // of three that fails on one adds nothing. Never a loop of single writes, + // which left the rows before the failure in place. A data source without + // the batch offers no add (`addBatchable`). Server-side insert rules (e.g. + // the AI-seat cap) surface inline. + const addBatchable = typeof (dataSource as DataSource | undefined)?.batchTransaction === 'function'; const handleAddRecords = React.useCallback(async (records: any[]) => { if (!add || !dataSource || !api || referenceField == null || parentId === undefined || parentId === null) return; + const batch = (dataSource as DataSource).batchTransaction; + if (typeof batch !== 'function') return; const vf = add.picker.valueField || 'id'; + const operations: Parameters>[0] = []; + for (const rec of records || []) { + const pickedId = rec?.[vf] ?? rec?.id; + if (pickedId == null) continue; + operations.push(add.linkField + ? { object: api, action: 'create', data: { [referenceField]: parentId, [add.linkField]: pickedId } } + : { object: add.picker.object, action: 'update', id: String(pickedId), data: { [referenceField]: parentId } }); + } + setPickerOpen(false); + if (operations.length === 0) return; setAddBusy(true); setAddError(null); try { - for (const rec of records || []) { - const pickedId = rec?.[vf] ?? rec?.id; - if (pickedId == null) continue; - if (add.linkField) { - await (dataSource as any).create?.(api, { [referenceField]: parentId, [add.linkField]: pickedId }); - } else { - await (dataSource as any).update?.(add.picker.object, String(pickedId), { [referenceField]: parentId }); - } - } + await batch.call(dataSource, operations); setRefreshNonce((n) => n + 1); } catch (err: any) { const raw = err?.body?.error ?? err?.error ?? err?.message ?? String(err); - setAddError(typeof raw === 'string' ? raw : 'Failed to add'); + const reason = typeof raw === 'string' ? raw : typeof raw?.message === 'string' ? raw.message : 'Failed to add'; + setAddError(reason); } finally { setAddBusy(false); - setPickerOpen(false); } }, [add, dataSource, api, referenceField, parentId]); + /** + * The related tab's one 「+ 添加」 (objectstack#35601): with a picker it + * opens it — the picker's first row is 「新建」 when New is offered too — + * and with none it creates a new row directly (New). `null` when neither is + * offered. + */ + const pickerOffered = !!add && !!add.picker?.object && !!dataSource && addGranted && addBatchable; + const addEntry: { label: string; disabled: boolean; onClick: () => void } | null = pickerOffered + ? { + label: add!.label || t('detail.add', { defaultValue: 'Add' }), + disabled: addBusy, + onClick: () => { setAddError(null); setPickerOpen(true); }, + } + : onNew + ? { + label: t('detail.add', { defaultValue: 'Add' }), + disabled: !!newDisabled, + onClick: () => onNew(), + } + : null; + // Generate effective columns from explicit prop or object schema fields. // Behavior: // - Hide the parent FK column (already implicit context). @@ -2997,7 +3140,7 @@ export const RelatedList: React.FC = ({ // Reset to first page when filter/sort changes React.useEffect(() => { setCurrentPage(0); - }, [filterText, sortField, sortDirection, enlargedChip]); + }, [filterText, sortField, sortDirection]); const handleSort = React.useCallback((field: string) => { // A masked column is never sorted by (objectui#10728). The button row @@ -3282,6 +3425,13 @@ export const RelatedList: React.FC = ({ }; }, [enlargedGrid, windowed, total, currentPage, effectivePageSize, relatedData.length, hasMore, sortedData.length, paginatedData.length, activeSort, handleTableSort, objectSchema, onRowEdit, onRowDelete, handleDeleteRow]); + // objectstack#35601 — a stateful child (tasks) is grouped by its status on + // the related tab: open groups first, completed last (`statusGroupsOf`). + const statusGroups = React.useMemo( + () => (enlargedGrid ? statusGroupsOf(objectSchema, paginatedData, predicateScope) : null), + [enlargedGrid, objectSchema, paginatedData, predicateScope], + ); + /** * objectstack#28865 — where a row action the enlarged grid dispatches goes. * @@ -3350,9 +3500,6 @@ export const RelatedList: React.FC = ({ React.useEffect(() => { if (settledTotal !== null) reportTotal?.(settledTotal); }, [reportTotal, settledTotal]); - React.useEffect(() => { - if (enlargedFace && enlargedChip === 'all' && !filterActive && !loading && !loadFailure) setAllCount(recordCount); - }, [enlargedFace, enlargedChip, filterActive, loading, loadFailure, recordCount]); // objectstack#29945 — `bodyTableOverflows`, read where the table scrolls: // its scroll box is wider inside than out. Re-read when the box or the // table resizes (rows arrive, columns size themselves), and whenever the @@ -3483,7 +3630,7 @@ export const RelatedList: React.FC = ({ render-path bare read of `add.picker` rather than optional-chaining it: off-spec `add` still does nothing at all, so no second dialect appears (AGENTS.md #0.1). #3838. */} - {add && pickerObject && dataSource && addGranted && ( + {add && pickerObject && dataSource && addGranted && addBatchable && ( setPickerOpen(o)} @@ -3503,6 +3650,11 @@ export const RelatedList: React.FC = ({ baseFilter={add.picker.filter} onSelect={() => {}} onSelectRecords={(records: any[]) => { void handleAddRecords(records); }} + // objectstack#35601 — on the related tab the picker's first row is + // 「新建」: the add entry and New are one entry there. + {...(enlargedFace && onNew && !newDisabled + ? { createRow: { label: t('detail.new'), onSelect: () => { setPickerOpen(false); onNew(); } } } + : {})} /> )} @@ -3624,7 +3776,7 @@ export const RelatedList: React.FC = ({ )} - {add && pickerObject && dataSource && addGranted && ( + {add && pickerObject && dataSource && addGranted && addBatchable && ( - ); - })} - + {onToolbarAction && permittedToolbarActions.map((a) => ( + + ))} + {onViewAll && ( + + )} + {addEntry && ( + )} -
- {onToolbarAction && permittedToolbarActions.map((a) => ( - - ))} - {add && pickerObject && dataSource && addGranted && ( - - )} - {onNew && ( - - )} - {exportable && ( - - )} -
- {exportState.error && ( -
- {exportState.error} -
- )} {loadFailure ? ( ) : loading && relatedData.length === 0 ? (
{t('detail.loading')}
- ) : isEmpty || shownCount === 0 ? ( + ) : isEmpty ? (
{t('detail.noRelatedRecords')}
) : ( <> - {(!countOnChip || showPagination) && ( -
- {[ - countOnChip ? null : t('detail.relatedRows', { count: shownCount, defaultValue: '{{count}} rows' }), - showPagination ? t('detail.pageOf', { current: currentPage + 1, total: totalPages }) : null, - ].filter(Boolean).join(' · ')} + {statusGroups ? ( + ( + + )} + actions={enlargedGridActions} + /> + ) : ( +
+ {enlargedGridActions ? ( + + + + ) : ( + + )}
)} -
- {enlargedGridActions ? ( - - - - ) : ( - - )} -
{showPagination && (
+ + {t('detail.pageOf', { current: currentPage + 1, total: totalPages })} + ) : null; + // objectstack#35601 — 「Object / Record / this list」: the way back to the + // record whose related list opened this one. + const sourceCrumbs = source && sourceField && appName ? ( + + ) : null; + return (
+ {sourceCrumbs}
0 && ( + {(urlFilters.length > 0 || (source && sourceField)) && (
- {textKey && text !== undefined ? `${t(textKey)} ${text}` : textKey ? t(textKey) : text} + {field === sourceField && sourceConditionOn + ? source?.t || text + : textKey && text !== undefined ? `${t(textKey)} ${text}` : textKey ? t(textKey) : text} + )}
)} diff --git a/ui/packages/app-shell/src/views/RelatedRecordActionsBridge.tsx b/ui/packages/app-shell/src/views/RelatedRecordActionsBridge.tsx index 1c56ce90fae..92579741913 100644 --- a/ui/packages/app-shell/src/views/RelatedRecordActionsBridge.tsx +++ b/ui/packages/app-shell/src/views/RelatedRecordActionsBridge.tsx @@ -642,8 +642,20 @@ export function RelatedRecordActionsBridge({ ) : null; if (viewAllFilter) { - const viewAllPath = recordListPath(appName, objectName, viewAllFilter); - handlers.onViewAll = () => navigate(viewAllPath); + const listPath = recordListPath(appName, objectName, viewAllFilter); + // objectstack#35601 — the list names the record it was opened from: + // the record trail (`?from=`) gains this parent, which the list page + // reads for its breadcrumb, its source chip, 「Reset」 and New. + // Read off the live URL at the click, as `recordPath` reads it. + const viewAllPath = () => parentObjectName && parentRecordId + ? `${listPath}${listPath.includes('?') ? '&' : '?'}${new URLSearchParams({ + [RECORD_TRAIL_PARAM]: appendRecordTrail( + new URLSearchParams(window.location.search).get(RECORD_TRAIL_PARAM), + { o: parentObjectName, i: parentRecordId, ...(parentTitle ? { t: parentTitle } : {}) }, + ), + }).toString()}` + : listPath; + handlers.onViewAll = () => navigate(viewAllPath()); } if (aff.create) { @@ -713,7 +725,7 @@ export function RelatedRecordActionsBridge({ // the #4646 create predicates: a parent record that changes (a save, a // status transition) must re-resolve "+ New" for every related list under // it, or the toolbar keeps answering for the record's previous state. - [objects, base, appName, navigate, dataSource, localizeActionTexts, runRowAction, openChildForm, recordHref, openRecord, perms, parentRecord, parentObjectFields, predicateScope, hasParentRecord, parentFromList], + [objects, base, appName, navigate, dataSource, localizeActionTexts, runRowAction, openChildForm, recordHref, openRecord, perms, parentRecord, parentObjectFields, predicateScope, hasParentRecord, parentFromList, parentObjectName, parentRecordId, parentTitle], ); return ( diff --git a/ui/packages/plugin-detail/src/RelatedList.tsx b/ui/packages/plugin-detail/src/RelatedList.tsx index 1e3fe594d08..efaf47a4de8 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -85,7 +85,7 @@ import { type ActionResult, type FilterNode, } from '@object-ui/core'; -import { useSafeFieldLabel, useRecordContext } from '@object-ui/react'; +import { useSafeFieldLabel, useRecordContext, useRecordPagePreferences, type RelatedListPreference } from '@object-ui/react'; import { usePermissions } from '@object-ui/permissions'; import { useDisplayLocale, useLocalization, resolveFieldCurrency, recordCurrencyField, recordCurrencyPath, withFollowedParent } from '@object-ui/i18n'; import { useDetailTranslation } from './useDetailTranslation'; @@ -795,6 +795,11 @@ interface BodyTableTotalPlan { groupBy?: string; /** The one currency every row is in, for a currency column grouped by nothing. */ currency?: string; + /** + * A currency column whose currency does not resolve (objectstack#35710): its + * total is drawn the way its cells are, as an amount with no symbol. + */ + amount?: true; /** The parent's stored roll-up, when it is this list's total (`RolledUpSum.sameRows`). */ stored?: number; } @@ -810,7 +815,8 @@ interface BodyTableTotalPlan { * * 1. a `currency` column, totalled in its one currency: a `fixed` code, the * tenant default for `dynamic`, the parent's code for a `record` amount - * that follows its parent. A `record` amount whose rows carry their own + * that follows its parent; with none resolving, as an amount with no + * symbol, as its cells draw (objectstack#35710). A `record` amount whose rows carry their own * code is grouped by that code on the server, and totalled only when one * currency comes back — a sum across currencies is not a total; * 2. a `number` / `integer` / `decimal` column only when the record's object @@ -876,9 +882,12 @@ function useBodyTableTotals(opts: { } else { // A `record` amount following its parent reads the parent's code // off the record this list hangs under (ADR-0144 D2). + // With none resolving (no code of its own, no tenant default), the + // total is still the server's figure, drawn without a symbol, as + // the column's cells are (objectstack#35710). const currency = resolveFieldCurrency(def, tenantCurrency, withFollowedParent({}, def, parentRecord) as any); - if (!currency) continue; - plan.currency = currency; + if (currency) plan.currency = currency; + else plan.amount = true; } } if (!plan.groupBy && rollUp?.sameRows && listFilterNode === undefined) { @@ -965,6 +974,8 @@ function useBodyTableTotals(opts: { let text: string; if (sum.currency) { text = formatCurrency(sum.value, sum.currency, displayLocale); + } else if (plan.amount) { + text = formatCurrency(sum.value, undefined, displayLocale); } else { try { text = new Intl.NumberFormat(displayLocale, { maximumFractionDigits: 2 }).format(sum.value); @@ -1365,6 +1376,37 @@ export const RelatedList: React.FC = ({ const bodyTableIds = React.useContext(RecordBodyTablesContext); const ownRelationshipId = objectName && referenceField ? relatedCardId(objectName, referenceField) : null; const bodyTable = !compact && !!ownRelationshipId && bodyTableIds.has(ownRelationshipId); + // objectstack#35601 — the related tab remembers the reader's header sort and + // column widths, per list, in their record-page preferences (the + // `sys_user_preference` row of the parent object's record page). No store, + // no memory: the list's own default, as before. + const pagePreferences = useRecordPagePreferences(); + const preferenceContext = useRecordContext(); + const preferenceObject = (typeof (preferenceContext?.objectSchema as { name?: unknown } | undefined)?.name === 'string' + ? (preferenceContext!.objectSchema as { name: string }).name + : preferenceContext?.objectName) || undefined; + const preferenceKey = enlargedFace && pagePreferences && preferenceObject && ownRelationshipId ? ownRelationshipId : null; + const storedListPreference = preferenceKey ? pagePreferences!.get(preferenceObject!).relatedLists?.[preferenceKey] : undefined; + const writeListPreference = React.useCallback( + (patch: RelatedListPreference) => { + if (!preferenceKey || !pagePreferences || !preferenceObject) return; + const lists = pagePreferences.get(preferenceObject).relatedLists ?? {}; + pagePreferences.update(preferenceObject, { + relatedLists: { ...lists, [preferenceKey]: { ...lists[preferenceKey], ...patch } }, + }); + }, + [preferenceKey, pagePreferences, preferenceObject], + ); + // The remembered sort applies once, when it is first read; a header click + // after that is the reader's and is written back. + const storedSortApplied = React.useRef(false); + const storedSort = storedListPreference?.sort; + React.useEffect(() => { + if (storedSortApplied.current || !storedSort) return; + storedSortApplied.current = true; + setSortField(storedSort.field); + setSortDirection(storedSort.order); + }, [storedSort]); // objectstack#35597 — a body table shows its first `pageSize` rows (ten by // default, the page may say otherwise) and 「显示全部 N 条」 expands it in // place: every row, one read, no pages. N is the server's count when the @@ -3190,8 +3232,10 @@ export const RelatedList: React.FC = ({ setCurrentPage(0); setSortField(first.field); setSortDirection(first.order); + storedSortApplied.current = true; + writeListPreference({ sort: { field: first.field, order: first.order } }); }, - [unmaskedColumnKeysKey], + [unmaskedColumnKeysKey, writeListPreference], ); // A `grid`/`table` list renders a real table, whose column headers carry the @@ -3280,8 +3324,11 @@ export const RelatedList: React.FC = ({ if (enlargedFace && (type === 'grid' || type === 'table')) { return { type: 'object-grid', + // Its own column-layout key, apart from the object's list page grid. + ...(ownRelationshipId ? { id: `related-${ownRelationshipId}` } : {}), objectName: api, data: { provider: 'value', items: paginatedData }, + ...(storedListPreference?.columnState ? { columnState: storedListPreference.columnState } : {}), columns: effectiveColumns .map((c: any) => c.accessorKey || columnIdentity(c)) .filter(Boolean), @@ -3381,7 +3428,7 @@ export const RelatedList: React.FC = ({ default: return { type: 'div', children: 'No view configured' }; } - }, [type, paginatedData, tableColumns, effectiveColumns, schema, effectivePageSize, hasRowActions, hasCustomRowActions, rowActions, onRowAction, onRowEdit, onRowDelete, handleDeleteRow, handleRowClick, isMobile, compact, enlargedFace, api, objectSchema, activeSort, handleTableSort, bodyTable, bodyTableOverflows, bodySummaryRow]); + }, [type, paginatedData, tableColumns, effectiveColumns, schema, effectivePageSize, hasRowActions, hasCustomRowActions, rowActions, onRowAction, onRowEdit, onRowDelete, handleDeleteRow, handleRowClick, isMobile, compact, enlargedFace, api, objectSchema, activeSort, handleTableSort, bodyTable, bodyTableOverflows, bodySummaryRow, ownRelationshipId, storedListPreference?.columnState]); const enlargedGrid = enlargedFace && !schema && (type === 'grid' || type === 'table'); @@ -3422,8 +3469,9 @@ export const RelatedList: React.FC = ({ ...(objectSchema?.fields ? { objectFields: objectSchema.fields } : {}), ...(onRowEdit ? { onEdit: onRowEdit } : {}), ...(onRowDelete ? { onDelete: handleDeleteRow } : {}), + ...(preferenceKey ? { onColumnStateChange: (columnState: RelatedListPreference['columnState']) => writeListPreference({ columnState }) } : {}), }; - }, [enlargedGrid, windowed, total, currentPage, effectivePageSize, relatedData.length, hasMore, sortedData.length, paginatedData.length, activeSort, handleTableSort, objectSchema, onRowEdit, onRowDelete, handleDeleteRow]); + }, [preferenceKey, writeListPreference, enlargedGrid, windowed, total, currentPage, effectivePageSize, relatedData.length, hasMore, sortedData.length, paginatedData.length, activeSort, handleTableSort, objectSchema, onRowEdit, onRowDelete, handleDeleteRow]); // objectstack#35601 — a stateful child (tasks) is grouped by its status on // the related tab: open groups first, completed last (`statusGroupsOf`). diff --git a/ui/packages/react/src/context/RecordPagePreferencesContext.tsx b/ui/packages/react/src/context/RecordPagePreferencesContext.tsx index 621b79fbd54..734c3d2828a 100644 --- a/ui/packages/react/src/context/RecordPagePreferencesContext.tsx +++ b/ui/packages/react/src/context/RecordPagePreferencesContext.tsx @@ -11,7 +11,7 @@ * per object, offered to the record page's renderers by their host * (objectstack#25883). * - * The one choice it carries today is "show empty fields": a reader who opens a + * Its first choice is "show empty fields": a reader who opens a * section's "Show N empty fields" row wants to see the whole record, and wants * it on every section of the page, on the next record of the same object and * after a reload. The host keeps that choice where it keeps the user's list @@ -48,6 +48,18 @@ export interface RecordPagePreference { * means no choice was made: the page folds them, as it always has. */ showEmptyFields?: boolean; + /** + * The reader's sort and column layout of each related list on the record + * page's related tab (objectstack#35601), keyed by the list's `child.field` + * id. Absent: the list's own default sort and column widths. + */ + relatedLists?: Record; +} + +/** One related list's remembered sort and column layout. */ +export interface RelatedListPreference { + sort?: { field: string; order: 'asc' | 'desc' }; + columnState?: { order?: string[]; widths?: Record }; } /** The host's store of record-page choices, one entry per object. */ diff --git a/ui/packages/react/src/context/index.ts b/ui/packages/react/src/context/index.ts index 232025518d2..946bbcd0b77 100644 --- a/ui/packages/react/src/context/index.ts +++ b/ui/packages/react/src/context/index.ts @@ -38,6 +38,6 @@ export * from './DrillNavigationContext.js'; export * from './HostNavigationContext.js'; export { useHostMapStyle, HostMapStyleProvider } from './HostMapStyleContext.js'; export { useRecordPagePreferences, RecordPagePreferencesProvider } from './RecordPagePreferencesContext.js'; -export type { RecordPagePreference, RecordPagePreferencesStore } from './RecordPagePreferencesContext.js'; +export type { RecordPagePreference, RecordPagePreferencesStore, RelatedListPreference } from './RecordPagePreferencesContext.js'; export * from './RelatedRecordActionsContext.js'; export { PrintPageProvider, usePrintPage } from './PrintPageContext.js'; From 756d92bfdccd1ac613c8d0b040199a9fb6966803 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 03:09:58 +0000 Subject: [PATCH 3/7] test(ui): pin the related tab's two entries, one-batch add, status groups, remembered sort and widths, sourced list page and currency-less totals Migrates the retired chip, filter and export pins; adds the batch mock the picker gate now needs to the add tests. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZrgaiMgTJCnswR6jQ --- .changeset/35601-related-tab-open-and-add.md | 23 + .../RecordPreferencesProvider-25883.test.tsx | 22 + .../ObjectDataPage.sourceList-35601.test.tsx | 187 +++++++ ...RecordActionsBridge.viewAll-12741.test.tsx | 12 + ...tedListRenderer.showViewAll-12741.test.tsx | 21 +- .../RelatedList.addGateDataSource.test.tsx | 2 + .../RelatedList.addGrant-12082.test.tsx | 2 + .../RelatedList.addPickerFilter.test.tsx | 2 + .../RelatedList.addPickerGuard.test.tsx | 2 + .../RelatedList.addPickerLabelField.test.tsx | 2 + .../RelatedList.bodyTable-27055.test.tsx | 18 +- ...elatedList.enlargedListGrid-28865.test.tsx | 71 ++- ...RelatedList.enlargedToolbar-27524.test.tsx | 469 +++++++++++------- ...locks.nestedLabelsI18nLabel-10993.test.tsx | 2 + 14 files changed, 616 insertions(+), 219 deletions(-) create mode 100644 .changeset/35601-related-tab-open-and-add.md create mode 100644 ui/packages/app-shell/src/views/ObjectDataPage.sourceList-35601.test.tsx diff --git a/.changeset/35601-related-tab-open-and-add.md b/.changeset/35601-related-tab-open-and-add.md new file mode 100644 index 00000000000..35782f3af34 --- /dev/null +++ b/.changeset/35601-related-tab-open-and-add.md @@ -0,0 +1,23 @@ +--- +'@object-ui/plugin-detail': patch +'@object-ui/app-shell': patch +'@object-ui/fields': patch +'@object-ui/react': patch +--- + +fix(record-page): the related tab offers only 「↗」 and 「+ 添加」, and a pick of several is added all or none + +Clause-②: no +Metadata-protocol: none + +The record page's related tab drew a filter box, condition chips, an options menu, an export and its own New, and repeated the row count under the table. It now carries two entries at its right end. 「↗」 opens the child object's list under this record, on an empty list too. 「+ 添加」 is the one add entry, chosen by the relationship when the page authored no `add`: a `lookup` child opens a picker of that object whose first row is New; a `master_detail` child whose rows name a catalog record (one other required lookup) opens a picker of that catalog; one with no catalog opens the new-record form directly. The count shows once, in the tab title. + +A pick of several records is one request to the transactional batch route: every row is added or none is, and the list says why when none was. Before, each pick was its own write, and a failure part way left the earlier rows added. A data source without the batch route offers no picker. + +A child with a status and a deadline that the status settles is grouped by status on the tab: open groups first in the order the status lists them, completed groups last, each collapsible. + +The reader's header sort and column widths on the tab are remembered per list in the record page's existing per-user preferences. + +The list page 「↗」 opens names the record it came from: its condition tag reads the record's name, a breadcrumb leads back to it, 「Reset」 puts that condition back after the reader changed the filters, and New opens the record form linked to it. + +A body table's total under a currency column whose currency does not resolve is drawn as its cells are, an amount with no symbol, instead of being left out (objectstack#35710). Rows that name their own currency are still totalled per currency. diff --git a/ui/packages/app-shell/src/context/__tests__/RecordPreferencesProvider-25883.test.tsx b/ui/packages/app-shell/src/context/__tests__/RecordPreferencesProvider-25883.test.tsx index f339e26cdad..aa5a37d9d1b 100644 --- a/ui/packages/app-shell/src/context/__tests__/RecordPreferencesProvider-25883.test.tsx +++ b/ui/packages/app-shell/src/context/__tests__/RecordPreferencesProvider-25883.test.tsx @@ -194,3 +194,25 @@ describe('RecordPreferencesProvider — the record page remembers "show empty fi expect(result.current?.get('account')).toEqual({}); }); }); + +/** + * objectstack#35601 — the related tab's header sort and column widths ride in + * the same row, per list (`CHILD.FK`); what the row holds is kept only well + * formed. + */ +describe('RecordPreferencesProvider — the related tab\'s remembered sort and widths (objectstack#35601)', () => { + it('keeps a well-formed sort and column state per list and drops the rest', () => { + expect(sanitizeRecordPreference({ + relatedLists: { + 'task.project': { sort: { field: 'due_date', order: 'desc' }, columnState: { order: ['subject', 7], widths: { subject: 240, due_date: -1 } } }, + 'note.project': { sort: { field: 'title', order: 'sideways' } }, + 'bad.entry': 'x', + }, + })).toEqual({ + relatedLists: { + 'task.project': { sort: { field: 'due_date', order: 'desc' }, columnState: { order: ['subject'], widths: { subject: 240 } } }, + }, + }); + expect(sanitizeRecordPreference({ relatedLists: ['x'] })).toEqual({}); + }); +}); diff --git a/ui/packages/app-shell/src/views/ObjectDataPage.sourceList-35601.test.tsx b/ui/packages/app-shell/src/views/ObjectDataPage.sourceList-35601.test.tsx new file mode 100644 index 00000000000..11ec068ff47 --- /dev/null +++ b/ui/packages/app-shell/src/views/ObjectDataPage.sourceList-35601.test.tsx @@ -0,0 +1,187 @@ +/** + * 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#35601 — a list opened from a record's related tab (「↗」) + * knows the record it came from. The record rides on the record trail + * (`?from=`, its last entry); the condition itself stays the ordinary + * `filter[FIELD]=ID` the related list always sent. The page then: + * + * - names the record in the condition's tag (「所属 X:record ×」), not its id; + * - draws a breadcrumb back to it (object / record / this list); + * - offers 「重置」, which puts the sourced condition back after the reader + * changed or removed it; + * - opens New as that record's child (the record form overlay, linked). + * + * Control: the same filter without a trail is an ordinary filtered list. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, cleanup, fireEvent, screen } from '@testing-library/react'; +import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom'; + +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + usePermissions: () => ({ + check: () => ({ allowed: true }), + checkField: () => true, + getFieldPermissions: () => [], + getRowFilter: () => undefined, + getObjectApiOperations: () => undefined, + roles: [], + isLoaded: false, + hasCapabilities: () => true, + can: () => true, + cannot: () => false, + }), + useFieldPermissions: () => ({ canRead: () => true, canWrite: () => true, permissions: [] }), + }; +}); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }), + useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }), + createAuthenticatedFetch: () => vi.fn(), +})); + +// Heavy children, all orthogonal to the chip row under test and each dragging in +// a plugin bundle — the same posture as the sibling create-affordance test on +// this page. +vi.mock('@object-ui/plugin-list', async (importOriginal) => ({ + ...(await importOriginal()), + ListView: () => null, +})); +vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null })); +vi.mock('./CreateViewDialog', () => ({ CreateViewDialog: () => null })); +vi.mock('./metadata-admin/useMetadata', () => ({ useMetadataClient: () => ({}) })); + +import { ObjectDataPage, sourceRelationshipField } from './ObjectDataPage'; +import { ExpressionProvider } from '../providers/ExpressionProvider'; +import { RECORD_TRAIL_PARAM } from '../urlParams'; + +const h = React.createElement; + +const OBJECTS = [ + { + name: 'task', + label: 'Task', + pluralLabel: 'Tasks', + managedBy: 'platform', + fields: { + id: { type: 'text', label: 'Id' }, + subject: { type: 'text', label: 'Subject' }, + project: { type: 'lookup', reference: 'project', label: 'Project' }, + status: { type: 'text', label: 'Status' }, + }, + }, + { name: 'project', label: 'Project', pluralLabel: 'Projects', managedBy: 'platform', fields: { name: { type: 'text', label: 'Name' } } }, +]; + +const TRAIL = encodeURIComponent(JSON.stringify([{ o: 'project', i: 'P-1', t: 'Launch' }])); + +function makeDataSource() { + return { + find: vi.fn(async () => ({ data: [], total: 0 })), + findOne: vi.fn(async () => null), + create: vi.fn(async () => ({})), + update: vi.fn(async () => ({})), + delete: vi.fn(async () => ({})), + } as any; +} + +function Probe() { + const location = useLocation(); + return h('output', { 'data-testid': 'probe' }, `${location.pathname}${location.search}`); +} + +function renderAt(search: string) { + return render( + h(ExpressionProvider, { + user: { id: 'u1', name: 'Ada', profile: 'admin' }, + children: h( + MemoryRouter, + { initialEntries: [`/apps/demo/task/data?${search}`] }, + h(Routes, null, h(Route, { + path: '/apps/:appName/:objectName/data', + element: h(React.Fragment, null, h(ObjectDataPage, { dataSource: makeDataSource(), objects: OBJECTS }), h(Probe)), + })), + ), + }), + ); +} + +const params = () => new URLSearchParams((screen.getByTestId('probe').textContent ?? '').split('?')[1] ?? ''); +const chipText = (field: string) => + document.querySelector(`[data-testid="object-data-remove-filter-${field}"]`)?.previousElementSibling?.textContent ?? null; +const reset = () => screen.getByTestId('object-data-reset-source') as HTMLButtonElement; + +beforeEach(() => { + cleanup(); + vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: [] }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }))); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.clearAllMocks(); +}); + +describe('a list opened from a related tab knows its record (objectstack#35601)', () => { + it('the condition tag names the record, and a breadcrumb leads back to it', () => { + renderAt(`filter[project]=P-1&${RECORD_TRAIL_PARAM}=${TRAIL}`); + expect(chipText('project')).toBe('Launch'); + const crumbs = screen.getByTestId('object-data-source-crumbs'); + expect(crumbs.textContent).toBe('Projects/Launch/Tasks'); + expect(screen.getByTestId('object-data-source-record').getAttribute('href')).toContain('/apps/demo/project/record/P-1'); + // Already on the sourced condition: nothing to reset. + expect(reset().disabled).toBe(true); + }); + + it('「重置」 puts the sourced condition back after the reader changed the filters', () => { + renderAt(`filter[project]=P-1&filter[status]=open&${RECORD_TRAIL_PARAM}=${TRAIL}`); + fireEvent.click(screen.getByTestId('object-data-remove-filter-project')); + expect(params().get('filter[project]')).toBeNull(); + // The trail outlives the removed condition, so the way back stays. + expect(reset().disabled).toBe(false); + fireEvent.click(reset()); + expect(params().get('filter[project]')).toBe('P-1'); + expect(params().get('filter[status]')).toBeNull(); + expect(params().get(RECORD_TRAIL_PARAM)).not.toBeNull(); + expect(reset().disabled).toBe(true); + }); + + it('New opens the record form as that record\'s child', () => { + renderAt(`filter[project]=P-1&${RECORD_TRAIL_PARAM}=${TRAIL}`); + fireEvent.click(document.querySelector('[data-testid="object-data-new-button"]')!); + expect(params().get('form')).toBe('new'); + expect(params().get('formObject')).toBe('task'); + expect(params().get('formLink')).toBe('project:P-1'); + }); + + it('CONTROL — the same filter without a trail: the id, no breadcrumb, no reset', () => { + renderAt('filter[project]=P-1'); + expect(chipText('project')).toBe('= P-1'); + expect(screen.queryByTestId('object-data-source-crumbs')).toBeNull(); + expect(screen.queryByTestId('object-data-reset-source')).toBeNull(); + }); +}); + +describe('sourceRelationshipField', () => { + it('is the one single-valued relationship to the source object, and none when that is ambiguous', () => { + const source = { o: 'project', i: 'P-1' }; + expect(sourceRelationshipField(OBJECTS[0], source)).toBe('project'); + expect(sourceRelationshipField({ fields: { a: { type: 'lookup', reference: 'project' }, b: { type: 'lookup', reference: 'project' } } }, source)).toBeUndefined(); + expect(sourceRelationshipField({ fields: { a: { type: 'lookup', reference: 'project', multiple: true } } }, source)).toBeUndefined(); + }); +}); diff --git a/ui/packages/app-shell/src/views/__tests__/RelatedRecordActionsBridge.viewAll-12741.test.tsx b/ui/packages/app-shell/src/views/__tests__/RelatedRecordActionsBridge.viewAll-12741.test.tsx index 701799a325f..285c9639732 100644 --- a/ui/packages/app-shell/src/views/__tests__/RelatedRecordActionsBridge.viewAll-12741.test.tsx +++ b/ui/packages/app-shell/src/views/__tests__/RelatedRecordActionsBridge.viewAll-12741.test.tsx @@ -34,6 +34,7 @@ import '@object-ui/plugin-detail'; import { RelatedRecordActionsBridge } from '../RelatedRecordActionsBridge'; import { parseUrlFilterTriples } from '../drillUrlFilters'; +import { RECORD_TRAIL_PARAM, decodeRecordTrail } from '../../urlParams'; /** Desktop, pinned (objectui#8399): under 768px a table related list is a card gallery. */ beforeAll(() => { @@ -165,6 +166,17 @@ describe('objectui#12741 — "View all" opens this parent’s children on the li expect(parseUrlFilterTriples(new URLSearchParams(search))).toEqual([['project', '=', 'P-1']]); }); + // objectstack#35601 — the list knows where it came from: the record this + // list hangs under rides on the record trail, so the list page can name it + // in its condition tag and breadcrumb, and reset to it. + it('the destination carries this record on the trail, named by its title', async () => { + mount(); + await waitForRows(); + fireEvent.click(viewAll()!); + const search = new URLSearchParams(location().split('?')[1]); + expect(decodeRecordTrail(search.get(RECORD_TRAIL_PARAM))).toEqual([{ o: 'project', i: 'P-1', t: 'Launch' }]); + }); + it('`showViewAll: false` draws no link', async () => { mount({ properties: { showViewAll: false } }); await waitForRows(); diff --git a/ui/packages/plugin-detail/src/__tests__/RecordRelatedListRenderer.showViewAll-12741.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordRelatedListRenderer.showViewAll-12741.test.tsx index a8e7a206f45..2ea2cd2d2ce 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordRelatedListRenderer.showViewAll-12741.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordRelatedListRenderer.showViewAll-12741.test.tsx @@ -17,7 +17,8 @@ * (`handlers.onViewAll`) and the list has records, including when every * row fits on the list (no truncation condition: the spec states none); * - `false` → no link, whatever the host offers; - * - an EMPTY list → no link; + * - an EMPTY list → the 「↗」 open-in-list entry still draws + * (objectstack#35601: the list page is where records are found to add); * - no destination from the host (none offered, or no host at all) → no link. * * The destination itself, the child object's list scoped to this parent, is @@ -122,6 +123,17 @@ describe('record:related_list.showViewAll — default on (objectui#12741)', () = await waitForRows(); expect(viewAll()).toBeInTheDocument(); }); + + // objectstack#35601 — migrated from 「an EMPTY list: no link」: an empty list + // still opens the child list under this record (「↗」). + it('an EMPTY list: 「↗」 still draws and opens the host’s destination', async () => { + mount(undefined, { rows: [] }); + expect(await screen.findByText(/no related records|no records/i)).toBeInTheDocument(); + const link = viewAll(); + expect(link).toBeInTheDocument(); + fireEvent.click(link!); + expect(onViewAll).toHaveBeenCalledTimes(1); + }); }); describe('record:related_list.showViewAll — when no link draws (objectui#12741)', () => { @@ -134,13 +146,6 @@ describe('record:related_list.showViewAll — when no link draws (objectui#12741 expect(onViewAll).not.toHaveBeenCalled(); }); - it('an EMPTY list: no link', async () => { - mount(undefined, { rows: [] }); - expect(await screen.findByTestId('related-list-new')).toBeInTheDocument(); - expect(await screen.findByText(/no related records|no records/i)).toBeInTheDocument(); - expect(viewAll()).toBeNull(); - }); - it('a host that offers no destination: no link', async () => { mount(undefined, { host: HOST_WITHOUT_DESTINATION }); await waitForRows(); diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.addGateDataSource.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.addGateDataSource.test.tsx index 4d42c5670d4..5383b1ab123 100644 --- a/ui/packages/plugin-detail/src/__tests__/RelatedList.addGateDataSource.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.addGateDataSource.test.tsx @@ -66,6 +66,8 @@ const ADD = { }; const makeDS = () => ({ + // The picker's add is one transactional batch (objectstack#35601); a source without it offers no picker. + batchTransaction: vi.fn(async () => ({ results: [] })), find: vi.fn(async () => [{ id: 'ps_1', label: 'Admin' }]), getObjectSchema: vi.fn(async (name: string) => ({ name, fields: {} })), }); diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.addGrant-12082.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.addGrant-12082.test.tsx index c1b7be787b3..3ec80bd7c46 100644 --- a/ui/packages/plugin-detail/src/__tests__/RelatedList.addGrant-12082.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.addGrant-12082.test.tsx @@ -79,6 +79,8 @@ const REPARENT_ADD = { picker: { object: CHILD, labelField: 'name' }, label: ADD function makeDS() { return { + // The picker's add is one transactional batch (objectstack#35601); a source without it offers no picker. + batchTransaction: vi.fn(async () => ({ results: [] })), find: vi.fn(async () => [{ id: 'row_1', permission_set_id: 'ps_1' }]), getObjectSchema: vi.fn(async (name: string) => ({ name, fields: {} })), create: vi.fn(async (_o: string, data: any) => data), diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.addPickerFilter.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.addPickerFilter.test.tsx index 1df1647af70..d566049210f 100644 --- a/ui/packages/plugin-detail/src/__tests__/RelatedList.addPickerFilter.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.addPickerFilter.test.tsx @@ -55,6 +55,8 @@ const positionSchema = { }; const makeDataSource = () => ({ + // The picker's add is one transactional batch (objectstack#35601); a source without it offers no picker. + batchTransaction: vi.fn(async () => ({ results: [] })), getObjectSchema: vi.fn(async (api: string) => api === 'sys_position' ? positionSchema : junctionSchema, ), diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.addPickerGuard.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.addPickerGuard.test.tsx index 133af878e9b..af5d03caecd 100644 --- a/ui/packages/plugin-detail/src/__tests__/RelatedList.addPickerGuard.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.addPickerGuard.test.tsx @@ -44,6 +44,8 @@ const junctionRows = [ ]; const makeDataSource = () => ({ + // The picker's add is one transactional batch (objectstack#35601); a source without it offers no picker. + batchTransaction: vi.fn(async () => ({ results: [] })), getObjectSchema: vi.fn(async () => ({ name: 'sys_user_permission_set', fields: { permission_set_id: { type: 'text', label: 'Permission Set' } }, diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.addPickerLabelField.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.addPickerLabelField.test.tsx index a34b4f68ad6..c3c6f3e7647 100644 --- a/ui/packages/plugin-detail/src/__tests__/RelatedList.addPickerLabelField.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.addPickerLabelField.test.tsx @@ -60,6 +60,8 @@ const candidates = [ ]; const makeDataSource = () => ({ + // The picker's add is one transactional batch (objectstack#35601); a source without it offers no picker. + batchTransaction: vi.fn(async () => ({ results: [] })), getObjectSchema: vi.fn(async (api: string) => api === 'sys_permission_set' ? permissionSetSchema : junctionSchema, ), diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.bodyTable-27055.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.bodyTable-27055.test.tsx index 17fbcebe836..a3cd34951f4 100644 --- a/ui/packages/plugin-detail/src/__tests__/RelatedList.bodyTable-27055.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.bodyTable-27055.test.tsx @@ -426,14 +426,22 @@ describe('RelatedList — which body-table columns are totalled (objectstack#299 expect(summaryRow()).toBeNull(); }); - it('a dynamic amount totals in the tenant default currency, and not at all without one', async () => { - const first = renderPlan({ columns: ['name', 'dynamic_fee'], parent: contract({}), tenantCurrency: 'CNY' }); + it('a dynamic amount totals in the tenant default currency', async () => { + renderPlan({ columns: ['name', 'dynamic_fee'], parent: contract({}), tenantCurrency: 'CNY' }); await waitFor(() => expect(summaryOf('dynamic_fee')).toMatch(/CN¥|¥/)); expect(summaryOf('dynamic_fee')).toContain('6.00'); - first.unmount(); + }); + + // objectstack#35710 — with no currency resolving the column's cells still + // draw as amounts (two places, no symbol); the total is the same server + // figure drawn the same way, never a missing last row. + it('with no currency resolving, the total is the server figure drawn as its cells are: an amount, no symbol', async () => { const { aggregate } = renderPlan({ columns: ['name', 'dynamic_fee'], parent: contract({}) }); - await settled(aggregate); - expect(summaryRow()).toBeNull(); + await waitFor(() => expect(summaryOf('dynamic_fee')).not.toBeNull()); + expect(summaryOf('dynamic_fee')).toMatch(/(^|\D)6\.00$/); + expect(summaryOf('dynamic_fee')).not.toMatch(/[$€¥£]|[A-Z]{3}/); + expect(aggregate.mock.calls[0][1].aggregations).toEqual([{ function: 'sum', field: 'dynamic_fee', alias: 'dynamic_fee' }]); + expect(aggregate.mock.calls[0][1].groupBy ?? []).toEqual([]); }); }); diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedListGrid-28865.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedListGrid-28865.test.tsx index 97457052752..9a9d98bc195 100644 --- a/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedListGrid-28865.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedListGrid-28865.test.tsx @@ -16,14 +16,14 @@ * on the grid's host channel (React props on `SchemaRenderer`, the ones * `plugin-list`'s `ListView` hands the same grid), its own pager stays the one * pager, and a row action the grid dispatches goes back to the host's - * `onRowAction`. The count shows once. + * `onRowAction`. The count shows once: in the tab title (objectstack#35601). */ import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest'; -import { cleanup, render, screen, waitFor, fireEvent, act } from '@testing-library/react'; +import { cleanup, render, screen, waitFor, act } from '@testing-library/react'; import '@testing-library/jest-dom'; import * as React from 'react'; -import { FilterScopeProvider } from '@object-ui/react'; +import { FilterScopeProvider, RecordContextProvider, RecordPagePreferencesProvider } from '@object-ui/react'; import { RelatedList } from '../RelatedList'; import { RelatedListEnlargedContext } from '../relatedListCompact'; @@ -170,33 +170,58 @@ describe('the enlarged related tab on a desktop is the child object list face (o expect(screen.getByText('Previous')).toBeInTheDocument(); }); - it('DEVIATION, pinned: while the filter box has text the grid still gets this list’s sort on the host channel', async () => { - // The list sorts its in-memory rows itself in this state (it read them - // all). Handed as a HOST sort, the grid's manual-sort rule applies: it - // offers no header sort on a relational column (`owner_id` here), whose - // stored value is an id. The data-table this face drew before sorted that - // column by its label in this one state. + // objectstack#35601 retired the tab's filter box and chips, and with them + // the in-memory sort state the DEVIATION pin above them described: every + // sort is now the server's. + it('the count is not repeated under the grid: the line keeps only the page (the count lives in the tab title)', async () => { renderList(); await waitFor(() => expect(h.props?.rowCount).toBe(TOTAL)); - fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'Deal 1' } }); - await waitFor(() => expect(h.props.rowCount).toBe(11)); - expect(h.props.manualPagination).toBe(true); - expect(h.props.onSortChange).toEqual(expect.any(Function)); - expect(h.schema.data.items.every((row: any) => row.name.startsWith('Deal 1'))).toBe(true); + expect(document.querySelector('[data-related-enlarged-status]')?.textContent).toBe('Page 1 of 2'); + expect(document.querySelector('[data-related-chip]')).toBeNull(); + expect(screen.queryByRole('searchbox')).toBeNull(); }); - it('the count shows once: on the 全部 chip, not again on the line under the toolbar', async () => { - renderList(); - await waitFor(() => expect(document.querySelector('[data-related-chip="all"]')?.textContent).toBe(`All${TOTAL}`)); - // The line keeps only the page; it no longer repeats the 30. - expect(document.querySelector('[data-related-enlarged-status]')?.textContent).toBe('Page 1 of 2'); + it('column widths and order are the reader\'s: read from and written to the record-page preference (objectstack#35601)', async () => { + const stored = { order: ['amount', 'name', 'owner_id'], widths: { name: 260 } }; + const store = { + get: vi.fn(() => ({ relatedLists: { 'opportunity.account': { columnState: stored } } })), + update: vi.fn(), + }; + render( + + + + + + + + + , + ); + await waitFor(() => expect(h.props?.rowCount).toBe(TOTAL)); + expect(h.schema.columnState).toEqual(stored); + expect(h.schema.id).toBe('related-opportunity.account'); + act(() => h.props.onColumnStateChange({ widths: { name: 300 } })); + expect(store.update).toHaveBeenCalledWith('account', { + relatedLists: { 'opportunity.account': { columnState: { widths: { name: 300 } } } }, + }); }); - it('a chip that narrows keeps its own count on the line, a different number from 全部’s', async () => { + it('CONTROL: with no preference store the grid gets no column state and no writer', async () => { renderList(); - await waitFor(() => expect(document.querySelector('[data-related-chip="all"]')?.textContent).toBe(`All${TOTAL}`)); - fireEvent.click(document.querySelector('[data-related-chip="mine"]')!); - await waitFor(() => expect(document.querySelector('[data-related-enlarged-status]')?.textContent).toMatch(/^1 row/)); + await waitFor(() => expect(h.props?.rowCount).toBe(TOTAL)); + expect(h.schema).not.toHaveProperty('columnState'); + expect(h.props).not.toHaveProperty('onColumnStateChange'); }); it('row actions: the host’s defs ride to the grid, and a dispatch from the grid reaches onRowAction with the row', async () => { diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx index f42db816767..10817d7d6d5 100644 --- a/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx @@ -7,38 +7,49 @@ */ /** - * objectstack#27524 — the enlarged related list (the record page's active - * tab, `RelatedListEnlargedContext`), the ride-along ruled at ③'s preview - * gate: the board's toolbar over the table — the filter, 全部 / 我的 / 逾期, - * 新建, 导出 — with the count and page line between them, and no card header - * or card foot. Each chip is drawn only where the child object declares what - * it says (an `owner_id` column; a `dueLike` deadline with no `settledWhen`), - * and a chip narrows the list's own read; 导出 asks the server for the rows - * the face shows. + * The record page's related tab (the enlarged related list, + * `RelatedListEnlargedContext`). + * + * objectstack#35601 — no filter, sort, options or condition row, and the count + * only in the tab title. The right end carries two entries: 「↗」 (the child's + * list under this record's condition, on an empty list too) and 「+ 添加」, + * the one add entry, decided by the relationship when the page authored no + * `add`: a `lookup` child opens a picker of the child object whose first row is + * 「新建」; a `master_detail` child with a catalog opens a picker of the + * catalog; one with none creates a row directly. A pick of several is ONE + * transactional batch: all rows or none. A stateful child is grouped by its + * status, completed last. The reader's header sort is remembered. */ import { describe, it, expect, vi, beforeAll } from 'vitest'; import { render, screen, waitFor, fireEvent, within } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; -import { FilterScopeProvider } from '@object-ui/react'; +import { FilterScopeProvider, RecordContextProvider, RecordPagePreferencesProvider, type RecordPagePreference } from '@object-ui/react'; import { ComponentRegistry } from '@object-ui/core'; -import { I18nProvider } from '@object-ui/i18n'; -import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; import { RelatedList } from '../RelatedList'; import { RelatedListEnlargedContext } from '../relatedListCompact'; /** * The enlarged face draws `object-grid` (objectstack#28865), which * `plugin-grid` registers and this package cannot import (`plugin-grid` - * depends on it). A stand-in draws the rows it is handed, as a table. + * depends on it). A stand-in draws the rows it is handed, as a table, with a + * header button per column that sorts through the host channel. */ -function ObjectGridStandIn({ schema }: { schema: any }) { +function ObjectGridStandIn({ schema, onSortChange }: { schema: any; onSortChange?: (s: unknown) => void }) { const rows: any[] = schema?.data?.items ?? []; const columns: string[] = schema?.columns ?? []; return ( - {columns.map((c) => )} + + + {columns.map((c) => ( + + ))} + + {rows.map((row) => {columns.map((c) => )})}
{c}
+ +
{String(row[c] ?? '')}
); @@ -59,225 +70,317 @@ const ROWS = [ { id: 't1', subject: 'Send quote', lead: 'L-1', owner_id: 'u-1', due_date: '2026-10-30' }, { id: 't2', subject: 'Call back', lead: 'L-1', owner_id: 'u-2', due_date: '2026-11-04' }, ]; +const CANDIDATES = [ + { id: 'c1', name: 'Alpha' }, + { id: 'c2', name: 'Bravo' }, + { id: 'c3', name: 'Charlie' }, +]; + +interface Harness { + fields?: Record; + rows?: any[]; + batch?: ((ops: unknown[]) => Promise) | null; + pickerObject?: string; +} -function dataSourceFor(fields: Record = TASK_FIELDS) { - return { - find: vi.fn(async () => ({ data: ROWS, total: ROWS.length })), - getObjectSchema: vi.fn(async () => ({ name: 'task', fields })), - exportDownload: vi.fn(async () => new Blob(['subject\n'], { type: 'text/csv' })), +function dataSourceFor({ fields = TASK_FIELDS, rows = ROWS, batch, pickerObject }: Harness = {}) { + const ds: Record = { + // The list's own read carries this record's condition; the picker's read + // (the child object for a lookup, the catalog for a master_detail) does not. + find: vi.fn(async (resource: string, params?: unknown) => ( + resource === 'task' && JSON.stringify(params ?? {}).includes('L-1') + ? { data: rows, total: rows.length } + : { data: CANDIDATES, total: CANDIDATES.length } + )), + getObjectSchema: vi.fn(async (name: string) => ( + name === 'task' + ? { name: 'task', fields } + : { name: name ?? pickerObject, fields: { name: { type: 'text', label: 'Name' } } } + )), + create: vi.fn(async () => ({})), + update: vi.fn(async () => ({})), }; + if (batch !== null) ds.batchTransaction = vi.fn(batch ?? (async (ops: unknown[]) => ({ results: ops.map(() => ({})) }))); + return ds; } function renderList({ enlarged = true, - fields, onNew = vi.fn(), -}: { enlarged?: boolean; fields?: Record; onNew?: () => void } = {}) { - const dataSource = dataSourceFor(fields); + onViewAll = vi.fn(), + preferences = null, + ...harness +}: Harness & { + enlarged?: boolean; + onNew?: (() => void) | undefined; + onViewAll?: (() => void) | undefined; + preferences?: { get: (o: string) => RecordPagePreference; update: (o: string, p: RecordPagePreference) => void } | null; +} = {}) { + const dataSource = dataSourceFor(harness); const utils = render( - - - + + + + + , ); return { ...utils, dataSource }; } -const toolbar = () => document.querySelector('[data-related-enlarged-toolbar]') as HTMLElement | null; -const lastFilter = (find: ReturnType) => JSON.stringify(find.mock.calls[find.mock.calls.length - 1][1].$filter); +/** The list's own reads: the child object under this record's condition. */ +const listReads = (ds: Record) => + ds.find.mock.calls.filter(([r, p]: [string, unknown]) => r === 'task' && JSON.stringify(p ?? {}).includes('L-1')).length; +const toolbar = () => document.querySelector('[data-related-enlarged-toolbar]') as HTMLElement; +const addButton = () => toolbar().querySelector('[data-related-add]') as HTMLElement | null; -describe('the enlarged related list draws the board toolbar (objectstack#27524)', () => { - it('a toolbar over the table: the filter, 全部 N / 我的 / 逾期, 新建, 导出 — and no card header or foot', async () => { - const onNew = vi.fn(); - renderList({ onNew }); +async function pickThree() { + fireEvent.click(addButton()!); + const dialog = await screen.findByTestId('record-picker-dialog'); + for (const id of ['c1', 'c2', 'c3']) { + fireEvent.click(await within(dialog).findByTestId(`record-row-${id}`)); + } + fireEvent.click(within(dialog).getByTestId('record-picker-confirm')); +} + +describe('the related tab carries 「↗」 and 「+ 添加」 alone (objectstack#35601)', () => { + it('no filter, chips, export or New; the count is not repeated; ↗ opens the list', async () => { + const onViewAll = vi.fn(); + renderList({ onViewAll }); await waitFor(() => expect(screen.getByText('Send quote')).toBeInTheDocument()); - const bar = toolbar()!; - expect(bar).not.toBeNull(); + const bar = toolbar(); expect(bar.getAttribute('role')).toBe('toolbar'); - expect(within(bar).getByRole('searchbox', { name: 'Filter Tasks…' })).toBeInTheDocument(); - const chips = Array.from(bar.querySelectorAll('[data-related-chip]')).map((el) => el.getAttribute('data-related-chip')); - expect(chips).toEqual(['all', 'mine', 'overdue']); - await waitFor(() => expect(bar.querySelector('[data-related-chip="all"]')?.textContent).toBe('All2')); - expect(bar.querySelector('[data-related-chip="all"]')?.getAttribute('aria-pressed')).toBe('true'); - fireEvent.click(within(bar).getByTestId('related-list-new')); - expect(onNew).toHaveBeenCalledTimes(1); - expect(bar.querySelector('[data-related-enlarged-export]')).not.toBeNull(); - // The count shows once (objectstack#28865): the 全部 chip says 2, so the - // line under the toolbar, which holds no page either, is not drawn. + const controls = Array.from(bar.querySelectorAll('button')).map((b) => b.getAttribute('aria-label') || b.textContent); + expect(controls).toEqual(['View All', 'Add']); + expect(within(bar).queryByRole('searchbox')).toBeNull(); + expect(bar.querySelector('[data-related-chip], [data-related-enlarged-export]')).toBeNull(); + expect(screen.queryByTestId('related-list-new')).toBeNull(); expect(document.querySelector('[data-related-enlarged-status]')).toBeNull(); - // No card: no header title, no count badge, no View all. expect(screen.queryByLabelText('2 records')).toBeNull(); - expect(document.querySelector('.rounded-xl, [class*="card"]')).toBeNull(); - expect(document.querySelector('[data-object-grid-stand-in] thead')).not.toBeNull(); + fireEvent.click(bar.querySelector('[data-related-open-list]')!); + expect(onViewAll).toHaveBeenCalledTimes(1); + }); + + it('an empty list keeps both entries', async () => { + renderList({ rows: [] }); + await waitFor(() => expect(document.querySelector('[data-related-enlarged-empty]')).not.toBeNull()); + expect(toolbar().querySelector('[data-related-open-list]')).not.toBeNull(); + expect(addButton()).not.toBeNull(); }); - it('我的 and 逾期 narrow the list\'s own read, beside the parent', async () => { - const { dataSource } = renderList(); + it('control: outside the active tab the list keeps its card face', async () => { + renderList({ enlarged: false }); await waitFor(() => expect(screen.getByText('Send quote')).toBeInTheDocument()); - const before = lastFilter(dataSource.find); - expect(before).not.toContain('owner_id'); + expect(document.querySelector('[data-related-enlarged-toolbar]')).toBeNull(); + expect(screen.getByLabelText('2 records')).toBeInTheDocument(); + }); +}); - fireEvent.click(document.querySelector('[data-related-chip="mine"]')!); - await waitFor(() => expect(lastFilter(dataSource.find)).toContain('owner_id')); - expect(lastFilter(dataSource.find)).toContain('u-1'); - expect(lastFilter(dataSource.find)).toContain('L-1'); - expect(document.querySelector('[data-related-chip="mine"]')?.getAttribute('aria-pressed')).toBe('true'); +describe('「+ 添加」 is decided by the relationship, and a pick is one transactional batch (objectstack#35601)', () => { + it('lookup: the picker lists the child object, its first row is 新建, and three picks are ONE batch of three', async () => { + const onNew = vi.fn(); + const { dataSource } = renderList({ onNew }); + await waitFor(() => expect(screen.getByText('Send quote')).toBeInTheDocument()); + fireEvent.click(addButton()!); + const dialog = await screen.findByTestId('record-picker-dialog'); + expect(within(dialog).getByTestId('record-picker-create-row')).toHaveTextContent('New'); + fireEvent.click(within(dialog).getByTestId('record-picker-create-row')); + expect(onNew).toHaveBeenCalledTimes(1); - fireEvent.click(document.querySelector('[data-related-chip="overdue"]')!); - await waitFor(() => expect(lastFilter(dataSource.find)).toContain('due_date')); - expect(lastFilter(dataSource.find)).not.toContain('owner_id'); - expect(lastFilter(dataSource.find)).toContain('<'); + const readsBefore = listReads(dataSource); + await pickThree(); + await waitFor(() => expect(dataSource.batchTransaction).toHaveBeenCalledTimes(1)); + expect(dataSource.batchTransaction.mock.calls[0][0]).toEqual([ + { object: 'task', action: 'update', id: 'c1', data: { lead: 'L-1' } }, + { object: 'task', action: 'update', id: 'c2', data: { lead: 'L-1' } }, + { object: 'task', action: 'update', id: 'c3', data: { lead: 'L-1' } }, + ]); + expect(dataSource.update).not.toHaveBeenCalled(); + expect(dataSource.create).not.toHaveBeenCalled(); + // The list reads again once the batch committed. + await waitFor(() => expect(listReads(dataSource)).toBeGreaterThan(readsBefore)); }); - it('a chip is drawn only where the object declares what it says', async () => { + it('a failing batch adds nothing and says why; no single write is sent', async () => { + const { dataSource } = renderList({ + batch: async () => { throw Object.assign(new Error("Field 'quantity' is required"), { status: 400 }); }, + }); + await waitFor(() => expect(screen.getByText('Send quote')).toBeInTheDocument()); + const readsBefore = listReads(dataSource); + await pickThree(); + expect(await screen.findByRole('alert')).toHaveTextContent("Field 'quantity' is required"); + expect(dataSource.batchTransaction).toHaveBeenCalledTimes(1); + expect(dataSource.update).not.toHaveBeenCalled(); + expect(dataSource.create).not.toHaveBeenCalled(); + expect(listReads(dataSource)).toBe(readsBefore); + }); + + it('master_detail with a catalog: the picker lists the catalog and a pick creates a row naming it', async () => { const { dataSource } = renderList({ fields: { subject: { type: 'text', label: 'Subject' }, - lead: { type: 'lookup', reference: 'lead', label: 'Lead' }, - // A deadline with a `settledWhen`: no query can ask which are settled. - due_date: { type: 'date', label: 'Due', dueLike: true, settledWhen: 'record.done == true' }, + lead: { type: 'master_detail', reference: 'lead', label: 'Lead' }, + product: { type: 'lookup', reference: 'product', label: 'Product', required: true }, + owner_id: { type: 'lookup', reference: 'sys_user', label: 'Owner' }, }, }); - await waitFor(() => expect(dataSource.find).toHaveBeenCalled()); await waitFor(() => expect(screen.getByText('Send quote')).toBeInTheDocument()); - // 全部 alone is no choice: no chip group at all. - expect(document.querySelector('[data-related-chip]')).toBeNull(); - expect(toolbar()).not.toBeNull(); + await pickThree(); + await waitFor(() => expect(dataSource.batchTransaction).toHaveBeenCalledTimes(1)); + expect(dataSource.find.mock.calls.some(([r]: [string]) => r === 'product')).toBe(true); + expect(dataSource.batchTransaction.mock.calls[0][0]).toEqual([ + { object: 'task', action: 'create', data: { lead: 'L-1', product: 'c1' } }, + { object: 'task', action: 'create', data: { lead: 'L-1', product: 'c2' } }, + { object: 'task', action: 'create', data: { lead: 'L-1', product: 'c3' } }, + ]); }); - it('导出 asks the server for the rows the face shows: the parent and the chip', async () => { - const { dataSource } = renderList(); + it('master_detail with no catalog: 「+ 添加」 creates a row directly', async () => { + const onNew = vi.fn(); + renderList({ + onNew, + fields: { subject: { type: 'text', label: 'Subject' }, lead: { type: 'master_detail', reference: 'lead', label: 'Lead' } }, + }); await waitFor(() => expect(screen.getByText('Send quote')).toBeInTheDocument()); - const createObjectURL = vi.fn(() => 'blob:x'); - const revokeObjectURL = vi.fn(); - Object.assign(URL, { createObjectURL, revokeObjectURL }); - fireEvent.click(document.querySelector('[data-related-chip="mine"]')!); - await waitFor(() => expect(lastFilter(dataSource.find)).toContain('owner_id')); - fireEvent.click(document.querySelector('[data-related-enlarged-export]')!); - await waitFor(() => expect(dataSource.exportDownload).toHaveBeenCalledTimes(1)); - const [resource, request] = dataSource.exportDownload.mock.calls[0] as unknown as [string, { format: string; filter: unknown; fields: string[] }]; - expect(resource).toBe('task'); - expect(request.format).toBe('csv'); - expect(JSON.stringify(request.filter)).toContain('L-1'); - expect(JSON.stringify(request.filter)).toContain('u-1'); - expect(request.fields).toEqual(['subject', 'due_date']); + fireEvent.click(addButton()!); + expect(onNew).toHaveBeenCalledTimes(1); + expect(screen.queryByTestId('record-picker-dialog')).toBeNull(); }); - it('control: outside the active tab the list keeps its card face', async () => { - renderList({ enlarged: false }); + it('a data source with no transactional batch offers no picker: never a loop of single writes', async () => { + const onNew = vi.fn(); + renderList({ onNew, batch: null }); await waitFor(() => expect(screen.getByText('Send quote')).toBeInTheDocument()); - expect(toolbar()).toBeNull(); - expect(screen.getByLabelText('2 records')).toBeInTheDocument(); + fireEvent.click(addButton()!); + expect(onNew).toHaveBeenCalledTimes(1); + expect(screen.queryByTestId('record-picker-dialog')).toBeNull(); }); }); -/** - * objectstack#30069 — 导出 asks the list page's question. `ListView`'s - * `exportPermitted` reads the child object's effective API operation set - * (`/me/permissions` `apiOperations`); the related table reads the same - * `usePermissions()` source, so a reader the list page hides 导出 from sees no - * 导出 here either, and a reader who may export still exports this relation's - * rows alone. A refusal that still reaches the table — the server's 403 — - * reads in the Console's language, never as the route's English sentence. - */ -describe('the related table asks the list page\'s export question (objectstack#30069)', () => { - const SERVER_SENTENCE = "Export is not permitted on object 'task' for this user"; +describe('a stateful child is grouped by its status on the related tab (objectstack#35601)', () => { + const STATEFUL = { + subject: { type: 'text', label: 'Subject' }, + lead: { type: 'lookup', reference: 'lead', label: 'Lead' }, + status: { + type: 'select', + label: 'Status', + options: [ + { value: 'todo', label: 'To Do' }, + { value: 'done', label: 'Done' }, + { value: 'doing', label: 'Doing' }, + ], + }, + due_date: { type: 'date', label: 'Due', dueLike: true, settledWhen: "record.status == 'done'" }, + }; + const STATEFUL_ROWS = [ + { id: 's1', subject: 'Finished', lead: 'L-1', status: 'done' }, + { id: 's2', subject: 'Started', lead: 'L-1', status: 'doing' }, + { id: 's3', subject: 'Queued', lead: 'L-1', status: 'todo' }, + ]; + + it('open groups first in option order, completed last, each collapsible', async () => { + renderList({ fields: STATEFUL, rows: STATEFUL_ROWS }); + await waitFor(() => expect(screen.getByText('Finished')).toBeInTheDocument()); + const groups = Array.from(document.querySelectorAll('[data-related-status-group]')); + expect(groups.map((g) => g.getAttribute('data-related-status-group'))).toEqual(['todo', 'doing', 'done']); + expect(groups.map((g) => g.getAttribute('data-settled'))).toEqual(['false', 'false', 'true']); + fireEvent.click(within(groups[2] as HTMLElement).getByRole('button', { expanded: true })); + expect(screen.queryByText('Finished')).toBeNull(); + expect(screen.getByText('Queued')).toBeInTheDocument(); + }); - function grant(apiOperations: string[]): MePermissionsAuthenticatedResponse { + it('control: with no declared settled status there is nothing to tell open from done, so no groups', async () => { + const { due_date: _drop, ...noDeadline } = STATEFUL; + renderList({ fields: noDeadline, rows: STATEFUL_ROWS }); + await waitFor(() => expect(screen.getByText('Finished')).toBeInTheDocument()); + expect(document.querySelector('[data-related-status-groups]')).toBeNull(); + }); +}); + +describe('the related tab remembers the reader\'s header sort (objectstack#35601)', () => { + function store(initial: RecordPagePreference = {}) { + const states: Record = { lead: initial }; return { - authenticated: true, - userId: 'u-1', - tenantId: null, - hasAnyQueue: false, - objectsUsingQueues: [], - positions: [], - permissionSets: ['rep'], - objects: { - task: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false, apiOperations }, - }, - fields: {}, - } as MePermissionsAuthenticatedResponse; + get: vi.fn((o: string) => states[o] ?? {}), + update: vi.fn((o: string, patch: RecordPagePreference) => { states[o] = { ...states[o], ...patch }; }), + }; } - function renderUnder(perms: MePermissionsAuthenticatedResponse, language = 'en') { - const dataSource = dataSourceFor(); + it('a header click is written to the record-page preference of the parent object', async () => { + const preferences = store(); render( - - - - - - - - - , + + + + + + + , ); - return dataSource; - } - - it('a reader without export sees no 导出, and nothing is asked of the export route', async () => { - const dataSource = renderUnder(grant(['get', 'list', 'create', 'update'])); await waitFor(() => expect(screen.getByText('Send quote')).toBeInTheDocument()); - expect(toolbar()).not.toBeNull(); - expect(document.querySelector('[data-related-enlarged-export]')).toBeNull(); - expect(dataSource.exportDownload).not.toHaveBeenCalled(); + fireEvent.click(document.querySelector('[data-sort-header="subject"]')!); + await waitFor(() => expect(preferences.update).toHaveBeenCalled()); + expect(preferences.update.mock.calls.at(-1)).toEqual([ + 'lead', + { relatedLists: { 'task.lead': { sort: { field: 'subject', order: 'desc' } } } }, + ]); }); - it('a reader with export sees 导出 and exports this relation\'s rows alone', async () => { - const dataSource = renderUnder(grant(['get', 'list', 'export'])); - await waitFor(() => expect(screen.getByText('Send quote')).toBeInTheDocument()); - Object.assign(URL, { createObjectURL: vi.fn(() => 'blob:x'), revokeObjectURL: vi.fn() }); - const button = document.querySelector('[data-related-enlarged-export]'); - expect(button).not.toBeNull(); - fireEvent.click(button!); - await waitFor(() => expect(dataSource.exportDownload).toHaveBeenCalledTimes(1)); - const [resource, request] = dataSource.exportDownload.mock.calls[0] as unknown as [string, { filter: unknown }]; - expect(resource).toBe('task'); - // The parent scope: the lead this record page is about, and only it. - expect(JSON.stringify(request.filter)).toContain('"lead"'); - expect(JSON.stringify(request.filter)).toContain('L-1'); - }); - - it('the server\'s 403 reads in the Console\'s language, not as the route\'s English sentence', async () => { - const dataSource = renderUnder(grant(['get', 'list', 'export']), 'zh'); - dataSource.exportDownload.mockRejectedValueOnce( - Object.assign(new Error(SERVER_SENTENCE), { code: 'EXPORT_NOT_PERMITTED', status: 403 }), + it('a remembered sort is the one the list reads by', async () => { + const preferences = store({ relatedLists: { 'task.lead': { sort: { field: 'subject', order: 'desc' } } } }); + const ds = dataSourceFor(); + render( + + + + + + + , ); - await waitFor(() => expect(screen.getByText('Send quote')).toBeInTheDocument()); - fireEvent.click(document.querySelector('[data-related-enlarged-export]')!); - const alert = await screen.findByRole('alert'); - expect(alert.textContent).toBe('你没有导出这些记录的权限。如需导出,请联系管理员。'); - expect(alert.textContent).not.toContain(SERVER_SENTENCE); - }); - - it('control: a failure that is not a refusal still says the server\'s sentence', async () => { - const dataSource = renderUnder(grant(['get', 'list', 'export'])); - dataSource.exportDownload.mockRejectedValueOnce(Object.assign(new Error('Export timed out'), { status: 504 })); - await waitFor(() => expect(screen.getByText('Send quote')).toBeInTheDocument()); - fireEvent.click(document.querySelector('[data-related-enlarged-export]')!); - const alert = await screen.findByRole('alert'); - expect(alert.textContent).toBe('Export timed out'); + await waitFor(() => { + const last = ds.find.mock.calls.filter(([r]: [string]) => r === 'task').at(-1); + expect(JSON.stringify(last?.[1]?.$orderby)).toContain('subject'); + }); + const last = ds.find.mock.calls.filter(([r]: [string]) => r === 'task').at(-1); + expect(JSON.stringify(last?.[1]?.$orderby)).toContain('desc'); }); }); + +/** The parent record page's context: the object the preference row belongs to. */ +function RecordContextHarness({ children }: { children: React.ReactNode }) { + return {children}; +} diff --git a/ui/packages/plugin-detail/src/renderers/__tests__/record-blocks.nestedLabelsI18nLabel-10993.test.tsx b/ui/packages/plugin-detail/src/renderers/__tests__/record-blocks.nestedLabelsI18nLabel-10993.test.tsx index 8dddb928f58..4fe006f8b3f 100644 --- a/ui/packages/plugin-detail/src/renderers/__tests__/record-blocks.nestedLabelsI18nLabel-10993.test.tsx +++ b/ui/packages/plugin-detail/src/renderers/__tests__/record-blocks.nestedLabelsI18nLabel-10993.test.tsx @@ -87,6 +87,8 @@ const objectSchema = { const record = { industry: 'Retail' }; const makeDataSource = () => ({ + // The picker's add is one transactional batch (objectstack#35601); a source without it offers no picker. + batchTransaction: vi.fn(async () => ({ results: [] })), find: vi.fn(async () => ({ data: [{ id: 't1', name: 'Call back' }], total: 1 })), findOne: vi.fn(async () => record), getObjectSchema: vi.fn(async (name: string) => ({ name, fields: { name: { type: 'text', label: 'Name' } } })), From 6ea1cb96bfde57d3a079690068e98d40207eff84 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 03:32:43 +0000 Subject: [PATCH 4/7] test(app-shell): pay the lint load at collection in the sourced list page pin Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZrgaiMgTJCnswR6jQ --- .../src/views/ObjectDataPage.sourceList-35601.test.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ui/packages/app-shell/src/views/ObjectDataPage.sourceList-35601.test.tsx b/ui/packages/app-shell/src/views/ObjectDataPage.sourceList-35601.test.tsx index 11ec068ff47..ce6c9f7f102 100644 --- a/ui/packages/app-shell/src/views/ObjectDataPage.sourceList-35601.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectDataPage.sourceList-35601.test.tsx @@ -25,6 +25,8 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, cleanup, fireEvent, screen } from '@testing-library/react'; import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom'; +// The page reaches `@objectstack/lint` through a dynamic import; its first load is paid at collection, not inside a case. +import '@objectstack/lint'; vi.mock('@object-ui/permissions', async (importOriginal) => { const actual = await importOriginal(); From df21125d573fe5a2d637a8ffedc869d8a722e003 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 03:47:26 +0000 Subject: [PATCH 5/7] fix(plugin-detail): one Add fallback for the related tab entry; drop unused import The related tab's single Add entry wrote the `detail.add` fallback twice (picker and New branches), tipping the residue pin from 4 to 5 sites. Hoist it once and record the new affordance in the pin's comment. Drop the unused `isPermissionError` import that failed Lint UI. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZrgaiMgTJCnswR6jQ --- .../i18n/src/__tests__/residue-namespaces-3546.test.tsx | 5 +++-- ui/packages/plugin-detail/src/RelatedList.tsx | 7 ++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/ui/packages/i18n/src/__tests__/residue-namespaces-3546.test.tsx b/ui/packages/i18n/src/__tests__/residue-namespaces-3546.test.tsx index 379ffe9cbec..083d4745476 100644 --- a/ui/packages/i18n/src/__tests__/residue-namespaces-3546.test.tsx +++ b/ui/packages/i18n/src/__tests__/residue-namespaces-3546.test.tsx @@ -389,8 +389,9 @@ describe('objectui#3546 slice seven — the ratchet residue', () => { } // PageView uses it twice on the same button (title + aria-label) and // RelatedList four times in four different affordances (the picker title, - // the compact card's icon-only + and the full list's Add button, - // objectstack#27055; the enlarged face's toolbar Add, objectstack#27524) — + // the compact card's icon-only +, objectstack#27055; the enlarged face's + // toolbar Add, objectstack#27524; the related tab's one 「+ 添加」 entry, + // whose picker and New branches share one fallback, objectstack#35601) — // the counts are pinned so a silent drop of one of them is visible. AppContent's two record-save toast // sites share one message builder since objectstack-ai/objectstack#26172, // so its fallback label is written once. diff --git a/ui/packages/plugin-detail/src/RelatedList.tsx b/ui/packages/plugin-detail/src/RelatedList.tsx index efaf47a4de8..0ba096db16f 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -31,7 +31,7 @@ import { useIsMobile, RelatedCountStore, } from '@object-ui/components'; -import { SchemaRenderer, ActionCtxReact, useCapabilityGate, useCondition, toPredicateInput, useSettledSchema, useFilterScope, useResolvedFilter, usePredicateScope, classifyLoadError, answeredLoadFailure, declaredUserMessage, isPermissionError, type LoadErrorKind, type RelatedRowActionDef } from '@object-ui/react'; +import { SchemaRenderer, ActionCtxReact, useCapabilityGate, useCondition, toPredicateInput, useSettledSchema, useFilterScope, useResolvedFilter, usePredicateScope, classifyLoadError, answeredLoadFailure, declaredUserMessage, type LoadErrorKind, type RelatedRowActionDef } from '@object-ui/react'; import { Plus, ExternalLink, @@ -2429,15 +2429,16 @@ export const RelatedList: React.FC = ({ * offered. */ const pickerOffered = !!add && !!add.picker?.object && !!dataSource && addGranted && addBatchable; + const addFallbackLabel = t('detail.add', { defaultValue: 'Add' }); const addEntry: { label: string; disabled: boolean; onClick: () => void } | null = pickerOffered ? { - label: add!.label || t('detail.add', { defaultValue: 'Add' }), + label: add!.label || addFallbackLabel, disabled: addBusy, onClick: () => { setAddError(null); setPickerOpen(true); }, } : onNew ? { - label: t('detail.add', { defaultValue: 'Add' }), + label: addFallbackLabel, disabled: !!newDisabled, onClick: () => onNew(), } From 05a187d49ba546d680678d78766a38b32daf4d68 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 04:07:59 +0000 Subject: [PATCH 6/7] fix(plugin-detail): call batchTransaction on the data source so the write census sees the add MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `batch.call(dataSource, …)` hid the related tab's atomic add from the affordance write census. Call the member directly and enter the site as one `batch` entry behind relatedNew and relatedRowEdit. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZrgaiMgTJCnswR6jQ --- ui/packages/plugin-detail/src/RelatedList.tsx | 6 +++--- .../plugin-form/src/affordanceGrantMap-12082.test.tsx | 9 +++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/ui/packages/plugin-detail/src/RelatedList.tsx b/ui/packages/plugin-detail/src/RelatedList.tsx index 0ba096db16f..7790780ef2b 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -2395,8 +2395,8 @@ export const RelatedList: React.FC = ({ const addBatchable = typeof (dataSource as DataSource | undefined)?.batchTransaction === 'function'; const handleAddRecords = React.useCallback(async (records: any[]) => { if (!add || !dataSource || !api || referenceField == null || parentId === undefined || parentId === null) return; - const batch = (dataSource as DataSource).batchTransaction; - if (typeof batch !== 'function') return; + const ds = dataSource as DataSource; + if (typeof ds.batchTransaction !== 'function') return; const vf = add.picker.valueField || 'id'; const operations: Parameters>[0] = []; for (const rec of records || []) { @@ -2411,7 +2411,7 @@ export const RelatedList: React.FC = ({ setAddBusy(true); setAddError(null); try { - await batch.call(dataSource, operations); + await ds.batchTransaction(operations); setRefreshNonce((n) => n + 1); } catch (err: any) { const raw = err?.body?.error ?? err?.error ?? err?.message ?? String(err); diff --git a/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx b/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx index db638e51c09..6affc9565ae 100644 --- a/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx +++ b/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx @@ -839,10 +839,11 @@ const WRITE_SITES: Record = { // re-parent of the picked record (without one) an update of the picked // object — the rows a related list's "+ New" and row Edit read. 'packages/plugin-detail/src/queueClaim.ts :: claimQueuedRecord :: update': helper('claimQueuedRecord'), - 'packages/plugin-detail/src/RelatedList.tsx :: RelatedList > handleAddRecords :: create': - mapped(['relatedNew'], RELATED_LIST), - 'packages/plugin-detail/src/RelatedList.tsx :: RelatedList > handleAddRecords :: update': - mapped(['relatedRowEdit'], RELATED_LIST), + // One atomic batch since objectstack#35601: a junction `linkField` adds + // by creating junction rows (relatedNew), a plain lookup by reparenting + // the picked rows (relatedRowEdit). + 'packages/plugin-detail/src/RelatedList.tsx :: RelatedList > handleAddRecords :: batch': + mapped(['relatedNew', 'relatedRowEdit'], RELATED_LIST), 'packages/plugin-detail/src/renderers/record-related-list.tsx :: RecordRelatedListBody :: delete': { ...mapped(['relatedRowDelete'], RELATED_LIST_BLOCK), note: "the FALLBACK remove (an `add` config, no host delete) reads the same row the host's delete reads, so it never puts back a delete the host withheld", From e62ce9e74e7196a74fbc96226454e0e4652f72ed Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 04:37:42 +0000 Subject: [PATCH 7/7] fix(plugin-detail): the derived lookup picker offers only unlinked children A pick re-parents the child, so a row already under this record was a no-op and a row under another parent moved silently. The derived picker on a lookup related tab now filters the relationship to empty; moving a child between parents stays on its own form. Authored pickers keep their own filter. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZrgaiMgTJCnswR6jQ --- ui/packages/plugin-detail/src/RelatedList.tsx | 8 ++++-- ...RelatedList.enlargedToolbar-27524.test.tsx | 27 +++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/ui/packages/plugin-detail/src/RelatedList.tsx b/ui/packages/plugin-detail/src/RelatedList.tsx index 7790780ef2b..3b0bad16406 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -1036,7 +1036,11 @@ function relationFieldEntries(fields: unknown): Array<[string, RelationFieldDef] * (objectstack#35601), decided by the relationship this list hangs on: * * - `lookup`: the child is a record of its own, so the picker lists the - * child object and a pick re-parents it (`add` with no `linkField`); + * child object and a pick re-parents it (`add` with no `linkField`). It + * lists only UNLINKED children (this relationship empty): a row already + * here would be a no-op pick, and a row under another parent would move + * silently. Moving a child between parents stays on the child's own + * form, where the change is visible (seat ruling on L1-a S1, #35725); * - `master_detail` with a source catalog: the picker lists the catalog and * a pick creates a row of this list naming it (`linkField`). The catalog * is the child's one other REQUIRED single-valued `lookup` (a line's @@ -1056,7 +1060,7 @@ export function derivedAddOf( const entries = relationFieldEntries(childFields); const rel = entries.find(([name]) => name === referenceField)?.[1]; if (!rel || rel.multiple === true) return undefined; - if (rel.type === 'lookup') return { picker: { object: childObject } }; + if (rel.type === 'lookup') return { picker: { object: childObject, filter: [{ field: referenceField, operator: 'is_empty' }] } }; if (rel.type !== 'master_detail') return undefined; const catalogs = entries.filter(([name, def]) => name !== referenceField diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx index 10817d7d6d5..40c474256fd 100644 --- a/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx @@ -214,6 +214,33 @@ describe('「+ 添加」 is decided by the relationship, and a pick is one trans await waitFor(() => expect(listReads(dataSource)).toBeGreaterThan(readsBefore)); }); + it('lookup: the picker offers only unlinked children, never a row here or under another parent', async () => { + const { dataSource } = renderList(); + // A server stand-in for the picker's read: it honours the emptiness rule + // on the relationship, and serves all three rows when the rule is absent. + const pool = [ + { id: 'p-here', name: 'Already here', lead: 'L-1' }, + { id: 'p-other', name: 'Under another lead', lead: 'L-2' }, + { id: 'p-free', name: 'Unlinked', lead: null }, + ]; + const listFind = dataSource.find.getMockImplementation()!; + dataSource.find.mockImplementation(async (resource: string, params?: any) => { + if (resource !== 'task' || JSON.stringify(params ?? {}).includes('L-1')) return listFind(resource, params); + const unlinkedOnly = JSON.stringify(params?.$filter ?? []).includes('["lead","is_empty"]'); + const data = unlinkedOnly ? pool.filter((r) => r.lead == null) : pool; + return { data, total: data.length }; + }); + await waitFor(() => expect(screen.getByText('Send quote')).toBeInTheDocument()); + fireEvent.click(addButton()!); + const dialog = await screen.findByTestId('record-picker-dialog'); + expect(await within(dialog).findByTestId('record-row-p-free')).toBeInTheDocument(); + expect(within(dialog).queryByTestId('record-row-p-here')).toBeNull(); + expect(within(dialog).queryByTestId('record-row-p-other')).toBeNull(); + const pickerReads = dataSource.find.mock.calls.filter(([r, p]: [string, unknown]) => r === 'task' && !JSON.stringify(p ?? {}).includes('L-1')); + expect(pickerReads.length).toBeGreaterThan(0); + expect(pickerReads.every(([, p]: [string, any]) => JSON.stringify(p?.$filter ?? []).includes('["lead","is_empty"]'))).toBe(true); + }); + it('a failing batch adds nothing and says why; no single write is sent', async () => { const { dataSource } = renderList({ batch: async () => { throw Object.assign(new Error("Field 'quantity' is required"), { status: 400 }); },