Repository navigation
Expand file tree
/
Copy pathObjectView.titleViewSwitcher-27594.test.tsx
More file actions
327 lines (284 loc) · 14 KB
/
Copy pathObjectView.titleViewSwitcher-27594.test.tsx
File metadata and controls
327 lines (284 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/**
* 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#27594 — the console list page switches views from its title.
*
* The title reads 「VIEW ▾」 and opens a dropdown: a search box, the
* reader's pinned view, the views they opened lately, then every view. The
* flat view-tab row it replaced (`ViewTabBar`, in the list's toolbar row
* since objectui#12440) is not drawn on any face, the split pane's narrowed
* list included.
*
* Everything here is the real chain: the real `ObjectView`, the real plugin
* `ObjectView` calling the page's `renderListView` and the real `ListView`.
*
* WHAT IS PINNED.
* - No view-tab bar or tab row. Since objectstack#35548 the switcher leads
* the list's view bar (its `toolbarLeading` slot) at every width, reading
* the view type's icon, the view's label, the record count and a caret;
* the page bar's heading names the object alone.
* - The dropdown: a search box, the views in their declared order, search
* narrowing them, and choosing one switching the list.
* - 📌 keeps the pinned view per object (the reader's workspace preference)
* and the object's bare address opens it, also on the next mount; unpinned,
* the declared default opens again.
* - A record open beside the list (the split pane) leaves the same one
* switcher.
* - On a phone (objectstack#27058) the page header is not drawn, and the
* same one switcher, with no count either, leads the list's toolbar row
* (its `toolbarLeading` slot): the same dropdown, and choosing a view
* switches the list. The record count is still on the phone's screen, in
* the list's footer, away from the view name.
*/
import * as React from 'react';
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { render, cleanup, screen, waitFor, within, fireEvent } from '@testing-library/react';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
import { createI18n, I18nProvider } from '@object-ui/i18n';
vi.mock('@object-ui/permissions', async (importOriginal) => {
const actual = await importOriginal<typeof import('@object-ui/permissions')>();
// Stable identities — `ListView` names `perms` in its fetch dependencies.
const perms = {
check: () => ({ allowed: true }),
checkField: () => true,
getFieldPermissions: () => [],
getRowFilter: () => undefined,
getObjectApiOperations: () => undefined,
roles: [],
isLoaded: false,
hasCapabilities: () => true,
can: () => true,
cannot: () => false,
};
const fieldPerms = { canRead: () => true, canWrite: () => true, permissions: [] };
return { ...actual, usePermissions: () => perms, useFieldPermissions: () => fieldPerms };
});
vi.mock('@object-ui/auth', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAuth: () => ({ user: { id: 'u1', name: 'Sales Manager' }, activeOrganization: { id: 'org1', name: 'Acme' } }),
useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }),
}));
vi.mock('@object-ui/collaboration', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useRealtimeSubscription: () => ({ lastMessage: null }),
useConflictResolution: () => ({ hasConflicts: false, resolveAllConflicts: () => {} }),
}));
vi.mock('./MetadataInspector', () => ({
MetadataPanel: () => null,
useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }),
}));
vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null }));
// `ObjectView` reaches a dynamic `import('@objectstack/lint')`: pay its load at
// collection, never inside a case's clocked window (`check:test-source-alias`).
import '@objectstack/lint';
import { ObjectView } from './ObjectView';
import { ExpressionProvider } from '../providers/ExpressionProvider';
// The page's own reads (the security `explain` probe among them) are relative
// fetches, which happy-dom would send to a real socket. One double, installed
// at module scope and never torn down, so no read the mounted tree issues
// after a test body returns can reach the network.
vi.stubGlobal('fetch', vi.fn(async () =>
new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } })));
/** Eight grid views: more than a tab row ever held. */
const LIST_VIEWS = Object.fromEntries(
Array.from({ length: 8 }, (_, i) => [
`v${i + 1}`,
{ name: `v${i + 1}`, label: `View ${i + 1}`, type: 'grid', columns: ['name'] },
]),
);
const LEAD = {
name: 'crm_lead',
label: 'Lead',
pluralLabel: 'Leads',
fields: {
id: { type: 'text', label: 'Id' },
name: { type: 'text', label: 'Name' },
},
listViews: LIST_VIEWS,
};
const ROWS = [{ id: 'lead_1', name: 'Ada' }];
const DESKTOP_WIDTH = window.innerWidth;
function setViewportWidth(px: number) {
Object.defineProperty(window, 'innerWidth', { value: px, configurable: true, writable: true });
}
function mountLeads(entry = '/apps/crm/crm_lead/view/v1') {
const objects = [LEAD];
const i18n = createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false });
const dataSource = {
find: vi.fn(async () => ({ data: ROWS, total: ROWS.length })),
findOne: vi.fn(async () => null),
getObjectSchema: vi.fn(async (name: string) => objects.find((o) => o.name === name) ?? null),
create: vi.fn(async () => ({})),
update: vi.fn(async () => ({})),
delete: vi.fn(async () => ({})),
} as never;
return render(
<I18nProvider instance={i18n}>
<ExpressionProvider user={{ id: 'u1', name: 'Sales Manager' }}>
<MemoryRouter initialEntries={[entry]}>
<Routes>
<Route
path="/apps/:appName/:objectName/view/:viewId"
element={<ObjectView dataSource={dataSource} objects={objects} onEdit={() => {}} />}
/>
<Route
path="/apps/:appName/:objectName"
element={<ObjectView dataSource={dataSource} objects={objects} onEdit={() => {}} />}
/>
</Routes>
</MemoryRouter>
</ExpressionProvider>
</I18nProvider>,
);
}
/** The list's toolbar has drawn: its Filter control is on screen. */
const listToolbar = () =>
waitFor(() => expect(screen.getByTestId('condition-add-filter')).toBeInTheDocument(), { timeout: 5000 });
/** The reader's pinned view of `crm_lead`, as the workspace preference keeps it. */
const PIN_KEY = 'os:pref:list.view.pinned@object:crm_lead';
const switcher = () => screen.getByTestId('list-view-switcher');
/** Open the title's view switcher. */
function openSwitcher() {
fireEvent.click(switcher());
return screen.getByTestId('list-view-switcher-menu');
}
/**
* The list's footer count once its load settled: it says how many records the
* view holds. A grid draws it in its resident footer row
* (`data-table-summary-lead`, objectstack#35702) and the record-count bar then
* not at all; any other view draws it in the bar.
*/
const FOOTER_COUNT = '[data-testid="data-table-summary-lead"], [data-testid="record-count-bar"]';
const footerCountElement = () => document.querySelector<HTMLElement>(FOOTER_COUNT);
const footerCount = () =>
waitFor(() => expect(footerCountElement()).toHaveTextContent('1 record'), { timeout: 5000 });
/** The ids of the rows in the dropdown's All section, in order. */
const allRowIds = () =>
Array.from(screen.getByTestId('list-view-switcher-all').querySelectorAll('[data-section="all"]')).map((el) =>
el.getAttribute('data-testid')!.replace('view-switcher-row-', ''));
beforeEach(() => {
localStorage.clear();
});
afterEach(() => {
cleanup();
setViewportWidth(DESKTOP_WIDTH);
});
describe('objectstack#27594 — the list title is the view switcher', () => {
it('draws no view-tab bar or tab row; the view bar leads with the switcher: icon, view, count, caret (objectstack#35548)', async () => {
setViewportWidth(1440);
mountLeads();
await listToolbar();
expect(screen.queryByTestId('view-tab-bar')).toBeNull();
expect(screen.queryByTestId('view-tab-row')).toBeNull();
// The page bar names the object; the switcher leads the list's view bar.
const heading = screen.getByRole('heading', { level: 1 });
expect(heading.contains(switcher())).toBe(false);
expect(screen.getByTestId('list-toolbar-leading').contains(switcher())).toBe(true);
expect(within(switcher()).getByTestId('list-view-switcher-label')).toHaveTextContent(/^View 1$/);
// Once the list has reported its count it is drawn beside the view name
// (the maintainer's 「记录数显示在下拉左侧」, after objectstack#34603 had
// taken it away), between the name and the caret.
await footerCount();
await waitFor(() => expect(within(switcher()).getByTestId('list-view-switcher-count')).toHaveTextContent(/^1$/));
const parts = Array.from(switcher().querySelectorAll('[data-testid^="list-view-switcher-"]')).map((el) => el.getAttribute('data-testid'));
expect(parts).toEqual([
'list-view-switcher-type-icon',
'list-view-switcher-label',
'list-view-switcher-count',
'list-view-switcher-caret',
]);
});
it('opens a dropdown with a search box and every view in its declared order', async () => {
setViewportWidth(1440);
mountLeads();
await listToolbar();
const menu = openSwitcher();
expect(within(menu).getByTestId('list-view-switcher-search')).toBeInTheDocument();
expect(allRowIds()).toEqual(['v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8']);
expect(within(menu).queryByTestId('list-view-switcher-pinned')).toBeNull();
});
it('search narrows the views; choosing one switches the list', async () => {
setViewportWidth(1440);
mountLeads();
await listToolbar();
const menu = openSwitcher();
fireEvent.change(within(menu).getByTestId('list-view-switcher-search'), { target: { value: 'view 7' } });
const rows = within(menu).getAllByTestId(/^view-switcher-row-/);
expect(rows.map((el) => el.getAttribute('data-testid'))).toEqual(['view-switcher-row-v7']);
fireEvent.click(rows[0].querySelector('button')!);
await waitFor(() => expect(switcher()).toHaveTextContent('View 7'));
expect(screen.queryByTestId('list-view-switcher-menu')).toBeNull();
});
it('a search nothing matches says so', async () => {
setViewportWidth(1440);
mountLeads();
await listToolbar();
const menu = openSwitcher();
fireEvent.change(within(menu).getByTestId('list-view-switcher-search'), { target: { value: 'zzz' } });
expect(within(menu).getByTestId('list-view-switcher-empty')).toBeInTheDocument();
expect(within(menu).queryAllByTestId(/^view-switcher-row-/)).toHaveLength(0);
});
it('📌 keeps the pinned view per object, and the bare address opens it — on the next mount too', async () => {
setViewportWidth(1440);
const first = mountLeads('/apps/crm/crm_lead');
await listToolbar();
expect(switcher()).toHaveTextContent('View 1');
const menu = openSwitcher();
const row = within(menu).getAllByTestId('view-switcher-row-v3').at(-1)!;
fireEvent.click(within(row).getByTestId('view-switcher-pin'));
expect(JSON.parse(localStorage.getItem(PIN_KEY)!)).toEqual({ view: 'v3', v: 1 });
await waitFor(() => expect(switcher()).toHaveTextContent('View 3'));
first.unmount();
mountLeads('/apps/crm/crm_lead');
await listToolbar();
expect(switcher()).toHaveTextContent('View 3');
const pinnedSection = within(openSwitcher()).getByTestId('list-view-switcher-pinned');
expect(within(pinnedSection).getByTestId('view-switcher-row-v3')).toBeInTheDocument();
// Unpinned, the declared default (the first view here) opens again.
fireEvent.click(within(within(pinnedSection).getByTestId('view-switcher-row-v3')).getByTestId('view-switcher-pin'));
expect(JSON.parse(localStorage.getItem(PIN_KEY)!)).toEqual({ view: null, v: 1 });
await waitFor(() => expect(switcher()).toHaveTextContent('View 1'));
});
it('an address that names a view still opens that view, whatever is pinned', async () => {
setViewportWidth(1440);
localStorage.setItem(PIN_KEY, JSON.stringify({ view: 'v3', v: 1 }));
mountLeads('/apps/crm/crm_lead/view/v5');
await listToolbar();
expect(switcher()).toHaveTextContent('View 5');
});
it('a record open in the drawer over the list keeps the same one switcher in the title', async () => {
setViewportWidth(1440);
mountLeads('/apps/crm/crm_lead/view/v1?recordId=lead_1');
await listToolbar();
expect(screen.getAllByTestId('list-view-switcher')).toHaveLength(1);
expect(switcher()).toHaveTextContent('View 1');
expect(screen.queryByTestId('view-tab-bar')).toBeNull();
expect(screen.queryByTestId('view-tab-row')).toBeNull();
});
it('on a phone (objectstack#27058) the same one switcher leads the list\'s toolbar row, with its dropdown; the count is in the footer (objectstack#34603)', async () => {
setViewportWidth(390);
mountLeads();
await listToolbar();
expect(screen.getAllByTestId('list-view-switcher')).toHaveLength(1);
expect(screen.getByTestId('list-toolbar-leading').contains(switcher())).toBe(true);
expect(screen.queryByRole('heading', { level: 1 })?.contains(switcher()) ?? false).toBe(false);
expect(switcher()).toHaveTextContent('View 1');
// The phone still shows the record count in the list's footer; beside
// the view name it is not drawn below `sm` (objectstack#35548 leaves the
// phone as it was).
await footerCount();
expect(screen.getByTestId('list-view-switcher-count')).toHaveClass('max-sm:hidden');
expect(screen.getByTestId('list-toolbar-leading').contains(footerCountElement())).toBe(false);
expect(screen.queryByTestId('view-tab-bar')).toBeNull();
expect(screen.queryByTestId('view-tab-row')).toBeNull();
const menu = openSwitcher();
expect(allRowIds()).toEqual(['v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8']);
fireEvent.click(within(menu).getAllByTestId('view-switcher-row-v4').at(-1)!.querySelector('button')!);
await waitFor(() => expect(switcher()).toHaveTextContent('View 4'));
});
});