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/RecordPreferencesProvider.tsx b/ui/packages/app-shell/src/context/RecordPreferencesProvider.tsx index 3b68b8f1b6b..ec936a6f871 100644 --- a/ui/packages/app-shell/src/context/RecordPreferencesProvider.tsx +++ b/ui/packages/app-shell/src/context/RecordPreferencesProvider.tsx @@ -18,7 +18,8 @@ * written on its own. * * ```json - * { "showEmptyFields": true } + * { "showEmptyFields": true, + * "relatedLists": { ".": { "sort": {…}, "columnState": {…} } } } * ``` * * The renderers read it through `@object-ui/react`'s @@ -40,6 +41,7 @@ import { RecordPagePreferencesProvider, type RecordPagePreference, type RecordPagePreferencesStore, + type RelatedListPreference, } from '@object-ui/react'; import { useRecordStateFamily } from './UserStateAdapters.js'; @@ -59,9 +61,40 @@ export function sanitizeRecordPreference(v: unknown): RecordPagePreference { const out: RecordPagePreference = {}; const show = (v as Record).showEmptyFields; if (typeof show === 'boolean') out.showEmptyFields = show; + const lists = sanitizeRelatedLists((v as Record).relatedLists); + if (lists) out.relatedLists = lists; return out; } +/** The related tab's remembered sort and column widths, per list (objectstack#35601), well formed. */ +function sanitizeRelatedLists(v: unknown): Record | undefined { + if (!v || typeof v !== 'object' || Array.isArray(v)) return undefined; + const out: Record = {}; + for (const [id, raw] of Object.entries(v as Record)) { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue; + const entry: RelatedListPreference = {}; + const sort = (raw as Record).sort as { field?: unknown; order?: unknown } | undefined; + if (sort && typeof sort.field === 'string' && sort.field !== '' && (sort.order === 'asc' || sort.order === 'desc')) { + entry.sort = { field: sort.field, order: sort.order }; + } + const columns = (raw as Record).columnState as { order?: unknown; widths?: unknown } | undefined; + if (columns && typeof columns === 'object') { + const state: NonNullable = {}; + if (Array.isArray(columns.order)) state.order = columns.order.filter((k): k is string => typeof k === 'string'); + if (columns.widths && typeof columns.widths === 'object' && !Array.isArray(columns.widths)) { + const widths: Record = {}; + for (const [k, w] of Object.entries(columns.widths as Record)) { + if (typeof w === 'number' && Number.isFinite(w) && w > 0) widths[k] = w; + } + state.widths = widths; + } + entry.columnState = state; + } + if (entry.sort || entry.columnState) out[id] = entry; + } + return Object.keys(out).length > 0 ? out : undefined; +} + export function RecordPreferencesProvider({ children }: { children: ReactNode }) { const family = useRecordStateFamily(); const [states, setStates] = useState>({}); 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..ce6c9f7f102 --- /dev/null +++ b/ui/packages/app-shell/src/views/ObjectDataPage.sourceList-35601.test.tsx @@ -0,0 +1,189 @@ +/** + * 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'; +// 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(); + 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/ObjectDataPage.tsx b/ui/packages/app-shell/src/views/ObjectDataPage.tsx index 6de134d676f..259185c3a40 100644 --- a/ui/packages/app-shell/src/views/ObjectDataPage.tsx +++ b/ui/packages/app-shell/src/views/ObjectDataPage.tsx @@ -28,7 +28,7 @@ */ import * as React from 'react'; -import { useParams, useNavigate, useSearchParams } from 'react-router-dom'; +import { Link, useParams, useNavigate, useSearchParams } from 'react-router-dom'; import { ListView } from '@object-ui/plugin-list'; import { useNavigationOverlay, useRowPredicate } from '@object-ui/react'; import { @@ -42,7 +42,7 @@ import { DropdownMenuItem, DropdownMenuTrigger, } from '@object-ui/components'; -import { Database, Lock, MoreHorizontal, Plus, Save, X } from 'lucide-react'; +import { Database, Lock, MoreHorizontal, Plus, RotateCcw, Save, X } from 'lucide-react'; import { toast } from 'sonner'; import { formatMetadataError } from '@object-ui/data-objectstack'; import { useObjectTranslation, useObjectLabel } from '@object-ui/i18n'; @@ -84,6 +84,35 @@ import { useTenancyPosture } from '../hooks/useTenancyPosture.js'; import { servedObjectLabel, servedObjectPluralLabel } from '../hooks/servedObjectLabel.js'; import type { RowCrudPredicates } from '../utils/crudAffordances.js'; import { servesRecordRead } from '../utils/recordReadServed.js'; +import { + RECORD_FORM_LINK_PARAM, + RECORD_FORM_OBJECT_PARAM, + RECORD_FORM_PARAM, + RECORD_TRAIL_PARAM, + buildRecordTrailHref, + decodeRecordTrail, + type RecordTrailEntry, +} from '../urlParams.js'; + +/** + * The relationship field of `objectDef` that points at the source record of a + * list opened from that record's related list (objectstack#35601): its one + * single-valued `lookup` / `master_detail` whose `reference` is the source's + * object. `undefined` when there is none, or more than one (the source alone + * does not say which). + */ +export function sourceRelationshipField(objectDef: any, source: RecordTrailEntry | undefined): string | undefined { + if (!source || !objectDef?.fields || typeof objectDef.fields !== 'object') return undefined; + const entries: Array<[string, any]> = Array.isArray(objectDef.fields) + ? objectDef.fields.map((f: any) => [f?.name, f]) + : Object.entries(objectDef.fields); + const hits = entries.filter(([name, def]) => + typeof name === 'string' + && (def?.type === 'lookup' || def?.type === 'master_detail') + && def?.reference === source.o + && def?.multiple !== true); + return hits.length === 1 ? hits[0][0] : undefined; +} /** Field types the auto-derived user-filter bar offers as dropdowns. */ const USER_FILTER_TYPES = new Set(['select', 'multiselect', 'radio', 'enum', 'boolean']); @@ -314,6 +343,39 @@ export function ObjectDataPage({ dataSource, objects }: any) { // (>= start, < end) collapse into a single "start → end" chip (objectstack-ai/objectstack#1752). const filterChips = React.useMemo(() => groupFilterChips(urlFilters), [urlFilters]); + /** + * objectstack#35601 — a list opened by a record's related list (「↗」) + * carries that record as its SOURCE, in the record trail (`?from=`, the last + * entry): the breadcrumb names it, the source condition's chip names the + * record instead of its id, 「Reset」 puts that condition back, and New + * creates a record linked to it. The condition itself stays an ordinary URL + * filter, removable like any other: the source only names it. + */ + const sourceTrail = React.useMemo( + () => decodeRecordTrail(searchParams.get(RECORD_TRAIL_PARAM)), + [searchParams], + ); + const source = sourceTrail.length > 0 ? sourceTrail[sourceTrail.length - 1] : undefined; + const sourceField = React.useMemo(() => sourceRelationshipField(objectDef, source), [objectDef, source]); + const sourceDef = sourceField ? (objects || []).find((o: any) => o?.name === source?.o) : undefined; + const sourceConditionOn = !!source && !!sourceField + && urlFilters.some(([field, op, value]) => field === sourceField && op === '=' && String(value) === source.i); + const sourceFilterKey = sourceField ? `filter[${sourceField}]` : undefined; + const conditionsAreSourced = sourceConditionOn + && Array.from(searchParams.keys()).every((k) => k === sourceFilterKey || !(k.startsWith('filter[') || k.startsWith('uf_'))); + const resetToSource = React.useCallback(() => { + if (!source || !sourceFilterKey) return; + setSearchParams((prev) => { + const next = new URLSearchParams(); + for (const [k, v] of prev.entries()) { + if (k.startsWith('filter[') || k.startsWith('uf_')) continue; + next.append(k, v); + } + next.set(sourceFilterKey, source.i); + return next; + }); + }, [source, sourceFilterKey, setSearchParams]); + const removeUrlFilter = React.useCallback( (field: string) => { // Clears the equality param AND both range-bound operator params for the field. @@ -588,7 +650,19 @@ export function ObjectDataPage({ dataSource, objects }: any) { const newButton = objectCanCreate && createVisible ? ( ) : 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/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/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/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 2c8f50ed9b3..3b0bad16406 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, @@ -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'; @@ -87,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'; @@ -797,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; } @@ -812,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 @@ -878,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) { @@ -967,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); @@ -1001,54 +1010,183 @@ 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`). 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 + * 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, filter: [{ field: referenceField, operator: 'is_empty' }] } }; + 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 +1207,7 @@ export const RelatedList: React.FC = ({ onRowAction, toolbarActions, onToolbarAction, - add, + add: authoredAdd, redactFields, maxColumns = 6, pageSize, @@ -1220,10 +1358,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); @@ -1238,6 +1380,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 @@ -1255,7 +1428,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 +1488,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 +2026,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 +2192,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 +2390,64 @@ 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 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 || []) { + 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 ds.batchTransaction(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 addFallbackLabel = t('detail.add', { defaultValue: 'Add' }); + const addEntry: { label: string; disabled: boolean; onClick: () => void } | null = pickerOffered + ? { + label: add!.label || addFallbackLabel, + disabled: addBusy, + onClick: () => { setAddError(null); setPickerOpen(true); }, + } + : onNew + ? { + label: addFallbackLabel, + 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 +3187,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 @@ -3047,8 +3237,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 @@ -3137,8 +3329,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), @@ -3238,7 +3433,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'); @@ -3279,8 +3474,16 @@ 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`). + 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 +3553,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 +3683,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 +3703,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 +3829,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 })} +