diff --git a/.changeset/35727-sourced-list-one-condition-tag.md b/.changeset/35727-sourced-list-one-condition-tag.md new file mode 100644 index 00000000000..ef6852ff820 --- /dev/null +++ b/.changeset/35727-sourced-list-one-condition-tag.md @@ -0,0 +1,13 @@ +--- +'@object-ui/plugin-list': patch +'@object-ui/app-shell': patch +--- + +fix(list): a list opened from a record shows its condition once, by name + +Clause-②: no +Metadata-protocol: none + +A list opened from a record's related tab (「↗」) now shows its condition once, as the data page's own 「Filtered by」 tag: the list under it still filters on the condition but no longer repeats it as a locked chip printing the record's raw id beside a second 「Reset」. Where a list does lock a lookup condition (a saved view filtered on a lookup), the chip names the record it points at — and so does the reader's own lookup filter chip — keeping the id only when the name cannot be read. The condition row's 「Reset」 is drawn only while the reader has something of their own to reset (a filter they added, a sort they changed); it is no longer drawn disabled. + +`ListView` takes a host prop, `hostDrawnConditionFields`: the fields whose conditions in `schema.filter` the host draws as its own tags. The list keeps filtering on them and draws no locked chip for them. It is not a schema key. diff --git a/ui/packages/app-shell/src/views/ObjectDataPage.sourcedOpenOneTag-35727.test.tsx b/ui/packages/app-shell/src/views/ObjectDataPage.sourcedOpenOneTag-35727.test.tsx new file mode 100644 index 00000000000..2f95731f8c1 --- /dev/null +++ b/ui/packages/app-shell/src/views/ObjectDataPage.sourcedOpenOneTag-35727.test.tsx @@ -0,0 +1,172 @@ +/** + * 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#35727 — the data page opened with an address condition (a + * record's related tab 「↗」 lands here with `filter[account]=`) draws + * that condition ONCE: as its own 「Filtered by」 tag. The list under it still + * filters on the condition, and draws no second, locked chip for it and no + * 「Reset」 of its own while the reader has added nothing. + * + * The real `ListView` renders here — the defect lived where the two surfaces + * meet, so a stand-in list would pin nothing. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, cleanup, screen, waitFor, within, act } from '@testing-library/react'; +import { MemoryRouter, Routes, Route } from 'react-router-dom'; + +// One answer object per hook, held for the file: the page keys its address +// conditions on `canRead`, so a fresh function every render would rebuild the +// list's schema every render and re-read the records without end — a stand-in +// artefact, not the page's behaviour (the real hooks answer stable values). +const permissionAnswers = vi.hoisted(() => ({ + permissions: { + check: () => ({ allowed: true }), + checkField: () => true, + getFieldPermissions: () => [], + getRowFilter: () => undefined, + getObjectApiOperations: () => undefined, + roles: [], + isLoaded: false, + hasCapabilities: () => true, + can: () => true, + cannot: () => false, + }, + fields: { canRead: () => true, canWrite: () => true, permissions: [] }, +})); + +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + usePermissions: () => permissionAnswers.permissions, + useFieldPermissions: () => permissionAnswers.fields, + }; +}); + +const authAnswer = vi.hoisted(() => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null })); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => authAnswer, + useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }), + createAuthenticatedFetch: () => vi.fn(), +})); + +vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null })); +vi.mock('./CreateViewDialog', () => ({ CreateViewDialog: () => null })); +vi.mock('./metadata-admin/useMetadata', () => ({ useMetadataClient: () => ({}) })); + +import { I18nProvider } from '@object-ui/i18n'; +// The page reaches a dynamic `import('@objectstack/lint')`; its first load is +// paid here, at collection, never inside a clocked test window. +import '@objectstack/lint'; +import { ObjectDataPage } from './ObjectDataPage'; +import { ExpressionProvider } from '../providers/ExpressionProvider'; + +const h = React.createElement; +const OBJECT_NAME = 'contact_35727'; +const ACCOUNT = 'account_35727'; + +const CONTACT = { + name: OBJECT_NAME, + label: 'Contact', + managedBy: 'platform', + fields: { + name: { type: 'text', label: 'Name' }, + account: { type: 'lookup', label: 'Account', reference: ACCOUNT }, + }, +}; +const OBJECTS = [CONTACT, { name: ACCOUNT, label: 'Account', fields: { name: { type: 'text', label: 'Name' } } }]; + +function makeDataSource() { + return { + find: vi.fn(async (object: string) => + object === ACCOUNT + ? { data: [{ id: 'acc_1', name: 'Globex' }], total: 1 } + : { data: [{ id: 'c1', name: 'Ada', account: 'acc_1' }], total: 1 }, + ), + findOne: vi.fn(async () => null), + create: vi.fn(async () => ({})), + update: vi.fn(async () => ({})), + delete: vi.fn(async () => ({})), + getObjectSchema: vi.fn(async (object: string) => structuredClone(OBJECTS.find((o) => o.name === object))), + } as any; +} + +// Module constants: `I18nProvider` re-boots on a new `config` identity. +const ZH = { defaultLanguage: 'zh-Hans', detectBrowserLanguage: false }; +const EN = { defaultLanguage: 'en', detectBrowserLanguage: false }; + +function renderAt(config: typeof ZH, search: string) { + const dataSource = makeDataSource(); + const page = h( + MemoryRouter, + { initialEntries: [`/apps/demo/${OBJECT_NAME}/data?${search}`] }, + h( + Routes, + null, + h(Route, { + path: '/apps/:appName/:objectName/data', + element: h(ObjectDataPage, { dataSource, objects: OBJECTS }), + }), + ), + ); + render( + h(I18nProvider, { + config, + children: h(ExpressionProvider, { user: { id: 'u1', name: 'Ada', profile: 'admin' }, children: page }), + }), + ); + return dataSource; +} + +const recordReads = (ds: { find: ReturnType }) => + ds.find.mock.calls.filter((call: unknown[]) => call[0] === OBJECT_NAME); + +beforeEach(() => { + cleanup(); + window.localStorage.clear(); + 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 sourced open of the data page draws each condition once (objectstack#35727)', () => { + it.each([ + ['zh', ZH], + ['en', EN], + ])('%s: one page tag, no locked chip, no list Reset — and the records are still filtered', async (_lang, config) => { + const ds = renderAt(config, 'filter[account]=acc_1'); + const row = await screen.findByTestId('list-condition-row'); + await waitFor(() => expect(recordReads(ds).length).toBeGreaterThan(0)); + await act(async () => {}); + + const tags = screen.getByTestId('object-data-filter-chips'); + expect(within(tags).getAllByTestId(/^object-data-remove-filter-/)).toHaveLength(1); + expect(screen.queryAllByTestId('view-condition-chip')).toHaveLength(0); + expect(within(row).queryByTestId('condition-reset')).toBeNull(); + expect(JSON.stringify(recordReads(ds).at(-1)![1])).toContain('acc_1'); + }); + + it('CONTROL: with no address condition there is no page tag and the list reads unfiltered', async () => { + const ds = renderAt(EN, ''); + await screen.findByTestId('list-condition-row'); + await waitFor(() => expect(recordReads(ds).length).toBeGreaterThan(0)); + expect(screen.queryByTestId('object-data-filter-chips')).toBeNull(); + expect(JSON.stringify(recordReads(ds).at(-1)![1])).not.toContain('acc_1'); + }); +}); diff --git a/ui/packages/app-shell/src/views/ObjectDataPage.tsx b/ui/packages/app-shell/src/views/ObjectDataPage.tsx index 6de134d676f..1734bed6b25 100644 --- a/ui/packages/app-shell/src/views/ObjectDataPage.tsx +++ b/ui/packages/app-shell/src/views/ObjectDataPage.tsx @@ -728,6 +728,10 @@ export function ObjectDataPage({ dataSource, objects }: any) { // objectstack#33317 — a list-only object's rows open nothing, so // the grid draws them no record link and no Open. rowOpensRecord={recordServed} + // objectstack#35727 — the address conditions are this page's own + // 「Filtered by」 tags; the list filters on them and draws no + // second, locked chip for them. + hostDrawnConditionFields={urlFilters.map(([field]) => field)} /> )} diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 7a435158c6e..e3e76924750 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -694,6 +694,19 @@ export interface ListViewProps { * notification. A HOST prop, never a schema key. */ onPageChange?: (page: number) => void; + /** + * Fields whose conditions in `schema.filter` the HOST draws itself as its + * own tags (objectstack#35727) — the data page's 「Filtered by」 row for the + * conditions its address carries. The list still filters on them; its + * condition row draws no locked chip for them, so each condition shows + * once, and 「Reset」 (which never clears the view's filter) is not offered + * for them. + * + * A HOST prop, never a schema key: which surface draws a condition is the + * page's layout, not anything an author writes. Absent ⇒ every condition of + * the view's filter is a locked chip, exactly as before. + */ + hostDrawnConditionFields?: ReadonlyArray; } // Helper to convert FilterBuilder group to ObjectStack AST. @@ -2122,6 +2135,7 @@ export const ListView = React.forwardRef(({ recordOpen, page, onPageChange, + hostDrawnConditionFields, ...props }: ListViewProps & { [key: string]: any }, ref) => { // The switcher can be enabled either by the host component (prop) or by @@ -7847,7 +7861,10 @@ export const ListView = React.forwardRef(({ {/* objectstack#35549 / #35550: sort chips, the view's own conditions as locked chips, the reader's filter chips, then 「Add filter」 and 「Reset」. It draws nothing while there is - nothing to show, so the slot stays empty and takes no height. */} + nothing to show, so the slot stays empty and takes no height. + objectstack#35727: a condition the host draws as its own tag is + no locked chip here, and 「Reset」 is drawn only while the + reader has something of their own to reset. */} (({ filterFields={filterFields} onFiltersChange={applyPanelFilters} viewFilter={authoredFilter} + hostDrawnFields={hostDrawnConditionFields} + dataSource={dataSource} shownFields={shownFieldNames} renderAdvanced={advancedFilterBuilder} - onReset={handleResetConditions} - resetDisabled={!conditionsDifferFromView} + onReset={conditionsDifferFromView ? handleResetConditions : undefined} /> )} diff --git a/ui/packages/plugin-list/src/__tests__/ListView.conditionRow-35549.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.conditionRow-35549.test.tsx index d9a25b3bfd4..fe2cc016833 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.conditionRow-35549.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.conditionRow-35549.test.tsx @@ -107,13 +107,13 @@ describe('ListView condition row and panels (objectstack#35549, objectstack#3555 await waitFor(() => expect(onSortChange.mock.calls.at(-1)![0]).toEqual([])); }); - it("the view's own filter is a locked chip, and Reset is disabled while the list matches the view", async () => { + it("the view's own filter is a locked chip, and no Reset is drawn while the list matches the view (objectstack#35727)", async () => { const ds = mount({ filter: [['stage', '=', 'proposal']] }); await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalled()); const locked = await within(slot()).findByTestId('view-condition-chip'); expect(locked).toHaveAttribute('data-locked', 'true'); expect(within(locked).queryByRole('button')).toBeNull(); - expect(within(slot()).getByTestId('condition-reset')).toBeDisabled(); + expect(within(slot()).queryByTestId('condition-reset')).toBeNull(); }); it('Reset clears the reader\'s filter and returns the sort to the view as saved', async () => { diff --git a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx index 78e5df7e0bd..2134998f18f 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx @@ -109,6 +109,111 @@ function restoreAfterBlock() { }); } +// ── ListView.hostDrawnConditions-35727 ────────────────────────────────────────── + +/** + * objectstack#35727 — a list opened from a record's 「↗」 showed its one + * condition twice: the data page's 「Filtered by」 tag, and under the view bar + * a locked chip printing the lookup's raw id beside a second 「Reset」. + * + * The host now names the fields it draws itself (`hostDrawnConditionFields`): + * the list still filters on them and draws no locked chip for them. A locked + * chip the list does draw for a lookup (a saved view filtered on one) names + * the record, read through the list's data source. 「Reset」 is drawn only + * while the reader has something of their own to reset. + */ +describe('ListView.hostDrawnConditions-35727', () => { + restoreAfterBlock(); + + const ZH = { defaultLanguage: 'zh', detectBrowserLanguage: false }; + const EN = { defaultLanguage: 'en', detectBrowserLanguage: false }; + const OBJECT = 'contact_35727'; + const DEFINITION = { + name: OBJECT, + label: 'Contact', + fields: { + name: { type: 'text', label: 'Name' }, + account: { type: 'lookup', label: 'Account', reference: 'account_35727' }, + }, + }; + const ACCOUNT_DEFINITION = { name: 'account_35727', label: 'Account', fields: { name: { type: 'text', label: 'Name' } } }; + + function mount(config: typeof ZH, props: Partial> = {}) { + const ds = { + find: vi.fn(async (object: string) => + object === 'account_35727' + ? { data: [{ id: 'acc_1', name: 'Globex' }], total: 1 } + : { data: [{ id: 'c1', name: 'Ada', account: 'acc_1' }], total: 1 }, + ), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn(async (object: string) => + structuredClone(object === 'account_35727' ? ACCOUNT_DEFINITION : DEFINITION), + ), + }; + const schema = { + type: 'list-view', + objectName: OBJECT, + viewType: 'grid', + columns: [{ field: 'name' }, { field: 'account' }], + filter: [['account', '=', 'acc_1']], + } as unknown as ListViewSchema; + render( + + + + + , + ); + return ds; + } + + const slot = () => screen.getByTestId('list-condition-row'); + const recordReads = (ds: { find: ReturnType }) => ds.find.mock.calls.filter(([object]) => object === OBJECT); + + beforeEach(() => window.localStorage.clear()); + + it.each([ + ['zh', ZH], + ['en', EN], + ])('%s: a condition the host draws is no locked chip and no Reset, and still filters the records', async (_lang, config) => { + const ds = mount(config, { hostDrawnConditionFields: ['account'] }); + await waitFor(() => expect(recordReads(ds).length).toBeGreaterThan(0)); + await act(async () => {}); + expect(JSON.stringify(recordReads(ds).at(-1)![1])).toContain('acc_1'); + expect(within(slot()).queryByTestId('view-condition-chip')).toBeNull(); + expect(within(slot()).queryByTestId('condition-reset')).toBeNull(); + expect(slot()).toBeEmptyDOMElement(); + }); + + it.each([ + ['zh', ZH, ':', 'Account:= Globex'], + ['en', EN, ': ', 'Account: = Globex'], + ])('%s: a saved view filtered on a lookup locks a chip that names the record, not its id, and draws no Reset', async (_lang, config, _sep, text) => { + mount(config); + const chip = await within(slot()).findByTestId('view-condition-chip'); + await waitFor(() => expect(chip.textContent).toBe(text)); + expect(chip.textContent).not.toContain('acc_1'); + expect(within(slot()).queryByTestId('condition-reset')).toBeNull(); + }); + + it.each([ + ['zh', ZH, '重置'], + ['en', EN, 'Reset'], + ])('%s: once the reader adds a condition of their own, one Reset is drawn', async (_lang, config, label) => { + mount(config, { + hostDrawnConditionFields: ['account'], + initialFilters: { id: 'root', logic: 'and', conditions: [{ id: 'c1', field: 'name', operator: 'contains', value: 'A' }] }, + }); + const reset = await within(slot()).findByTestId('condition-reset'); + expect(reset).toHaveTextContent(label); + expect(within(slot()).getAllByTestId('condition-reset')).toHaveLength(1); + expect(within(slot()).queryByTestId('view-condition-chip')).toBeNull(); + }); +}); + // ── ListView.concurrencyTokenProjection-12292 ─────────────────────────────────── /** diff --git a/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx b/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx index e6d8ae5c6f1..058c54b2b97 100644 --- a/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx +++ b/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx @@ -16,13 +16,17 @@ * - `SortPanel`: the same field list with the direction on top; one click on * a field adds a sort level (or sets that level's direction). * - `ConditionChipRow`: sort chips, then the view's own conditions as locked - * chips, then the reader's filter chips, 「+ Add filter」 and 「Reset」. It - * draws nothing at all while there is nothing to show, so the row the host - * reserves for it takes no height. + * chips (less the ones the host draws itself, `hostDrawnFields`), then the + * reader's filter chips, 「+ Add filter」 and 「Reset」 (only while the host + * has something to reset). It draws nothing at all while there is nothing + * to show, so the row the host reserves for it takes no height. * * All three are controlled: they read the host's filter group and sort array * and hand back the next one. Nothing here stores anything or changes what a - * filter row or a sort entry looks like. + * filter row or a sort entry looks like. The one read the row makes is the + * names of the records a lookup condition points at, through the host's data + * source (`useLookupValueNames`), so a chip says 「Account: Globex」, not the + * record's id. */ import * as React from 'react'; @@ -36,6 +40,8 @@ import { type FilterBuilderRowGroup, type SortItem, } from '@object-ui/components'; +import { referencedRecordTitle } from '@object-ui/core'; +import type { DataSource } from '@object-ui/types'; import { ArrowDown, ArrowUp, Lock, Plus, RotateCcw, SlidersHorizontal, X } from 'lucide-react'; import { FieldList, type FieldListItem } from './FieldList'; import { FilterValuePanel, isQuickRowApplied, quickDateWindowOf } from './FilterValuePanel'; @@ -71,12 +77,20 @@ function optionLabel(field: ConditionField | undefined, raw: unknown): string { return hit ? hit.label : String(raw); } -/** The value half of a chip: 「Negotiation, Proposal」, 「≥ 100」, 「Today」. */ +/** The name of the record a lookup value points at, or `undefined` while it is not read. */ +export type LookupValueName = (field: string, id: string) => string | undefined; + +/** + * The value half of a chip: 「Negotiation, Proposal」, 「≥ 100」, 「Today」. + * A lookup's value is the referenced record's name when `nameOf` has it, and + * its id only when the name cannot be read. + */ export function describeConditionValue( field: ConditionField | undefined, operator: string, value: unknown, t: Translate, + nameOf?: LookupValueName, ): string { const opLabel = quickOperatorLabel(operator, t); if (isValuelessOperator(operator)) return opLabel; @@ -93,6 +107,8 @@ export function describeConditionValue( text = list.map(String).join(' – '); } else if (family === 'option') { text = list.map((v) => optionLabel(field, v)).join(joiner); + } else if (family === 'lookup' && field && nameOf) { + text = list.map((v) => nameOf(field.value, String(v)) ?? String(v)).join(joiner); } else { text = list.map(String).join(joiner); } @@ -102,18 +118,130 @@ export function describeConditionValue( : `${opLabel} ${text}`; } -function chipText(field: ConditionField | undefined, fieldName: string | undefined, operator: string, value: unknown, t: Translate) { +function chipText( + field: ConditionField | undefined, + fieldName: string | undefined, + operator: string, + value: unknown, + t: Translate, + nameOf?: LookupValueName, +) { return t('listConditions.chips.pattern', { field: field?.label ?? fieldName ?? '', - value: describeConditionValue(field, operator, value, t), + value: describeConditionValue(field, operator, value, t, nameOf), }); } -function viewChipText(chip: ViewConditionChip, fields: ReadonlyArray, t: Translate): string { - if (chip.anyOf) return chip.anyOf.map((member) => viewChipText(member, fields, t)).join(t('listConditions.chips.or')); +function viewChipText( + chip: ViewConditionChip, + fields: ReadonlyArray, + t: Translate, + nameOf?: LookupValueName, +): string { + if (chip.anyOf) return chip.anyOf.map((member) => viewChipText(member, fields, t, nameOf)).join(t('listConditions.chips.or')); if (!chip.field || !chip.operator) return t('listConditions.chips.viewFilter'); const field = fields.find((f) => f.value === chip.field); - return chipText(field, chip.field, chip.operator, chip.value, t); + return chipText(field, chip.field, chip.operator, chip.value, t, nameOf); +} + +// --------------------------------------------------------------------------- +// Lookup names +// --------------------------------------------------------------------------- + +/** One condition as the name read sees it: a field and the value it compares. */ +interface NamedCondition { + field?: string; + operator?: string; + value?: unknown; +} + +function lookupIds(value: unknown): string[] { + const list = Array.isArray(value) ? value : [value]; + return list + .filter((v): v is string | number => (typeof v === 'string' && v !== '') || typeof v === 'number') + .map(String); +} + +/** + * The names of the records the lookup conditions on screen point at, read + * the way the lookup value picker reads them: the target's records by id + * through the host's data source, named by the lookup's `displayField`, else + * the target's own name field (`referencedRecordTitle`). One record read and + * one definition read per target, again only when the ids change. + * + * Keyed on what it reads (targets and ids), never on the identity of the + * arrays the host rebuilds every render (`ui/AGENTS.md` #10). A read that + * fails, or a record nothing names, answers `undefined`: the chip keeps the id. + */ +function useLookupValueNames( + dataSource: Pick | null | undefined, + fields: ReadonlyArray, + conditions: ReadonlyArray, +): LookupValueName { + const wanted = new Map>(); + for (const condition of conditions) { + if (!condition.field || !condition.operator || isValuelessOperator(condition.operator)) continue; + const field = fields.find((f) => f.value === condition.field); + if (!field?.referenceTo || quickFilterFamily(field) !== 'lookup') continue; + const ids = lookupIds(condition.value); + if (ids.length === 0) continue; + const held = wanted.get(field.referenceTo) ?? new Set(); + for (const id of ids) held.add(id); + wanted.set(field.referenceTo, held); + } + const readKey = JSON.stringify( + [...wanted.entries()].map(([target, ids]) => [target, [...ids].sort()] as const).sort(([a], [b]) => a.localeCompare(b)), + ); + + const [read, setRead] = React.useState<{ + key: string; + byTarget: ReadonlyMap> }>; + } | null>(null); + + React.useEffect(() => { + const targets = JSON.parse(readKey) as Array<[string, string[]]>; + if (targets.length === 0 || !dataSource || typeof dataSource.find !== 'function') return; + let cancelled = false; + void Promise.all( + targets.map(async ([target, ids]) => { + let def: unknown; + if (typeof dataSource.getObjectSchema === 'function') { + try { + def = await dataSource.getObjectSchema(target); + } catch { + def = undefined; + } + } + const records = new Map>(); + try { + const result = await dataSource.find(target, { $top: ids.length, $filter: { id: { $in: ids } } }); + for (const record of Array.isArray(result?.data) ? result.data : []) { + const id = (record as Record | null)?.id; + if (id !== undefined && id !== null) records.set(String(id), record as Record); + } + } catch { + // The chip keeps the id: the name is a courtesy, the condition still filters. + } + return [target, { def, records }] as const; + }), + ).then((answers) => { + if (!cancelled) setRead({ key: readKey, byTarget: new Map(answers) }); + }); + return () => { + cancelled = true; + }; + }, [dataSource, readKey]); + + const byTarget = read?.key === readKey ? read.byTarget : undefined; + return React.useCallback( + (fieldName, id) => { + const field = fields.find((f) => f.value === fieldName); + const answer = field?.referenceTo ? byTarget?.get(field.referenceTo) : undefined; + const record = answer?.records.get(id); + return answer && record ? referencedRecordTitle(answer.def, record, field?.displayField) : undefined; + }, + [byTarget, fields], + ); } /** The words for one sort direction on a field of `type`: time, size or the alphabet. */ @@ -335,12 +463,21 @@ export interface ConditionChipRowProps { onFiltersChange: (next: FilterBuilderRowGroup) => void; /** The view's own filter, drawn as locked chips. */ viewFilter?: unknown; + /** + * Fields whose conditions in `viewFilter` the HOST draws itself (the data + * page's 「Filtered by」 tags for its address conditions): they still filter, + * and the row draws no locked chip for them, so each condition shows once. + */ + hostDrawnFields?: ReadonlyArray; + /** Where the names of the records a lookup condition points at are read. */ + dataSource?: Pick | null; shownFields?: ReadonlyArray; renderAdvanced: () => React.ReactNode; - /** Back to the view as saved. Drawn only when passed. */ + /** + * Back to the view as saved. Drawn only when passed: the host passes it + * only while the reader has something of their own to reset. + */ onReset?: () => void; - /** The list on screen is the view's own: 「Reset」 is drawn but disabled. */ - resetDisabled?: boolean; /** Extra chips the host draws after the filter chips (its own quick filters). */ trailing?: React.ReactNode; className?: string; @@ -357,10 +494,11 @@ export function ConditionChipRow({ filterFields, onFiltersChange, viewFilter, + hostDrawnFields, + dataSource, shownFields, renderAdvanced, onReset, - resetDisabled, trailing, className, }: ConditionChipRowProps) { @@ -368,8 +506,18 @@ export function ConditionChipRow({ const [openChip, setOpenChip] = React.useState(null); const dragFrom = React.useRef(null); - const viewChips = React.useMemo(() => readViewConditions(viewFilter), [viewFilter]); + // Keyed on the names, not on the array the host may rebuild every render. + const hostDrawnKey = (hostDrawnFields ?? []).join('\u0000'); + const viewChips = React.useMemo(() => { + const hostDrawn = new Set(hostDrawnKey ? hostDrawnKey.split('\u0000') : []); + return readViewConditions(viewFilter).filter((chip) => !(chip.field && hostDrawn.has(chip.field))); + }, [viewFilter, hostDrawnKey]); const appliedRows = (filters.conditions ?? []).filter(isQuickRowApplied); + const namedConditions = [ + ...viewChips.flatMap((chip) => (chip.anyOf ? chip.anyOf : [chip])), + ...appliedRows, + ]; + const nameOf = useLookupValueNames(dataSource, filterFields, namedConditions); const independent = chipsAreIndependent(filters); const hasChips = sort.length > 0 || viewChips.length > 0 || appliedRows.length > 0 || !!trailing; if (!hasChips) return null; @@ -467,7 +615,7 @@ export function ConditionChipRow({ })} {viewChips.map((chip) => { - const text = viewChipText(chip, filterFields, t); + const text = viewChipText(chip, filterFields, t, nameOf); return ( { const field = fieldOf(filterFields, row.field); - const text = chipText(field, row.field, row.operator, row.value, t); + const text = chipText(field, row.field, row.operator, row.value, t, nameOf); return ( diff --git a/ui/packages/plugin-list/src/conditions/__tests__/listConditions.test.tsx b/ui/packages/plugin-list/src/conditions/__tests__/listConditions.test.tsx index c23743a6a6f..4ff48de8f93 100644 --- a/ui/packages/plugin-list/src/conditions/__tests__/listConditions.test.tsx +++ b/ui/packages/plugin-list/src/conditions/__tests__/listConditions.test.tsx @@ -535,13 +535,72 @@ describe('ConditionChipRow — the row under the view bar', () => { expect(moveSortItem(sort, 0, 1).map((s) => s.field)).toEqual(['amount', 'stage']); }); - it('「Reset」 calls the host, and is disabled while the list is the view’s own', () => { + it('「Reset」 calls the host, and is not drawn at all while the host passes none (objectstack#35727)', () => { const onReset = vi.fn(); const { rerender } = render(); fireEvent.click(screen.getByTestId('condition-reset')); expect(onReset).toHaveBeenCalledTimes(1); - rerender(=', 10]]} onReset={onReset} resetDisabled />); - expect((screen.getByTestId('condition-reset') as HTMLButtonElement).disabled).toBe(true); + // The list is the view's own: the host passes no `onReset`, and the row + // draws no 「Reset」, disabled or otherwise, beside the locked chip. + rerender(=', 10]]} />); + expect(screen.getByTestId('view-condition-chip')).toBeInTheDocument(); + expect(screen.queryByTestId('condition-reset')).toBeNull(); + }); + + describe('conditions the host draws itself, and lookup names (objectstack#35727)', () => { + const ACCOUNT_DEF = { name: 'account', fields: { title: { type: 'text' } }, nameField: 'title' }; + function lookupSource(answer: () => Promise<{ data: unknown[] }>) { + return { + find: vi.fn(answer), + getObjectSchema: vi.fn(async () => ACCOUNT_DEF), + }; + } + + it('a field the host draws gets no locked chip; the view\'s other conditions keep theirs', () => { + render(=', 10]]} hostDrawnFields={['account']} />); + const chips = screen.getAllByTestId('view-condition-chip'); + expect(chips.map((c) => c.getAttribute('data-field'))).toEqual(['amount']); + }); + + it('CONTROL: without `hostDrawnFields` both conditions are locked chips', () => { + render(=', 10]]} />); + expect(screen.getAllByTestId('view-condition-chip').map((c) => c.getAttribute('data-field'))).toEqual(['account', 'amount']); + }); + + it('when every view condition is the host\'s and the reader has none, the row draws nothing', () => { + render(
); + expect(screen.getByTestId('slot').childElementCount).toBe(0); + }); + + it('a locked lookup chip names the record it points at, read through the data source', async () => { + const ds = lookupSource(async () => ({ data: [{ id: 'a1', title: 'Globex' }] })); + render(); + const chip = screen.getByTestId('view-condition-chip'); + await vi.waitFor(() => expect(chip.textContent).toBe('Account: = Globex')); + expect(ds.find).toHaveBeenCalledWith('account', { $top: 1, $filter: { id: { $in: ['a1'] } } }); + expect(chip.textContent).not.toContain('a1'); + }); + + it('the reader\'s own lookup chip names the record too', async () => { + const ds = lookupSource(async () => ({ data: [{ id: 'a1', title: 'Globex' }, { id: 'a2', title: 'Initech' }] })); + const filters: FilterBuilderRowGroup = { + id: 'root', + logic: 'and', + conditions: [{ id: 'c1', field: 'account', operator: 'in', value: ['a1', 'a2'] }], + }; + render(); + await vi.waitFor(() => expect(screen.getByTestId('filter-chip-open-account').textContent).toBe('Account: Globex, Initech')); + }); + + it('falls back to the id when the name cannot be read', async () => { + const ds = lookupSource(async () => { + throw new Error('offline'); + }); + render(); + await vi.waitFor(() => expect(ds.find).toHaveBeenCalled()); + await act(async () => {}); + expect(screen.getByTestId('view-condition-chip').textContent).toBe('Account: = a1'); + }); }); it('an OR group is one chip that opens the advanced panel', () => {