Skip to content
Merged
13 changes: 13 additions & 0 deletions .changeset/35727-sourced-list-one-condition-tag.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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]=<id>`) 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<typeof import('@object-ui/permissions')>();
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<Record<string, unknown>>()),
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<typeof vi.fn> }) =>
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');
});
});
4 changes: 4 additions & 0 deletions ui/packages/app-shell/src/views/ObjectDataPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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)}
/>
)}
</div>
Expand Down
24 changes: 21 additions & 3 deletions ui/packages/plugin-list/src/ListView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>;
}

// Helper to convert FilterBuilder group to ObjectStack AST.
Expand Down Expand Up @@ -2122,6 +2135,7 @@ export const ListView = React.forwardRef<ListViewHandle, ListViewProps>(({
recordOpen,
page,
onPageChange,
hostDrawnConditionFields,
...props
}: ListViewProps & { [key: string]: any }, ref) => {
// The switcher can be enabled either by the host component (prop) or by
Expand Down Expand Up @@ -7847,7 +7861,10 @@ export const ListView = React.forwardRef<ListViewHandle, ListViewProps>(({
{/* 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. */}
<ConditionChipRow
sort={currentSort}
sortFields={sortFields}
Expand All @@ -7856,10 +7873,11 @@ export const ListView = React.forwardRef<ListViewHandle, ListViewProps>(({
filterFields={filterFields}
onFiltersChange={applyPanelFilters}
viewFilter={authoredFilter}
hostDrawnFields={hostDrawnConditionFields}
dataSource={dataSource}
shownFields={shownFieldNames}
renderAdvanced={advancedFilterBuilder}
onReset={handleResetConditions}
resetDisabled={!conditionsDifferFromView}
onReset={conditionsDifferFromView ? handleResetConditions : undefined}
/>
</div>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
105 changes: 105 additions & 0 deletions ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<React.ComponentProps<typeof ListView>> = {}) {
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(
<I18nProvider config={config}>
<SchemaRendererProvider dataSource={ds as any}>
<ListView schema={schema} dataSource={ds as any} {...props} />
</SchemaRendererProvider>
</I18nProvider>,
);
return ds;
}

const slot = () => screen.getByTestId('list-condition-row');
const recordReads = (ds: { find: ReturnType<typeof vi.fn> }) => 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 ───────────────────────────────────

/**
Expand Down
Loading
Loading