Skip to content

Commit 06faee5

Browse files
fix(plugin-list): a sourced list shows each condition once, and a lookup chip names its record (#35744)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wgRuogP8Tp8XyFXLc92Bxvo6)_ repo:objectstack#5 · os-bill · session_01Utp6CZiaBg6rk7dpy1s9Me Fixes #35727 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户看到的变化:从记录「↗」打开的列表(数据页),条件只在页面顶部的「筛选条件」标签里出现一次;列表自己的条件行不再重复一个带锁、印着原始 id 的标签,也不再多出一个灰掉的「重置」。保存视图里锁定的关联字段条件,改为显示记录名称。 - 为什么做:列表筛选重做这条线上的一项,替从关联页签跳到列表的用户去掉重复的条件和多余的「重置」。 - 出错会怎样:最坏是数据页上某个条件看不到标签,或关联记录名读不到时退回显示 id;筛选本身照常生效,撤回这个改动即可复原。 - 要你做什么:无 ## What changes - **Host-owned conditions (the seam).** `ListView` takes a new host prop, `hostDrawnConditionFields` (a list of field names). Conditions of `schema.filter` on those fields still constrain the query exactly as before; the condition row (`ConditionChipRow`, new prop `hostDrawnFields`) simply draws no locked chip for them. The data page passes its address-condition fields there, so a sourced open shows each condition once, as the page's own 「Filtered by」 tag. - Why this seam rather than a separate "host filter" channel: the view filter (`authoredFilter`) feeds the fetch, the page-reset signature, the export, the self-querying child views, the empty-state copy and Save-as-view. Moving the address conditions out of `schema.filter` would have to re-thread every one of those readers; naming which fields the host draws changes only what the chip row renders, and the query path is byte-identical. It is a host prop, never a schema key: which surface draws a condition is the page's layout, not anything an author writes. - **Lookup chips name the record.** A locked chip for a lookup condition (and the reader's own lookup filter chip, same code path) shows the referenced record's name, read the way the lookup value picker reads it: the target's records by id through the list's data source (`find(target, { $filter: { id: { $in: ids } } })`), named by the lookup's `displayField` else the target's name field (`referencedRecordTitle`). It falls back to the id only when the name cannot be read. One read per target, re-run only when the targets or ids change (keyed on content, not on array identity). - **One Reset.** The condition row's 「Reset」 is drawn only while the reader has something of their own to reset (a filter, a changed sort, a filter-bar selection, the queue toggle) — it is no longer drawn disabled. `ConditionChipRow`'s `resetDisabled` prop is gone; `ListView` passes `onReset` only when the conditions differ from the view. - **Data page:** only the props passed to `ListView` changed — one added prop, `hostDrawnConditionFields={urlFilters.map(([field]) => field)}`, plus its comment, right after `rowOpensRecord={recordServed}`. The page's tag row is untouched (it belongs to the open PR #35725 for the related tab, which adds the page's own Reset and names the tag). Read first, by risk: 1. `ui/packages/plugin-list/src/conditions/ListConditionControls.tsx` — `useLookupValueNames` (the one read the chip row now makes) and the `hostDrawnFields` filter on `viewChips`. 2. `ui/packages/plugin-list/src/ListView.tsx` — the `ConditionChipRow` call site (`onReset={conditionsDifferFromView ? handleResetConditions : undefined}`). 3. `ui/packages/app-shell/src/views/ObjectDataPage.tsx` — the one added `ListView` prop. Two-minute check: open the showcase Contacts data page with `filter[account]=` set to any account id (or an account's Contacts tab → 「↗」). Expect one 「筛选条件 · 客户」 tag at the top, no row of chips under the view bar, and the record count matching that account. Add a 阶段 filter: its chip, 「+ 添加筛选」 and one enabled 「重置」 appear. ## Tests All at merged head `eae54db249` (after merging `origin/main` at `03bce5c22a`). - List level, `ConditionChipRow` (`listConditions.test.tsx`): a host-drawn field gets no locked chip while the view's other conditions keep theirs (with a CONTROL without the prop); all-host-drawn and nothing else ⇒ the row draws nothing; a locked lookup chip reads `Account: = Globex` and the read is `find('account', { $top: 1, $filter: { id: { $in: ['a1'] } } })`; the reader's lookup chip reads `Account: Globex, Initech`; a failing read keeps the id. The Reset pin now asserts no Reset is drawn when the host passes none. - List level, real `ListView` (`ListView.harness.test.tsx`, new block `ListView.hostDrawnConditions-35727`), zh and en each: a host-drawn condition is no locked chip and no Reset and the record query still carries it; a saved view filtered on a lookup locks `Account:= Globex` / `Account: = Globex`, never the id, and draws no Reset; once the reader adds a condition, exactly one Reset (`重置` / `Reset`). `ListView.conditionRow-35549.test.tsx`: the locked-chip case now asserts no Reset rather than a disabled one. - Data-page level, real page with the real `ListView` (`ObjectDataPage.sourcedOpenOneTag-35727.test.tsx`), zh and en: `filter[account]=acc_1` draws one page tag, zero locked chips, no list Reset, and the record query still carries `acc_1`; CONTROL: no address condition ⇒ no tag and an unfiltered read. <details><summary>Run readings</summary> - Touched suites: `pnpm --dir ui exec vitest run --maxWorkers=2` over `plugin-list/src/conditions/`, `ListView.harness`, `ListView.conditionRow-35549`, `ListView.clearFiltersChips-29052`, `ListView.emptyStateClearFilters-28908` and the seven `ObjectDataPage.*` tests → `Test Files 12 passed (12)`, `Tests 246 passed (246)`, lock `VERDICT command-exit 0`. - `pnpm --filter @object-ui/plugin-list run type-check` → exit 0 (after `turbo run build --filter='@object-ui/app-shell^...'`, 68/68 tasks). - `pnpm --filter @object-ui/app-shell run type-check` → exit 0. - `pnpm --dir ui exec vitest run scripts/` → `Test Files 171 passed | 2 skipped`, `Tests 5092 passed | 2 skipped`. </details> <details><summary>Ablations (one per changed behaviour; each via scripts/ablation-replace.mjs, mutation proven on disk, restored to the HEAD blob)</summary> 1. Drop the data page's `hostDrawnConditionFields` prop → both data-page cases red (a locked chip appears); CONTROL stays green. 2. Replace the `hostDrawnFields` filter with a pass-through → 6 red (two `ConditionChipRow` cases, the four host-drawn `ListView` cases). 3. Disable the lookup-name branch of `describeConditionValue` → 4 red (two `ConditionChipRow` name cases, the zh/en saved-view lookup cases). 4. Always pass `onReset` → 3 red (the zh/en saved-view cases and the 35549 locked-chip case). The data-page no-Reset case stays green under this one by design: with every condition host-drawn and nothing of the reader's, the row draws nothing at all. </details> ## Acceptance notes - Before/after in the browser (showcase, 1280×800, zh-CN, Contacts data page with `filter[account]` = Northwind's id): - before at `origin/main` `5ecf937470`: page tags 1 (「客户 = Pf5mgR55cgCKt58S」), locked chips 1 (「客户:= Pf5mgR55cgCKt58S」), list Reset 1 (drawn, disabled), 「+ 添加筛选」 1; - after: page tags 1, locked chips 0, list Reset 0, condition row empty; 26 records either way. Adding a 阶段 filter: 「阶段:新建」, 「+ 添加筛选」, one enabled 「重置」, 24 records. A reader 客户 filter reads 「客户:Northwind」. - On `main` alone the sourced data page now shows no Reset at all (the page tag's × still clears the condition); the open PR #35725 for the related tab adds the page's single Reset and names the page tag. Whichever of the two lands second merges `main`; `overlap-check` against `main` and against that PR's branch both answer clean. - The Reset rule is general, not only on the data page: every list now draws 「Reset」 only while it has something of the reader's to reset (previously drawn disabled). The e2e scenario in `list-condition-row-35549.spec.ts` presses Reset only after adding a sort and a filter, so it is unaffected. - A `user`-type lookup with no declared `reference` still prints its id in a chip: the value picker defaults such a field to `users` inline, and this change reads only a declared `referenceTo` rather than copying that default. - The plugin-list README documents some `ListView` host props (`rowOpensRecord`, `page`); the new `hostDrawnConditionFields` is documented on the prop's own JSDoc and in the changeset, not in the README, which is outside this card's file surface. - The data-page test holds its permission and auth stand-ins as stable objects: the page keys its address conditions on `canRead`, so a fresh function per render (as the sibling tests' stand-ins return, harmless there because they stub `ListView`) re-reads the records without end. ## Verification - `node scripts/pm/dispatch-gates.mjs --commands` (tree `f64696e915`, re-derived identical at the final tree): 38 families, all run locally, all exit 0 after one fix — `check:test-source-alias` first flagged the new data-page test for reaching a dynamic `import('@objectstack/lint')`; the test now pays that load at module top, and the gate is green. `--ran` reconciliation: 38 derived, 38 run, 0 NOT-MEASURED, 0 UNRUN. The one `vitest run scripts/` run that was killed by the box's memory limit was re-run alone and passed. - `pnpm check:new-line-citations` → 0 new citations. Control-byte self-scan over the diff: no hits. `eslint` over the changed files: 0 errors. - Every family CI runs on this PR (Lint & Repo Gates, Type Check UI, Test UI, Build & E2E UI, and the rest) is read from this PR's check-runs, not re-run here. --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CZiaBg6rk7dpy1s9Me)_ <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CZiaBg6rk7dpy1s9Me --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent bae933b commit 06faee5

8 files changed

Lines changed: 544 additions & 26 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@object-ui/plugin-list': patch
3+
'@object-ui/app-shell': patch
4+
---
5+
6+
fix(list): a list opened from a record shows its condition once, by name
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
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.
12+
13+
`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.
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#35727 — the data page opened with an address condition (a
11+
* record's related tab 「↗」 lands here with `filter[account]=<id>`) draws
12+
* that condition ONCE: as its own 「Filtered by」 tag. The list under it still
13+
* filters on the condition, and draws no second, locked chip for it and no
14+
* 「Reset」 of its own while the reader has added nothing.
15+
*
16+
* The real `ListView` renders here — the defect lived where the two surfaces
17+
* meet, so a stand-in list would pin nothing.
18+
*/
19+
20+
import * as React from 'react';
21+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
22+
import { render, cleanup, screen, waitFor, within, act } from '@testing-library/react';
23+
import { MemoryRouter, Routes, Route } from 'react-router-dom';
24+
25+
// One answer object per hook, held for the file: the page keys its address
26+
// conditions on `canRead`, so a fresh function every render would rebuild the
27+
// list's schema every render and re-read the records without end — a stand-in
28+
// artefact, not the page's behaviour (the real hooks answer stable values).
29+
const permissionAnswers = vi.hoisted(() => ({
30+
permissions: {
31+
check: () => ({ allowed: true }),
32+
checkField: () => true,
33+
getFieldPermissions: () => [],
34+
getRowFilter: () => undefined,
35+
getObjectApiOperations: () => undefined,
36+
roles: [],
37+
isLoaded: false,
38+
hasCapabilities: () => true,
39+
can: () => true,
40+
cannot: () => false,
41+
},
42+
fields: { canRead: () => true, canWrite: () => true, permissions: [] },
43+
}));
44+
45+
vi.mock('@object-ui/permissions', async (importOriginal) => {
46+
const actual = await importOriginal<typeof import('@object-ui/permissions')>();
47+
return {
48+
...actual,
49+
usePermissions: () => permissionAnswers.permissions,
50+
useFieldPermissions: () => permissionAnswers.fields,
51+
};
52+
});
53+
54+
const authAnswer = vi.hoisted(() => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }));
55+
56+
vi.mock('@object-ui/auth', async (importOriginal) => ({
57+
...(await importOriginal<Record<string, unknown>>()),
58+
useAuth: () => authAnswer,
59+
useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }),
60+
createAuthenticatedFetch: () => vi.fn(),
61+
}));
62+
63+
vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null }));
64+
vi.mock('./CreateViewDialog', () => ({ CreateViewDialog: () => null }));
65+
vi.mock('./metadata-admin/useMetadata', () => ({ useMetadataClient: () => ({}) }));
66+
67+
import { I18nProvider } from '@object-ui/i18n';
68+
// The page reaches a dynamic `import('@objectstack/lint')`; its first load is
69+
// paid here, at collection, never inside a clocked test window.
70+
import '@objectstack/lint';
71+
import { ObjectDataPage } from './ObjectDataPage';
72+
import { ExpressionProvider } from '../providers/ExpressionProvider';
73+
74+
const h = React.createElement;
75+
const OBJECT_NAME = 'contact_35727';
76+
const ACCOUNT = 'account_35727';
77+
78+
const CONTACT = {
79+
name: OBJECT_NAME,
80+
label: 'Contact',
81+
managedBy: 'platform',
82+
fields: {
83+
name: { type: 'text', label: 'Name' },
84+
account: { type: 'lookup', label: 'Account', reference: ACCOUNT },
85+
},
86+
};
87+
const OBJECTS = [CONTACT, { name: ACCOUNT, label: 'Account', fields: { name: { type: 'text', label: 'Name' } } }];
88+
89+
function makeDataSource() {
90+
return {
91+
find: vi.fn(async (object: string) =>
92+
object === ACCOUNT
93+
? { data: [{ id: 'acc_1', name: 'Globex' }], total: 1 }
94+
: { data: [{ id: 'c1', name: 'Ada', account: 'acc_1' }], total: 1 },
95+
),
96+
findOne: vi.fn(async () => null),
97+
create: vi.fn(async () => ({})),
98+
update: vi.fn(async () => ({})),
99+
delete: vi.fn(async () => ({})),
100+
getObjectSchema: vi.fn(async (object: string) => structuredClone(OBJECTS.find((o) => o.name === object))),
101+
} as any;
102+
}
103+
104+
// Module constants: `I18nProvider` re-boots on a new `config` identity.
105+
const ZH = { defaultLanguage: 'zh-Hans', detectBrowserLanguage: false };
106+
const EN = { defaultLanguage: 'en', detectBrowserLanguage: false };
107+
108+
function renderAt(config: typeof ZH, search: string) {
109+
const dataSource = makeDataSource();
110+
const page = h(
111+
MemoryRouter,
112+
{ initialEntries: [`/apps/demo/${OBJECT_NAME}/data?${search}`] },
113+
h(
114+
Routes,
115+
null,
116+
h(Route, {
117+
path: '/apps/:appName/:objectName/data',
118+
element: h(ObjectDataPage, { dataSource, objects: OBJECTS }),
119+
}),
120+
),
121+
);
122+
render(
123+
h(I18nProvider, {
124+
config,
125+
children: h(ExpressionProvider, { user: { id: 'u1', name: 'Ada', profile: 'admin' }, children: page }),
126+
}),
127+
);
128+
return dataSource;
129+
}
130+
131+
const recordReads = (ds: { find: ReturnType<typeof vi.fn> }) =>
132+
ds.find.mock.calls.filter((call: unknown[]) => call[0] === OBJECT_NAME);
133+
134+
beforeEach(() => {
135+
cleanup();
136+
window.localStorage.clear();
137+
vi.stubGlobal(
138+
'fetch',
139+
vi.fn(async () => new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } })),
140+
);
141+
});
142+
143+
afterEach(() => {
144+
vi.unstubAllGlobals();
145+
vi.clearAllMocks();
146+
});
147+
148+
describe('a sourced open of the data page draws each condition once (objectstack#35727)', () => {
149+
it.each([
150+
['zh', ZH],
151+
['en', EN],
152+
])('%s: one page tag, no locked chip, no list Reset — and the records are still filtered', async (_lang, config) => {
153+
const ds = renderAt(config, 'filter[account]=acc_1');
154+
const row = await screen.findByTestId('list-condition-row');
155+
await waitFor(() => expect(recordReads(ds).length).toBeGreaterThan(0));
156+
await act(async () => {});
157+
158+
const tags = screen.getByTestId('object-data-filter-chips');
159+
expect(within(tags).getAllByTestId(/^object-data-remove-filter-/)).toHaveLength(1);
160+
expect(screen.queryAllByTestId('view-condition-chip')).toHaveLength(0);
161+
expect(within(row).queryByTestId('condition-reset')).toBeNull();
162+
expect(JSON.stringify(recordReads(ds).at(-1)![1])).toContain('acc_1');
163+
});
164+
165+
it('CONTROL: with no address condition there is no page tag and the list reads unfiltered', async () => {
166+
const ds = renderAt(EN, '');
167+
await screen.findByTestId('list-condition-row');
168+
await waitFor(() => expect(recordReads(ds).length).toBeGreaterThan(0));
169+
expect(screen.queryByTestId('object-data-filter-chips')).toBeNull();
170+
expect(JSON.stringify(recordReads(ds).at(-1)![1])).not.toContain('acc_1');
171+
});
172+
});

‎ui/packages/app-shell/src/views/ObjectDataPage.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -842,6 +842,10 @@ export function ObjectDataPage({ dataSource, objects }: any) {
842842
// objectstack#33317 — a list-only object's rows open nothing, so
843843
// the grid draws them no record link and no Open.
844844
rowOpensRecord={recordServed}
845+
// objectstack#35727 — the address conditions are this page's own
846+
// 「Filtered by」 tags; the list filters on them and draws no
847+
// second, locked chip for them.
848+
hostDrawnConditionFields={urlFilters.map(([field]) => field)}
845849
/>
846850
)}
847851
</div>

‎ui/packages/plugin-list/src/ListView.tsx‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -694,6 +694,19 @@ export interface ListViewProps {
694694
* notification. A HOST prop, never a schema key.
695695
*/
696696
onPageChange?: (page: number) => void;
697+
/**
698+
* Fields whose conditions in `schema.filter` the HOST draws itself as its
699+
* own tags (objectstack#35727) — the data page's 「Filtered by」 row for the
700+
* conditions its address carries. The list still filters on them; its
701+
* condition row draws no locked chip for them, so each condition shows
702+
* once, and 「Reset」 (which never clears the view's filter) is not offered
703+
* for them.
704+
*
705+
* A HOST prop, never a schema key: which surface draws a condition is the
706+
* page's layout, not anything an author writes. Absent ⇒ every condition of
707+
* the view's filter is a locked chip, exactly as before.
708+
*/
709+
hostDrawnConditionFields?: ReadonlyArray<string>;
697710
}
698711

699712
// Helper to convert FilterBuilder group to ObjectStack AST.
@@ -2122,6 +2135,7 @@ export const ListView = React.forwardRef<ListViewHandle, ListViewProps>(({
21222135
recordOpen,
21232136
page,
21242137
onPageChange,
2138+
hostDrawnConditionFields,
21252139
...props
21262140
}: ListViewProps & { [key: string]: any }, ref) => {
21272141
// The switcher can be enabled either by the host component (prop) or by
@@ -7847,7 +7861,10 @@ export const ListView = React.forwardRef<ListViewHandle, ListViewProps>(({
78477861
{/* objectstack#35549 / #35550: sort chips, the view's own
78487862
conditions as locked chips, the reader's filter chips, then
78497863
「Add filter」 and 「Reset」. It draws nothing while there is
7850-
nothing to show, so the slot stays empty and takes no height. */}
7864+
nothing to show, so the slot stays empty and takes no height.
7865+
objectstack#35727: a condition the host draws as its own tag is
7866+
no locked chip here, and 「Reset」 is drawn only while the
7867+
reader has something of their own to reset. */}
78517868
<ConditionChipRow
78527869
sort={currentSort}
78537870
sortFields={sortFields}
@@ -7856,10 +7873,11 @@ export const ListView = React.forwardRef<ListViewHandle, ListViewProps>(({
78567873
filterFields={filterFields}
78577874
onFiltersChange={applyPanelFilters}
78587875
viewFilter={authoredFilter}
7876+
hostDrawnFields={hostDrawnConditionFields}
7877+
dataSource={dataSource}
78597878
shownFields={shownFieldNames}
78607879
renderAdvanced={advancedFilterBuilder}
7861-
onReset={handleResetConditions}
7862-
resetDisabled={!conditionsDifferFromView}
7880+
onReset={conditionsDifferFromView ? handleResetConditions : undefined}
78637881
/>
78647882
</div>
78657883
)}

‎ui/packages/plugin-list/src/__tests__/ListView.conditionRow-35549.test.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,13 +107,13 @@ describe('ListView condition row and panels (objectstack#35549, objectstack#3555
107107
await waitFor(() => expect(onSortChange.mock.calls.at(-1)![0]).toEqual([]));
108108
});
109109

110-
it("the view's own filter is a locked chip, and Reset is disabled while the list matches the view", async () => {
110+
it("the view's own filter is a locked chip, and no Reset is drawn while the list matches the view (objectstack#35727)", async () => {
111111
const ds = mount({ filter: [['stage', '=', 'proposal']] });
112112
await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalled());
113113
const locked = await within(slot()).findByTestId('view-condition-chip');
114114
expect(locked).toHaveAttribute('data-locked', 'true');
115115
expect(within(locked).queryByRole('button')).toBeNull();
116-
expect(within(slot()).getByTestId('condition-reset')).toBeDisabled();
116+
expect(within(slot()).queryByTestId('condition-reset')).toBeNull();
117117
});
118118

119119
it('Reset clears the reader\'s filter and returns the sort to the view as saved', async () => {

‎ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,111 @@ function restoreAfterBlock() {
109109
});
110110
}
111111

112+
// ── ListView.hostDrawnConditions-35727 ──────────────────────────────────────────
113+
114+
/**
115+
* objectstack#35727 — a list opened from a record's 「↗」 showed its one
116+
* condition twice: the data page's 「Filtered by」 tag, and under the view bar
117+
* a locked chip printing the lookup's raw id beside a second 「Reset」.
118+
*
119+
* The host now names the fields it draws itself (`hostDrawnConditionFields`):
120+
* the list still filters on them and draws no locked chip for them. A locked
121+
* chip the list does draw for a lookup (a saved view filtered on one) names
122+
* the record, read through the list's data source. 「Reset」 is drawn only
123+
* while the reader has something of their own to reset.
124+
*/
125+
describe('ListView.hostDrawnConditions-35727', () => {
126+
restoreAfterBlock();
127+
128+
const ZH = { defaultLanguage: 'zh', detectBrowserLanguage: false };
129+
const EN = { defaultLanguage: 'en', detectBrowserLanguage: false };
130+
const OBJECT = 'contact_35727';
131+
const DEFINITION = {
132+
name: OBJECT,
133+
label: 'Contact',
134+
fields: {
135+
name: { type: 'text', label: 'Name' },
136+
account: { type: 'lookup', label: 'Account', reference: 'account_35727' },
137+
},
138+
};
139+
const ACCOUNT_DEFINITION = { name: 'account_35727', label: 'Account', fields: { name: { type: 'text', label: 'Name' } } };
140+
141+
function mount(config: typeof ZH, props: Partial<React.ComponentProps<typeof ListView>> = {}) {
142+
const ds = {
143+
find: vi.fn(async (object: string) =>
144+
object === 'account_35727'
145+
? { data: [{ id: 'acc_1', name: 'Globex' }], total: 1 }
146+
: { data: [{ id: 'c1', name: 'Ada', account: 'acc_1' }], total: 1 },
147+
),
148+
findOne: vi.fn(),
149+
create: vi.fn(),
150+
update: vi.fn(),
151+
delete: vi.fn(),
152+
getObjectSchema: vi.fn(async (object: string) =>
153+
structuredClone(object === 'account_35727' ? ACCOUNT_DEFINITION : DEFINITION),
154+
),
155+
};
156+
const schema = {
157+
type: 'list-view',
158+
objectName: OBJECT,
159+
viewType: 'grid',
160+
columns: [{ field: 'name' }, { field: 'account' }],
161+
filter: [['account', '=', 'acc_1']],
162+
} as unknown as ListViewSchema;
163+
render(
164+
<I18nProvider config={config}>
165+
<SchemaRendererProvider dataSource={ds as any}>
166+
<ListView schema={schema} dataSource={ds as any} {...props} />
167+
</SchemaRendererProvider>
168+
</I18nProvider>,
169+
);
170+
return ds;
171+
}
172+
173+
const slot = () => screen.getByTestId('list-condition-row');
174+
const recordReads = (ds: { find: ReturnType<typeof vi.fn> }) => ds.find.mock.calls.filter(([object]) => object === OBJECT);
175+
176+
beforeEach(() => window.localStorage.clear());
177+
178+
it.each([
179+
['zh', ZH],
180+
['en', EN],
181+
])('%s: a condition the host draws is no locked chip and no Reset, and still filters the records', async (_lang, config) => {
182+
const ds = mount(config, { hostDrawnConditionFields: ['account'] });
183+
await waitFor(() => expect(recordReads(ds).length).toBeGreaterThan(0));
184+
await act(async () => {});
185+
expect(JSON.stringify(recordReads(ds).at(-1)![1])).toContain('acc_1');
186+
expect(within(slot()).queryByTestId('view-condition-chip')).toBeNull();
187+
expect(within(slot()).queryByTestId('condition-reset')).toBeNull();
188+
expect(slot()).toBeEmptyDOMElement();
189+
});
190+
191+
it.each([
192+
['zh', ZH, ':', 'Account:= Globex'],
193+
['en', EN, ': ', 'Account: = Globex'],
194+
])('%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) => {
195+
mount(config);
196+
const chip = await within(slot()).findByTestId('view-condition-chip');
197+
await waitFor(() => expect(chip.textContent).toBe(text));
198+
expect(chip.textContent).not.toContain('acc_1');
199+
expect(within(slot()).queryByTestId('condition-reset')).toBeNull();
200+
});
201+
202+
it.each([
203+
['zh', ZH, '重置'],
204+
['en', EN, 'Reset'],
205+
])('%s: once the reader adds a condition of their own, one Reset is drawn', async (_lang, config, label) => {
206+
mount(config, {
207+
hostDrawnConditionFields: ['account'],
208+
initialFilters: { id: 'root', logic: 'and', conditions: [{ id: 'c1', field: 'name', operator: 'contains', value: 'A' }] },
209+
});
210+
const reset = await within(slot()).findByTestId('condition-reset');
211+
expect(reset).toHaveTextContent(label);
212+
expect(within(slot()).getAllByTestId('condition-reset')).toHaveLength(1);
213+
expect(within(slot()).queryByTestId('view-condition-chip')).toBeNull();
214+
});
215+
});
216+
112217
// ── ListView.concurrencyTokenProjection-12292 ───────────────────────────────────
113218

114219
/**

0 commit comments

Comments
 (0)