Skip to content

Commit d2d160c

Browse files
committed
test(ui): pin the read-only package view gate and the adapter's served package (#35933)
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L6bhgW85kwjGaz7HqsmEuv
1 parent 806b530 commit d2d160c

2 files changed

Lines changed: 328 additions & 0 deletions

File tree

Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#35933 — a view a read-only package ships offers an admin no save
5+
* of its own: no footer calculation menu (objectstack#35702) and no Rename in
6+
* the list's options menu. A shared view the console saved into the
7+
* customization package, and the reader's own view, still offer the menu.
8+
*
9+
* A dotted view name cannot tell the two apart: every stored view is named
10+
* `object.key`, the console's own saved views included. What tells them apart
11+
* is the package the row was served under (`listViews()` carries the item's
12+
* `_packageId`) and the server's `writable` verdict for that package, read from
13+
* the session-held package list the Studio entries read (`fetchSessionPackages`).
14+
* While that verdict is unknown the menu stays offered, as it was before: the
15+
* server refuses the save and the pick is taken back.
16+
*
17+
* What runs: the real `ObjectView` on a stub data source. `ListView` is
18+
* replaced by a stand-in that records the props it is handed, so the menu's
19+
* presence is read as the `onColumnSummaryPick` the list receives (the grid
20+
* draws the menu exactly when it has one, pinned in plugin-grid's
21+
* `footerCalculationPicker-35702` tests). The package list is stubbed at
22+
* `fetchSessionPackages`.
23+
*/
24+
25+
import * as React from 'react';
26+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
27+
import { render, cleanup, act, waitFor } from '@testing-library/react';
28+
import { MemoryRouter, Routes, Route } from 'react-router-dom';
29+
// `ObjectView` reaches a dynamic `import('@objectstack/lint')`: pay its load at
30+
// collection, never inside a case's clocked window (`check:test-source-alias`).
31+
import '@objectstack/lint';
32+
33+
vi.mock('@object-ui/permissions', async (importOriginal) => {
34+
const actual = await importOriginal<typeof import('@object-ui/permissions')>();
35+
// Stable identities: `ListView` names `perms` in its fetch dependencies.
36+
const perms = {
37+
check: () => ({ allowed: true }),
38+
checkField: () => true,
39+
getFieldPermissions: () => [],
40+
getRowFilter: () => undefined,
41+
getObjectApiOperations: () => undefined,
42+
roles: [],
43+
isLoaded: false,
44+
hasCapabilities: () => true,
45+
can: () => true,
46+
cannot: () => false,
47+
};
48+
const fieldPerms = { canRead: () => true, canWrite: () => true, permissions: [] };
49+
return { ...actual, usePermissions: () => perms, useFieldPermissions: () => fieldPerms };
50+
});
51+
52+
vi.mock('@object-ui/auth', async (importOriginal) => ({
53+
...(await importOriginal<Record<string, unknown>>()),
54+
useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: { id: 'org1', name: 'Acme' } }),
55+
// The shared view's saves are an administrator's.
56+
useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }),
57+
createAuthenticatedFetch: () => vi.fn(),
58+
}));
59+
60+
vi.mock('@object-ui/collaboration', async (importOriginal) => ({
61+
...(await importOriginal<Record<string, unknown>>()),
62+
useRealtimeSubscription: () => ({ lastMessage: null }),
63+
useConflictResolution: () => ({ hasConflicts: false, resolveAllConflicts: () => {} }),
64+
}));
65+
66+
vi.mock('sonner', () => ({
67+
toast: Object.assign(vi.fn(), {
68+
success: vi.fn(), error: vi.fn(), info: vi.fn(),
69+
warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(),
70+
}),
71+
}));
72+
73+
vi.mock('./MetadataInspector', () => ({
74+
MetadataPanel: () => null,
75+
useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }),
76+
}));
77+
vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null }));
78+
79+
/** The props the list was last handed. */
80+
const listProps = vi.hoisted(() => ({ current: null as Record<string, any> | null }));
81+
vi.mock('@object-ui/plugin-list', async (importOriginal) => ({
82+
...(await importOriginal<typeof import('@object-ui/plugin-list')>()),
83+
ListView: (props: any) => {
84+
listProps.current = props;
85+
return null;
86+
},
87+
}));
88+
89+
/** The session-held package list, as `GET /api/v1/packages` answers it (parsed). */
90+
const packageList = vi.hoisted(() => ({ answer: (): Promise<any[]> => Promise.resolve([]) }));
91+
vi.mock('./studio-design/packages-io', async (importOriginal) => ({
92+
...(await importOriginal<Record<string, unknown>>()),
93+
fetchSessionPackages: vi.fn(() => packageList.answer()),
94+
}));
95+
96+
import { ObjectView } from './ObjectView';
97+
import { ExpressionProvider } from '../providers/ExpressionProvider';
98+
99+
const OBJECT = 'showcase_task';
100+
const SHIPPED_PACKAGE = 'com.example.showcase';
101+
const CUSTOM_PACKAGE = 'com.example.showcase.custom';
102+
103+
/** A view the read-only code package ships, as `listViews()` serves it. */
104+
const SHIPPED = {
105+
name: `${OBJECT}.in_progress`, object: OBJECT, label: 'In progress', type: 'grid',
106+
columns: ['name', 'amount'], _packageId: SHIPPED_PACKAGE,
107+
};
108+
/** A shared view the console saved: dotted the same way, in the customization package. */
109+
const CUSTOM = {
110+
name: `${OBJECT}.team_tasks`, object: OBJECT, label: 'Team tasks', type: 'grid',
111+
columns: ['name', 'amount'], _packageId: CUSTOM_PACKAGE,
112+
};
113+
/** A stored view bound to no package. */
114+
const UNBOUND = { name: `${OBJECT}.unbound`, object: OBJECT, label: 'Unbound', type: 'grid', columns: ['name', 'amount'] };
115+
/** The reader's own view (`sys_personal_view`). */
116+
const PERSONAL = {
117+
id: 'pv_mine', user_id: 'u1', object_name: OBJECT, label: 'My tasks',
118+
config: { type: 'grid', columns: ['name', 'amount'], data: { provider: 'object', object: OBJECT } },
119+
};
120+
121+
/** The packages row for each id: the server's `writable` verdict. */
122+
const PACKAGES = [
123+
{ id: SHIPPED_PACKAGE, name: 'Showcase', writable: false, namespace: 'showcase' },
124+
{ id: CUSTOM_PACKAGE, name: 'Showcase (custom)', writable: true, namespace: 'showcase' },
125+
];
126+
127+
function mount(viewId: string) {
128+
const dataSource = {
129+
find: vi.fn(async (resource: string) =>
130+
resource === 'sys_personal_view' ? { data: [PERSONAL], total: 1 } : { data: [], total: 0 }),
131+
findOne: vi.fn(async () => null),
132+
create: vi.fn(async () => ({})),
133+
update: vi.fn(async () => ({})),
134+
delete: vi.fn(async () => ({})),
135+
getObjectSchema: vi.fn(async () => ({ name: OBJECT, fields: {} })),
136+
listViews: vi.fn(async () => [SHIPPED, CUSTOM, UNBOUND]),
137+
updateView: vi.fn(async () => ({})),
138+
};
139+
render(
140+
<ExpressionProvider user={{ id: 'u1', name: 'Ada', profile: 'admin' }}>
141+
<MemoryRouter initialEntries={[`/apps/demo/${OBJECT}/view/${encodeURIComponent(viewId)}`]}>
142+
<Routes>
143+
<Route
144+
path="/apps/:appName/:objectName/view/:viewId"
145+
element={
146+
<ObjectView
147+
dataSource={dataSource as never}
148+
objects={[{
149+
name: OBJECT,
150+
label: 'Task',
151+
fields: { name: { type: 'text', label: 'Name' }, amount: { type: 'number', label: 'Amount' } },
152+
}]}
153+
onEdit={() => {}}
154+
/>
155+
}
156+
/>
157+
</Routes>
158+
</MemoryRouter>
159+
</ExpressionProvider>,
160+
);
161+
}
162+
163+
const settle = () => act(() => new Promise<void>((resolve) => setTimeout(resolve, 300)));
164+
165+
/** Whether the list is handed the footer's calculation pick. */
166+
const offersMenu = () => typeof listProps.current?.onColumnSummaryPick === 'function';
167+
168+
beforeEach(() => {
169+
listProps.current = null;
170+
packageList.answer = () => Promise.resolve(PACKAGES);
171+
localStorage.clear();
172+
});
173+
174+
afterEach(() => {
175+
cleanup();
176+
});
177+
178+
describe('objectstack#35933 — a read-only package\'s view offers no save of its own', () => {
179+
it('a view a read-only package ships: no calculation menu, no Rename', async () => {
180+
mount(SHIPPED.name);
181+
await settle();
182+
await waitFor(() => expect(listProps.current).not.toBeNull());
183+
expect(offersMenu()).toBe(false);
184+
expect(listProps.current?.onRenameView).toBeUndefined();
185+
});
186+
187+
it('a shared view saved into the customization package keeps the menu and Rename', async () => {
188+
mount(CUSTOM.name);
189+
await settle();
190+
await waitFor(() => expect(offersMenu()).toBe(true));
191+
expect(listProps.current?.columnSummaryPickFields).toEqual(['name', 'amount']);
192+
expect(typeof listProps.current?.onRenameView).toBe('function');
193+
});
194+
195+
it('a stored view bound to no package keeps the menu', async () => {
196+
mount(UNBOUND.name);
197+
await settle();
198+
await waitFor(() => expect(offersMenu()).toBe(true));
199+
});
200+
201+
it('the reader\'s own view keeps the menu', async () => {
202+
mount(PERSONAL.id);
203+
await settle();
204+
await waitFor(() => expect(offersMenu()).toBe(true));
205+
});
206+
207+
it('while the package list is unread, the shipped view keeps the menu (the server still refuses)', async () => {
208+
packageList.answer = () => new Promise<any[]>(() => {});
209+
mount(SHIPPED.name);
210+
await settle();
211+
await waitFor(() => expect(offersMenu()).toBe(true));
212+
});
213+
214+
it('a failed package-list read keeps the menu', async () => {
215+
packageList.answer = () => Promise.reject(new Error('offline'));
216+
mount(SHIPPED.name);
217+
await settle();
218+
await waitFor(() => expect(offersMenu()).toBe(true));
219+
});
220+
});
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
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#35933 — `listViews()` carries the package the server served each
11+
* row under (the item's `_packageId`) on both of its arms.
12+
*
13+
* A dotted view name does not say whether a view is read-only: the console's
14+
* own saved shared views are named `object.key` too, stored in the custom
15+
* package. The served package does, and the console reads it to offer a view's
16+
* own saves (the footer's calculation menu, Rename) only where the server would
17+
* take them. The `config`-flattening arm used to rebuild the row from `config`
18+
* and drop it.
19+
*/
20+
21+
import { describe, it, expect, vi } from 'vitest';
22+
import { ObjectStackAdapter } from './index';
23+
import { answerObjectViewRead } from './objectViewRoute.test-support';
24+
25+
const OBJECT = 'showcase_task';
26+
27+
/** A view a code package ships, in the canonical ViewItem shape (body under `config`). */
28+
const SHIPPED = {
29+
name: `${OBJECT}.in_progress`,
30+
object: OBJECT,
31+
viewKind: 'list',
32+
label: 'In progress',
33+
config: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } },
34+
_packageId: 'com.example.showcase',
35+
};
36+
37+
/** A shared view the console saved into the customization package. */
38+
const CUSTOM = {
39+
name: `${OBJECT}.team_tasks`,
40+
object: OBJECT,
41+
viewKind: 'list',
42+
label: 'Team tasks',
43+
config: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } },
44+
_packageId: 'com.example.showcase.custom',
45+
};
46+
47+
/** A bare spec row (no `config`), the legacy shape the second arm keeps as it is. */
48+
const BARE = {
49+
name: `${OBJECT}.legacy`,
50+
object: OBJECT,
51+
viewKind: 'list',
52+
label: 'Legacy',
53+
type: 'grid',
54+
columns: ['name'],
55+
data: { provider: 'object', object: OBJECT },
56+
_packageId: 'com.example.showcase',
57+
};
58+
59+
/** A row bound to no package: served with no `_packageId`. */
60+
const UNBOUND = {
61+
name: `${OBJECT}.unbound`,
62+
object: OBJECT,
63+
viewKind: 'list',
64+
label: 'Unbound',
65+
config: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } },
66+
};
67+
68+
function makeDS(seed: any[]) {
69+
const meta = {
70+
getItems: vi.fn(async (type: string) => ({ type, items: seed.map((r) => structuredClone(r)) })),
71+
};
72+
const json = (body: unknown, status = 200) =>
73+
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
74+
const ds: any = new ObjectStackAdapter({
75+
baseUrl: 'http://test.local',
76+
fetch: vi.fn(async (input: RequestInfo | URL) =>
77+
(await answerObjectViewRead(input, () => ds.client.meta.getItems('view')))
78+
?? json({ success: true, data: { capabilities: {}, routes: {} } })),
79+
});
80+
ds.connected = true;
81+
ds.connectionState = 'connected';
82+
ds.client = { meta, getLocale: () => undefined };
83+
return ds;
84+
}
85+
86+
describe('listViews carries the served package on every row (objectstack#35933)', () => {
87+
it('a flattened ViewItem row keeps its `_packageId`, shipped or custom', async () => {
88+
const rows = await makeDS([SHIPPED, CUSTOM]).listViews(OBJECT);
89+
const byName = new Map(rows.map((r: any) => [r.name, r]));
90+
expect(byName.get(SHIPPED.name)?._packageId).toBe('com.example.showcase');
91+
expect(byName.get(CUSTOM.name)?._packageId).toBe('com.example.showcase.custom');
92+
// Still the flattened shape the switcher reads.
93+
expect(byName.get(SHIPPED.name)?.type).toBe('grid');
94+
expect(byName.get(SHIPPED.name)?.config).toBeUndefined();
95+
});
96+
97+
it('a bare spec row keeps its `_packageId`', async () => {
98+
const [row] = await makeDS([BARE]).listViews(OBJECT);
99+
expect(row?.name).toBe(BARE.name);
100+
expect(row?._packageId).toBe('com.example.showcase');
101+
});
102+
103+
it('a row served with no package gains none', async () => {
104+
const [row] = await makeDS([UNBOUND]).listViews(OBJECT);
105+
expect(row?.name).toBe(UNBOUND.name);
106+
expect('_packageId' in (row ?? {})).toBe(false);
107+
});
108+
});

0 commit comments

Comments
 (0)