Repository navigation
Expand file tree
/
Copy pathSidebarAppMenu-36112.test.tsx
More file actions
709 lines (644 loc) · 31 KB
/
Copy pathSidebarAppMenu-36112.test.tsx
File metadata and controls
709 lines (644 loc) · 31 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* objectstack#36112 — the sidebar's app menu only switches apps: the viewer's
* apps with the current one checked, the Setup app among them when the server
* serves it, a search field once there are more than eight, and 「Add app」 at
* the foot for a workspace admin who may author. It offers no way home, no
* 「All apps」 and no Studio entry (the page's button group carries 「Edit app」).
*
* Real subjects: `SidebarAppMenu`, `AppMark`, the real launcher list. The
* dropdown primitives pass through so the menu content renders without
* radix's open/close machinery (`AppSwitcher.homeMenu-12605`'s idiom).
*
* objectstack#36485 — the menu is also the door into the design mode:
* 「Edit app」 under the list, in one group with 「Add app」, on the page
* header button's former gate (a workspace admin holding `manage_metadata`,
* an app whose package Studio lists, a read-only one included), not while the
* mode is on. Real subjects added: `useAppStudioEntry`'s gate over a stubbed
* package list, and the shell's real design-mode controller.
*
* objectstack#36758 — the design mode edits the layout only, so its door reads
* 「Design mode」 (zh 「设计模式」), the bar's own word; 「Edit app」 beside
* it opens this app's package in Studio on the app switcher's target and
* posture, and reads 「View in App Studio」 (zh 「在应用搭建中查看」) for an
* installed (read-only) package. Real subject added: the built-in en and
* zh-Hans packs, for the words.
*
* objectstack#36692 — while a dashboard's or a report's own editor is open,
* 「Design mode」 stays drawn and choosing it refuses with the prompt to
* save or cancel those changes first; the mode stays off. `sonner`'s toast is
* spied.
*
* objectstack#36969 — 「Add app」 offers building with AI only where the agent
* catalog serves the build agent (alias-aware). Where in-app building is
* closed the catalog keeps `ask` and drops `build`: the door gives way to 「New
* in Studio」, the template and the marketplace stay. The real
* `useAiSurfaceEnabled` reads a stubbed catalog (`useAgents`).
*
* objectstack#37197 — the docs portal's head (`SidebarDocsPortalMenu`): a
* neutral 「Documentation」 where an app's name is, opening the same list
* under 「Your apps」 with no row checked, and 「Add app」 only; no
* app-scoped row. Real subject added: `SidebarDocsPortalMenu`.
*/
import '@testing-library/jest-dom/vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import * as React from 'react';
import type { ReactNode } from 'react';
const toastError = vi.hoisted(() => vi.fn());
vi.mock('sonner', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
toast: { error: toastError, success: vi.fn() },
}));
type MockProps = Record<string, unknown> & { children?: ReactNode; onSelect?: () => void; className?: string };
vi.mock('@object-ui/components', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
DropdownMenu: (p: MockProps) => <div>{p.children}</div>,
DropdownMenuTrigger: (p: MockProps) => <div>{p.children}</div>,
DropdownMenuContent: ({ children, className: _c, sideOffset: _s, align: _a, ...rest }: MockProps) => (
<div {...rest}>{children}</div>
),
DropdownMenuItem: ({ onSelect, children, asChild: _asChild, className: _c, ...rest }: MockProps) => (
<div data-menu-row="" onClick={onSelect} {...rest}>{children}</div>
),
DropdownMenuSeparator: () => <hr />,
DropdownMenuSub: (p: MockProps) => <div>{p.children}</div>,
DropdownMenuSubTrigger: ({ children, className: _c, ...rest }: MockProps) => <div {...rest}>{children}</div>,
DropdownMenuSubContent: ({ children }: MockProps) => <div data-testid="add-app-choices">{children}</div>,
}));
vi.mock('@object-ui/i18n', async () => {
const actual = await vi.importActual<Record<string, unknown>>('@object-ui/i18n');
return {
...actual,
useObjectTranslation: () => ({
t: (key: string, o?: { defaultValue?: string }) => o?.defaultValue ?? key,
}),
useObjectLabel: () => ({
appLabel: ({ name, label }: { name: string; label?: string }) => label ?? name,
}),
};
});
let apps: Array<Record<string, unknown>> = [];
vi.mock('../../providers/MetadataProvider', () => ({
useMetadata: () => ({ apps }),
}));
let admin = false;
/** What the session's auth answers beyond the real hook: the deployment's posture, the platform operator flag. */
let authOverride: Record<string, unknown> = {};
vi.mock('@object-ui/auth', async (importOriginal) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- the real module, spread whole
const actual = await importOriginal<Record<string, any>>();
return {
...actual,
useWorkspaceAdminStatus: () => ({ isAdmin: admin, isResolved: true }),
useAuth: () => ({ ...actual.useAuth(), ...authOverride }),
};
});
let canAuthor = true;
vi.mock('../../hooks/useCanAuthorMetadata', () => ({
useCanAuthorMetadata: () => canAuthor,
}));
/** The agent catalog the real `useAiSurfaceEnabled` reads. */
let catalog: Array<{ name: string }> = [{ name: 'build' }, { name: 'ask' }];
vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAgents: () => ({ agents: catalog, isLoading: false, error: undefined, refetch: () => {} }),
}));
/** The deployment's posture: metadata authoring offered, a marketplace mounted. */
let aiStudio = true;
let marketplace = true;
vi.mock('../../runtime-config', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
isAiStudioEnabled: () => aiStudio,
isMarketplaceEnabled: () => marketplace,
}));
/** Whether the session holds the Setup → Packages pair (`setup.access` + `manage_platform_settings`). */
let setupPair = true;
vi.mock('@object-ui/permissions', async (importOriginal) => {
const actual = await importOriginal<typeof import('@object-ui/permissions')>();
return {
...actual,
usePermissions: () => {
const real = actual.usePermissions();
return {
...real,
hasCapabilities: (required: string[]) =>
required.includes('setup.access') || required.includes('manage_platform_settings')
? setupPair
: real.hasCapabilities(required),
};
},
};
});
/** When set, what the 「Add app」 list answers instead of the real hook (the empty-list guard). */
let entriesOverride: unknown[] | null = null;
vi.mock('../../hooks/useAddAppEntries', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../hooks/useAddAppEntries')>();
return {
...actual,
useAddAppEntries: () => {
const real = actual.useAddAppEntries();
return entriesOverride ?? real;
},
};
});
import { builtInLocales } from '@object-ui/i18n/locales';
import { SidebarAppMenu, SidebarDocsPortalMenu, APP_MENU_SEARCH_FROM } from '../SidebarAppMenu';
import { DesignModeProvider, useDesignModeController, useHoldDesignModeOut } from '../designMode';
const CRM = { name: 'crm', label: 'CRM', icon: 'flame', _packageId: 'com.acme.crm' };
const SERVICE = { name: 'service', label: 'Service', icon: 'headset' };
const SETUP = { name: 'setup', label: 'Setup', icon: 'settings', _packageId: 'com.objectstack.setup' };
function renderMenu(active = 'crm', onAppChange = vi.fn()) {
render(
<MemoryRouter>
<SidebarAppMenu activeAppName={active} onAppChange={onAppChange} />
</MemoryRouter>,
);
return onAppChange;
}
const menu = () => within(screen.getByTestId('sidebar-app-menu'));
/** Whether the stubbed package list serves CRM's package writable. */
let writable = true;
/** The package list (`GET /api/v1/packages`), read for a viewer who may author: CRM's package, writable or not. */
function stubPackageList() {
vi.stubGlobal(
'fetch',
vi.fn(async (url: unknown) => ({
headers: new Headers(), ok: true,
status: 200,
json: async () =>
String(url).endsWith('/api/v1/packages')
? { data: { packages: [{ manifest: { id: 'com.acme.crm', name: 'CRM' }, writable }] } }
: { data: [] },
})),
);
}
beforeEach(() => {
writable = true;
stubPackageList();
});
afterEach(() => {
cleanup();
apps = [];
admin = false;
canAuthor = true;
catalog = [{ name: 'build' }, { name: 'ask' }];
aiStudio = true;
marketplace = true;
entriesOverride = null;
setupPair = true;
authOverride = {};
toastError.mockReset();
vi.unstubAllGlobals();
});
describe('the sidebar app menu only switches apps (objectstack#36112)', () => {
it('names the current app and lists every app, the current one checked, Setup among them', () => {
apps = [CRM, SERVICE, SETUP];
renderMenu('crm');
expect(screen.getByTestId('sidebar-app-menu-trigger')).toHaveTextContent('CRM');
for (const name of ['crm', 'service', 'setup']) {
expect(menu().getByTestId(`sidebar-app-menu-row-${name}`)).toBeInTheDocument();
}
expect(menu().getByTestId('sidebar-app-menu-row-crm').querySelector('svg.lucide-check')).not.toBeNull();
expect(menu().getByTestId('sidebar-app-menu-row-service').querySelector('svg.lucide-check')).toBeNull();
});
it('offers no way home and no 「All apps」; a member gets no Studio entry', () => {
apps = [CRM, SERVICE, SETUP];
renderMenu('crm');
for (const text of ['Back to home', 'All apps', 'Edit app', 'View in App Studio', 'Edit CRM in App Studio', 'Open CRM in App Studio']) {
expect(menu().queryByText(text)).toBeNull();
}
});
it('a viewer the server serves no Setup app to sees none', () => {
apps = [CRM, SERVICE];
renderMenu('crm');
expect(menu().queryByTestId('sidebar-app-menu-row-setup')).toBeNull();
});
it('choosing another app opens it by its address; the current one does nothing', () => {
apps = [CRM, SERVICE];
const onAppChange = renderMenu('crm');
fireEvent.click(menu().getByTestId('sidebar-app-menu-row-service'));
expect(onAppChange).toHaveBeenCalledWith('service');
fireEvent.click(menu().getByTestId('sidebar-app-menu-row-crm'));
expect(onAppChange).toHaveBeenCalledTimes(1);
});
it(`draws a search field above the list only past ${APP_MENU_SEARCH_FROM} apps, and it narrows the list`, () => {
apps = Array.from({ length: APP_MENU_SEARCH_FROM }, (_, i) => ({ name: `app${i}`, label: `App ${i}` }));
renderMenu('app0');
expect(menu().queryByTestId('sidebar-app-menu-search')).toBeNull();
cleanup();
apps = [...apps, { name: 'billing', label: 'Billing' }];
renderMenu('app0');
fireEvent.change(menu().getByTestId('sidebar-app-menu-search'), { target: { value: 'bill' } });
expect(menu().getByTestId('sidebar-app-menu-row-billing')).toBeInTheDocument();
expect(menu().queryByTestId('sidebar-app-menu-row-app1')).toBeNull();
fireEvent.change(menu().getByTestId('sidebar-app-menu-search'), { target: { value: 'zzz' } });
expect(menu().getByTestId('sidebar-app-menu-empty')).toBeInTheDocument();
});
it('「Add app」 is offered to a workspace admin who may author: a blank app, a template, the marketplace', () => {
apps = [CRM];
admin = true;
renderMenu('crm');
expect(menu().getByTestId('sidebar-app-menu-add')).toHaveTextContent('Add app');
const choices = within(screen.getByTestId('add-app-choices'));
expect(choices.getByTestId('sidebar-app-menu-add-new-in-studio')).toHaveAttribute('href', '/apps/setup/component/developer/packages?face=admin&new=package');
expect(choices.getByTestId('sidebar-app-menu-add-template')).toHaveAttribute('href', '/apps/setup/system/marketplace');
expect(choices.getByTestId('sidebar-app-menu-add-marketplace')).toHaveAttribute('href', '/apps/setup/system/marketplace');
});
it('control: a member, or an admin who may not author, gets no 「Add app」', () => {
apps = [CRM];
renderMenu('crm');
expect(menu().queryByTestId('sidebar-app-menu-add')).toBeNull();
cleanup();
admin = true;
canAuthor = false;
renderMenu('crm');
expect(menu().queryByTestId('sidebar-app-menu-add')).toBeNull();
});
});
describe('「Add app」 offers 「New blank app」 whatever the catalog serves, and no 「Build with AI」 (objectstack#36908)', () => {
// objectstack#36969 drew a build-with-AI door where the catalog served the
// build agent and the Studio door elsewhere. The maintainer ruled 「Build with
// AI」 off this menu and 「New blank app」 always shown (ruling records
// 7153161067, 7153400210): the catalog no longer decides either.
function addChoices() {
apps = [CRM];
admin = true;
renderMenu('crm');
return within(screen.getByTestId('add-app-choices'));
}
const choiceIds = () =>
Array.from(screen.getByTestId('add-app-choices').querySelectorAll('a')).map((a) => a.getAttribute('data-testid'));
it.each([
['build and ask served', [{ name: 'build' }, { name: 'ask' }]],
['the legacy build id served', [{ name: 'metadata_assistant' }, { name: 'data_chat' }]],
['in-app building closed (`ask` only)', [{ name: 'ask' }]],
['other agents only', [{ name: 'custom_helper' }]],
['no agent at all', []],
])('%s: 「New blank app」 to New Package, a template, the marketplace — never 「Build with AI」', (_case, served) => {
catalog = served;
const choices = addChoices();
expect(choices.getByTestId('sidebar-app-menu-add-new-in-studio')).toHaveAttribute(
'href',
'/apps/setup/component/developer/packages?face=admin&new=package',
);
expect(choices.getByTestId('sidebar-app-menu-add-new-in-studio')).toHaveTextContent('New blank app');
expect(choices.queryByTestId('sidebar-app-menu-add-build-with-ai')).toBeNull();
expect(choices.queryByText('Build with AI')).toBeNull();
expect(choiceIds()).toEqual([
'sidebar-app-menu-add-new-in-studio',
'sidebar-app-menu-add-template',
'sidebar-app-menu-add-marketplace',
]);
});
// objectstack#37565 — the cross-package directory moved to Setup. objectstack#38150 — the
// package-less scope the door opened next is retired: Studio's Loose list of flows, where
// that scope's addresses land.
it('an author who may enter Studio but not Setup → Packages is sent to Studio\'s Loose list of flows, never Setup (objectstack#36908)', () => {
setupPair = false;
const choices = addChoices();
expect(choices.getByTestId('sidebar-app-menu-add-new-in-studio')).toHaveAttribute('href', '/studio/~all/metadata/flow?source=loose');
});
it.each([
['metadata authoring offered, no marketplace', true, false, ['sidebar-app-menu-add-new-in-studio']],
['a marketplace, no metadata authoring', false, true, ['sidebar-app-menu-add-template', 'sidebar-app-menu-add-marketplace']],
])('never empty for an admitted viewer — %s', (_case, ai, market, expected) => {
aiStudio = ai;
marketplace = market;
addChoices();
expect(menu().getByTestId('sidebar-app-menu-add')).toBeInTheDocument();
expect(choiceIds()).toEqual(expected);
});
it('control: with neither offered, the viewer is not admitted, and the menu draws no 「Add app」', () => {
aiStudio = false;
marketplace = false;
apps = [CRM];
admin = true;
renderMenu('crm');
expect(menu().queryByTestId('sidebar-app-menu-add')).toBeNull();
});
it('guard: an admitted viewer handed no entries gets no 「Add app」 and no separator for it', () => {
entriesOverride = [];
apps = [CRM];
admin = true;
renderMenu('crm');
expect(menu().queryByTestId('sidebar-app-menu-add')).toBeNull();
expect(screen.queryByTestId('add-app-choices')).toBeNull();
// 「Design mode」 and 「Edit app」 read the package list, which has not
// answered on this first frame, so nothing else asks for the separator.
expect(menu().queryByRole('separator')).toBeNull();
expect(screen.getByTestId('sidebar-app-menu').querySelector('hr')).toBeNull();
});
});
describe('「Design mode」 in the app menu enters the design mode (objectstack#36485, objectstack#36758)', () => {
/** The shell's hold on the mode, as `ConsoleLayout` keeps it, and whether it is on. */
function Shell({ children }: { children: ReactNode }) {
const mode = useDesignModeController({ appName: 'crm', appBasePath: '/apps/crm', enabled: true });
return (
<DesignModeProvider value={mode}>
<output data-testid="mode">{mode.active ? 'on' : 'off'}</output>
{children}
</DesignModeProvider>
);
}
async function mountMenu({ held = true, route = '/apps/crm/crm_lead', active = 'crm' } = {}) {
const menuNode = <SidebarAppMenu activeAppName={active} onAppChange={vi.fn()} />;
render(<MemoryRouter initialEntries={[route]}>{held ? <Shell>{menuNode}</Shell> : menuNode}</MemoryRouter>);
// The package list's verdict settled, so an absent item is a reading.
await act(() => new Promise<void>((resolve) => setTimeout(resolve, 0)));
await act(() => new Promise<void>((resolve) => setTimeout(resolve, 0)));
}
const editApp = () => menu().queryByTestId('sidebar-app-menu-design-layout');
beforeEach(() => {
apps = [CRM, SERVICE, SETUP];
admin = true;
});
it('a workspace admin who may author sees it under the list, in one group with 「Add app」', async () => {
await mountMenu();
const item = editApp();
expect(item).not.toBeNull();
expect(item).toHaveTextContent('Design mode');
expect(item!.querySelector('svg.lucide-pencil-ruler')).not.toBeNull();
const lastRow = menu().getByTestId('sidebar-app-menu-row-setup');
const add = menu().getByTestId('sidebar-app-menu-add');
const rule = item!.previousElementSibling;
expect(rule?.tagName).toBe('HR');
expect(lastRow.compareDocumentPosition(rule!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(item!.compareDocumentPosition(add) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
// 「Edit app」 (Studio) sits between the two, in the same group.
const studio = menu().getByTestId('sidebar-app-menu-edit-app');
expect(item!.compareDocumentPosition(studio) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(studio.compareDocumentPosition(add) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
// One group: the rule above it is the menu's only one, none between it and 「Add app」.
expect(screen.getByTestId('sidebar-app-menu').querySelectorAll('hr')).toHaveLength(1);
});
it('choosing it turns the mode on in place; while it is on the menu offers it no more', async () => {
await mountMenu();
expect(screen.getByTestId('mode')).toHaveTextContent('off');
await act(async () => fireEvent.click(editApp()!));
expect(screen.getByTestId('mode')).toHaveTextContent('on');
expect(editApp()).toBeNull();
// The rest of the menu is unchanged.
expect(menu().getByTestId('sidebar-app-menu-add')).toBeInTheDocument();
expect(menu().getByTestId('sidebar-app-menu-row-crm')).toBeInTheDocument();
});
it('an installed (read-only) package\'s app has it too, and it enters the same mode (objectstack#36363)', async () => {
writable = false;
await mountMenu();
await act(async () => fireEvent.click(editApp()!));
expect(screen.getByTestId('mode')).toHaveTextContent('on');
});
it('where the customization door is walled off for this caller, a read-only package\'s app gets none; a writable one keeps it', async () => {
authOverride = { getAuthConfig: async () => ({ features: { tenancyPosture: 'isolated' } }), user: { isPlatformAdmin: false } };
writable = false;
await mountMenu();
expect(editApp()).toBeNull();
cleanup();
writable = true;
// A fresh transport, so the list is read again rather than answered from the session's hold.
stubPackageList();
await mountMenu();
expect(editApp()).not.toBeNull();
});
it('control: a member, and an admin who may not author, get none', async () => {
admin = false;
await mountMenu();
expect(editApp()).toBeNull();
cleanup();
admin = true;
canAuthor = false;
await mountMenu();
expect(editApp()).toBeNull();
});
it('control: none on an app whose package Studio does not list (the console\'s own Setup), nor where no shell holds the mode', async () => {
await mountMenu({ active: 'setup', route: '/apps/setup/system' });
expect(editApp()).toBeNull();
cleanup();
await mountMenu({ held: false });
expect(editApp()).toBeNull();
});
});
describe('「Edit app」 in the app menu opens this app in Studio (objectstack#36758)', () => {
async function mountMenu({ route = '/apps/crm/crm_lead', active = 'crm' } = {}) {
render(
<MemoryRouter initialEntries={[route]}>
<SidebarAppMenu activeAppName={active} onAppChange={vi.fn()} />
</MemoryRouter>,
);
await act(() => new Promise<void>((resolve) => setTimeout(resolve, 0)));
await act(() => new Promise<void>((resolve) => setTimeout(resolve, 0)));
}
const editInStudio = () => menu().queryByTestId('sidebar-app-menu-edit-app');
const viewInStudio = () => menu().queryByTestId('sidebar-app-menu-view-in-studio');
beforeEach(() => {
apps = [CRM, SERVICE, SETUP];
admin = true;
});
it('a writable package\'s app: 「Edit app」 behind a pencil, linking to the package in Studio', async () => {
await mountMenu();
const item = editInStudio();
expect(item).not.toBeNull();
expect(item).toHaveTextContent(/^Edit app$/);
expect(item!.querySelector('svg.lucide-pencil')).not.toBeNull();
// The app switcher's target: the object route opens the package's Data tab on that object.
expect(item).toHaveAttribute('href', '/studio/com.acme.crm/metadata/object/crm_lead');
expect(viewInStudio()).toBeNull();
});
it('it follows the route the way the app switcher\'s Studio row does: a dashboard opens its design surface', async () => {
await mountMenu({ route: '/apps/crm/dashboard/pipeline' });
expect(editInStudio()).toHaveAttribute('href', '/studio/com.acme.crm/metadata/dashboard/pipeline');
});
it('an installed (read-only) package\'s app: 「View in Studio」 behind an eye, never the pencil', async () => {
writable = false;
await mountMenu();
expect(editInStudio()).toBeNull();
const item = viewInStudio();
expect(item).not.toBeNull();
expect(item).toHaveTextContent(/^View in App Studio$/);
expect(item!.querySelector('svg.lucide-eye')).not.toBeNull();
expect(item).toHaveAttribute('href', '/studio/com.acme.crm/metadata/object/crm_lead');
});
it('it is drawn with no shell holding the design mode: its gate is Studio\'s, not the mode\'s', async () => {
await mountMenu();
expect(menu().queryByTestId('sidebar-app-menu-design-layout')).toBeNull();
expect(editInStudio()).not.toBeNull();
});
it('control: a member, an admin who may not author, and the console\'s own Setup get none', async () => {
admin = false;
await mountMenu();
expect(editInStudio()).toBeNull();
expect(viewInStudio()).toBeNull();
cleanup();
admin = true;
canAuthor = false;
await mountMenu();
expect(editInStudio()).toBeNull();
expect(viewInStudio()).toBeNull();
cleanup();
canAuthor = true;
await mountMenu({ active: 'setup', route: '/apps/setup/system' });
expect(editInStudio()).toBeNull();
expect(viewInStudio()).toBeNull();
});
});
describe('the words: the door and the bar share one name (objectstack#36758)', () => {
type Pack = Record<string, Record<string, string>>;
const EN = builtInLocales.en as unknown as Pack;
const ZH = builtInLocales['zh-Hans'] as unknown as Pack;
it('zh-Hans: 「设计模式」 for the door and the bar, 「编辑应用」 and 「在应用搭建中查看」 for Studio', () => {
expect(ZH.topbar.designLayout).toBe('设计模式');
expect(ZH.designMode.title).toBe('设计模式');
expect(ZH.topbar.editApp).toBe('编辑应用');
expect(ZH.topbar.viewInStudio).toBe('在应用搭建中查看');
});
it('every built-in pack names the door as its bar', () => {
for (const [locale, pack] of Object.entries(builtInLocales as unknown as Record<string, Pack>)) {
expect(pack.topbar.designLayout, locale).toBe(pack.designMode.title);
expect(pack.topbar.designLayout, locale).not.toBe(pack.topbar.editApp);
}
expect(EN.designMode.title).toBe('Design mode');
});
});
describe('「Design mode」 refuses while a dashboard or report editor is open (objectstack#36692)', () => {
/** The shell's hold on the mode, and a page whose own editor can be opened and closed. */
function Shell({ children }: { children: ReactNode }) {
const mode = useDesignModeController({ appName: 'crm', appBasePath: '/apps/crm', enabled: true });
return (
<DesignModeProvider value={mode}>
<output data-testid="mode">{mode.active ? 'on' : 'off'}</output>
{children}
</DesignModeProvider>
);
}
function EditorPage() {
const [open, setOpen] = React.useState(false);
useHoldDesignModeOut(open);
return (
<button type="button" data-testid="editor-toggle" onClick={() => setOpen((o) => !o)}>
{open ? 'close editor' : 'open editor'}
</button>
);
}
async function mountMenu() {
render(
<MemoryRouter initialEntries={['/apps/crm/dashboard/ops_board']}>
<Shell>
<SidebarAppMenu activeAppName="crm" onAppChange={vi.fn()} />
<EditorPage />
</Shell>
</MemoryRouter>,
);
await act(() => new Promise<void>((resolve) => setTimeout(resolve, 0)));
await act(() => new Promise<void>((resolve) => setTimeout(resolve, 0)));
}
const designLayout = () => menu().queryByTestId('sidebar-app-menu-design-layout');
beforeEach(() => {
apps = [CRM, SERVICE, SETUP];
admin = true;
});
it('it stays drawn; choosing it says to save or cancel those changes first, and the mode stays off', async () => {
await mountMenu();
fireEvent.click(screen.getByTestId('editor-toggle'));
expect(designLayout()).not.toBeNull();
await act(async () => fireEvent.click(designLayout()!));
expect(screen.getByTestId('mode')).toHaveTextContent('off');
expect(toastError).toHaveBeenCalledTimes(1);
expect(toastError).toHaveBeenCalledWith('Save or cancel your dashboard or report changes before entering Design mode.');
});
it('control: the editor closed, choosing it enters the mode and says nothing', async () => {
await mountMenu();
fireEvent.click(screen.getByTestId('editor-toggle'));
fireEvent.click(screen.getByTestId('editor-toggle'));
await act(async () => fireEvent.click(designLayout()!));
expect(screen.getByTestId('mode')).toHaveTextContent('on');
expect(toastError).not.toHaveBeenCalled();
});
it('the prompt is in every built-in pack, and zh-Hans reads as the design mode is named', () => {
const packs = builtInLocales as unknown as Record<string, { designMode: { editorOpen?: string; title: string } }>;
for (const [locale, pack] of Object.entries(packs)) {
expect(pack.designMode.editorOpen, locale).toBeTruthy();
}
expect(packs['zh-Hans'].designMode.editorOpen).toContain(packs['zh-Hans'].designMode.title);
});
});
describe('the docs portal\'s head names no app and only switches apps (objectstack#37197)', () => {
function renderPortalMenu(onAppChange = vi.fn()) {
render(
<MemoryRouter>
<SidebarDocsPortalMenu onAppChange={onAppChange} />
</MemoryRouter>,
);
return onAppChange;
}
const portalMenu = () => within(screen.getByTestId('sidebar-docs-portal-menu'));
it('reads 「Documentation」, not an app, and lists every app under 「Your apps」 with none checked', () => {
apps = [CRM, SERVICE, SETUP];
renderPortalMenu();
const trigger = screen.getByTestId('sidebar-docs-portal-menu-trigger');
expect(trigger).toHaveTextContent('Documentation');
for (const app of [CRM, SERVICE, SETUP]) expect(trigger).not.toHaveTextContent(app.label);
expect(portalMenu().getByText('Your apps')).toBeInTheDocument();
for (const name of ['crm', 'service', 'setup']) {
const row = portalMenu().getByTestId(`sidebar-app-menu-row-${name}`);
expect(row.querySelector('svg.lucide-check'), name).toBeNull();
}
// The app menu itself is not drawn here.
expect(screen.queryByTestId('sidebar-app-menu-trigger')).toBeNull();
});
it('choosing any app opens it by its address', () => {
apps = [CRM, SERVICE];
const onAppChange = renderPortalMenu();
fireEvent.click(portalMenu().getByTestId('sidebar-app-menu-row-crm'));
fireEvent.click(portalMenu().getByTestId('sidebar-app-menu-row-service'));
expect(onAppChange.mock.calls).toEqual([['com.acme.crm'], ['service']]);
});
it('a workspace admin who may author gets 「Add app」 and no app-scoped row', () => {
apps = [CRM];
admin = true;
renderPortalMenu();
expect(portalMenu().getByTestId('sidebar-app-menu-add')).toHaveTextContent('Add app');
for (const id of ['sidebar-app-menu-design-layout', 'sidebar-app-menu-edit-app', 'sidebar-app-menu-view-in-studio']) {
expect(portalMenu().queryByTestId(id), id).toBeNull();
}
for (const text of ['Design mode', 'Edit app', 'View in App Studio']) expect(portalMenu().queryByText(text)).toBeNull();
});
it('control: a member gets the list and no 「Add app」', () => {
apps = [CRM];
renderPortalMenu();
expect(portalMenu().getByTestId('sidebar-app-menu-row-crm')).toBeInTheDocument();
expect(portalMenu().queryByTestId('sidebar-app-menu-add')).toBeNull();
});
// objectstack#36908 — the portal's 「Add app」 is the app menu's list, under
// the same rule (ruling records 7153161067, 7153400210).
it('its 「Add app」 offers 「New blank app」 and no 「Build with AI」, with the build agent served', () => {
apps = [CRM];
admin = true;
renderPortalMenu();
const choices = within(screen.getByTestId('add-app-choices'));
expect(choices.getByTestId('sidebar-app-menu-add-new-in-studio')).toHaveTextContent('New blank app');
expect(choices.getByTestId('sidebar-app-menu-add-new-in-studio')).toHaveAttribute(
'href',
'/apps/setup/component/developer/packages?face=admin&new=package',
);
expect(choices.queryByTestId('sidebar-app-menu-add-build-with-ai')).toBeNull();
expect(choices.queryByText('Build with AI')).toBeNull();
});
it('an author who may not open Setup → Packages gets 「New blank app」 to Studio\'s Loose list of flows (objectstack#37565, objectstack#38150)', () => {
setupPair = false;
apps = [CRM];
admin = true;
renderPortalMenu();
expect(
within(screen.getByTestId('add-app-choices')).getByTestId('sidebar-app-menu-add-new-in-studio'),
).toHaveAttribute('href', '/studio/~all/metadata/flow?source=loose');
});
it('guard: handed no entries, it draws no 「Add app」 and no separator for it', () => {
entriesOverride = [];
apps = [CRM];
admin = true;
renderPortalMenu();
expect(portalMenu().queryByTestId('sidebar-app-menu-add')).toBeNull();
expect(screen.getByTestId('sidebar-docs-portal-menu').querySelector('hr')).toBeNull();
});
});