Skip to content

Commit d9524d3

Browse files
committed
wip: sidebar elects the area holding the current page
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibz6e1jru1WvD8e9e9E
1 parent 1f1a369 commit d9524d3

3 files changed

Lines changed: 349 additions & 21 deletions

File tree

‎ui/packages/app-shell/src/layout/UnifiedSidebar.tsx‎

Lines changed: 39 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ import { useConsoleSidebarRail, useConsoleSidebarRailPanel } from './consoleSide
7676
import { SidebarItemMenu, sidebarItemDesignPath, favoriteDesignPath } from './SidebarItemMenu.js';
7777
import { SortableFavoriteRows, type FavoriteRowDragProps } from './SortableFavoriteRows.js';
7878
import { favoriteAppSegment } from './listViewFavorites.js';
79+
import { electSidebarArea, type SidebarAreaRoute } from './sidebarAreaElection.js';
7980
import type { FavoriteItem } from '../hooks/useFavorites.js';
8081

8182
/**
@@ -256,6 +257,24 @@ export function UnifiedSidebar({ activeAppName, railOverlay = false }: UnifiedSi
256257
can,
257258
} = useNavMemberGates();
258259

260+
// App-level context selectors (e.g. Studio's package scope). Their
261+
// values are injected into nav items as `{<id>}` template vars so a
262+
// single dropdown transparently scopes every secondary menu.
263+
const { contextValues, element: contextSelectorsUI } = useAppContextSelectors(
264+
activeApp?.name || 'home',
265+
activeApp?.contextSelectors,
266+
t,
267+
);
268+
269+
// The template context every navigation href here resolves with; the area
270+
// election below matches routes with it too, so it agrees with the drawn
271+
// highlight.
272+
const navTemplateContext = {
273+
currentUserId: user?.id ?? null,
274+
currentOrgId: activeOrganization?.id ?? null,
275+
contextValues,
276+
};
277+
259278
// Area management.
260279
//
261280
// Area visibility is DERIVED from the items inside (objectui#3311 /
@@ -303,38 +322,37 @@ export function UnifiedSidebar({ activeAppName, railOverlay = false }: UnifiedSi
303322
hasActionHandler: !!dispatchNavAction,
304323
}),
305324
);
325+
// The route the area election reads: in an app, the area whose navigation
326+
// holds the entry the current page addresses is shown (`electSidebarArea`).
327+
const areaRoute: SidebarAreaRoute | null =
328+
context === 'app' && activeApp
329+
? {
330+
pathname: location.pathname,
331+
search: location.search,
332+
basePath: `/apps/${appRouteSegment(activeApp)}`,
333+
templateContext: navTemplateContext,
334+
}
335+
: null;
306336
const [activeAreaId, setActiveAreaId] = React.useState<string | null>(
307-
() => visibleAreas.length > 0 ? visibleAreas[0].id : null,
337+
() => electSidebarArea(visibleAreas, null, areaRoute),
308338
);
309339

310340
const visibleAreaIds = visibleAreas.map((a) => a.id).join(',');
311341

312-
// Re-elect when the app changes or the visible-area set changes. Keeping
313-
// `prev` whenever it is still visible means merely REVEALING a new area
314-
// never steals the user's current selection.
342+
// Re-elect when the app, the visible-area set or the route changes. The
343+
// current area stays while it is still visible and the page is one of its
344+
// entries' (or no area's), so merely REVEALING a new area never steals the
345+
// user's selection, and a user's own pick holds on a page it addresses.
315346
React.useEffect(() => {
316-
if (visibleAreas.length > 0) {
317-
setActiveAreaId(prev => visibleAreas.some((a) => a.id === prev) ? prev : visibleAreas[0].id);
318-
} else {
319-
setActiveAreaId(null);
320-
}
321-
}, [activeApp?.name, visibleAreaIds]);
347+
setActiveAreaId((prev) => electSidebarArea(visibleAreas, prev, areaRoute));
348+
}, [activeApp?.name, visibleAreaIds, location.pathname, location.search, context]);
322349

323350
// Resolve navigation items. The render-time `?? visibleAreas[0]` fallback
324351
// covers the frame between a gating change hiding the active area and the
325352
// effect above re-electing.
326353
const activeArea = visibleAreas.find((a) => a.id === activeAreaId) ?? visibleAreas[0];
327354
const appNavigation: NavigationItem[] = activeArea?.navigation || readableAppNavigation || [];
328355

329-
// App-level context selectors (e.g. Studio's package scope). Their
330-
// values are injected into nav items as `{<id>}` template vars so a
331-
// single dropdown transparently scopes every secondary menu.
332-
const { contextValues, element: contextSelectorsUI } = useAppContextSelectors(
333-
activeApp?.name || 'home',
334-
activeApp?.contextSelectors,
335-
t,
336-
);
337-
338356
// Home navigation items. For workspace admins we surface the full system
339357
// ("Administration") nav right here on /home — previously the home context
340358
// showed ONLY a "Home" link, so a fresh env (no apps yet) rendered a bare
@@ -637,7 +655,7 @@ export function UnifiedSidebar({ activeAppName, railOverlay = false }: UnifiedSi
637655
locale={language}
638656
onAction={dispatchNavAction}
639657
t={t}
640-
templateContext={{ currentUserId: user?.id ?? null, currentOrgId: activeOrganization?.id ?? null, contextValues }}
658+
templateContext={navTemplateContext}
641659
/>
642660

643661
{/* The app's report index is an entry its navigation declares,
@@ -731,7 +749,7 @@ export function UnifiedSidebar({ activeAppName, railOverlay = false }: UnifiedSi
731749
locale={language}
732750
onAction={dispatchNavAction}
733751
t={t}
734-
templateContext={{ currentUserId: user?.id ?? null, currentOrgId: activeOrganization?.id ?? null, contextValues }}
752+
templateContext={navTemplateContext}
735753
/>
736754

737755
{/* Starred Apps */}
Lines changed: 231 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* UnifiedSidebar — the sidebar shows the area that holds the current page.
5+
*
6+
* In an app with several areas, the area elected on the first render, and
7+
* whenever the route moves to a page no entry of the shown area addresses, is
8+
* the one whose navigation holds the entry the route addresses: the entry
9+
* `resolveActiveNavItem` elects, the same match that highlights the row. With
10+
* none, the current area stays, else the first visible one. A reader's own
11+
* area pick holds while the page is one its entries address.
12+
*
13+
* `@object-ui/components` and `@object-ui/layout` stay REAL, so the highlight
14+
* asserted below is the one `NavigationRenderer` draws.
15+
*/
16+
17+
import '@testing-library/jest-dom/vitest';
18+
import { describe, it, expect, vi, beforeEach } from 'vitest';
19+
import React from 'react';
20+
import { render, screen, fireEvent, act } from '@testing-library/react';
21+
import { MemoryRouter, useNavigate, type NavigateFunction } from 'react-router-dom';
22+
import type { NavigationArea } from '@object-ui/types';
23+
24+
// ---------------------------------------------------------------------------
25+
// Mocks — providers and console-only chrome.
26+
// ---------------------------------------------------------------------------
27+
28+
// Partial mock: @object-ui/components also imports from @object-ui/i18n
29+
// (createSafeTranslation), so the rest of the module must stay real.
30+
vi.mock('@object-ui/i18n', async (importOriginal) => ({
31+
...(await importOriginal<Record<string, unknown>>()),
32+
useObjectTranslation: () => ({
33+
t: (key: string, options?: Record<string, unknown>) => String(options?.defaultValue ?? key),
34+
}),
35+
useObjectLabel: () => ({
36+
objectLabel: ({ label }: { label?: string }) => label,
37+
viewLabel: (_o: string, _v: string, fallback?: string) => fallback,
38+
dashboardLabel: ({ label }: { label?: string }) => label,
39+
}),
40+
}));
41+
42+
vi.mock('@object-ui/auth', async (importOriginal) => ({
43+
...(await importOriginal<Record<string, unknown>>()),
44+
useAuth: () => ({ user: null, activeOrganization: null }),
45+
useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }),
46+
}));
47+
48+
// Mutable permission state — swapped per test, re-read on every render.
49+
let permissionsState: {
50+
can: (objectName: string, action: string) => boolean;
51+
hasCapabilities: (caps: string[]) => boolean;
52+
};
53+
vi.mock('@object-ui/permissions', async (importOriginal) => {
54+
const actual = await importOriginal<typeof import('@object-ui/permissions')>();
55+
return {
56+
...actual,
57+
usePermissions: () => permissionsState,
58+
};
59+
});
60+
61+
let metadataState: { apps: unknown[]; objects: unknown[] };
62+
vi.mock('../../providers/MetadataProvider', () => ({
63+
useMetadata: () => metadataState,
64+
}));
65+
66+
vi.mock('../../providers/ExpressionProvider', () => ({
67+
useExpressionContext: () => ({ evaluator: null }),
68+
// Mirrors the real evaluateVisibility's literal handling — enough for
69+
// fixtures gating with `visible: false`.
70+
evaluateVisibility: (expr: unknown) => expr !== false && expr !== 'false',
71+
evaluateNavigationVisibility: (expr: unknown) => expr !== false && expr !== 'false',
72+
useHasExpressionScope: () => true,
73+
}));
74+
75+
vi.mock('../../utils', () => ({
76+
resolveKeyedI18nLabel: (label: unknown) => (typeof label === 'string' ? label : ''),
77+
matchAppBySegment: (apps: Array<{ name?: string }>, segment?: string) =>
78+
apps.find((a) => a?.name === segment),
79+
appRouteSegment: (app: { name?: string }) => app?.name,
80+
}));
81+
82+
// Lazy lucide DynamicIcon would suspend mid-test; a null icon is enough here.
83+
vi.mock('../../utils/getIcon', () => ({ getIcon: () => () => null }));
84+
85+
vi.mock('../../hooks/useRecentItems', () => ({ useRecentItems: () => ({ recentItems: [] }) }));
86+
vi.mock('../../hooks/useFavorites', () => ({
87+
useFavorites: () => ({ favorites: [], removeFavorite: vi.fn() }),
88+
}));
89+
vi.mock('../../hooks/useNavPins', () => ({
90+
useNavPins: () => ({ togglePin: vi.fn(), applyPins: (items: unknown) => items }),
91+
}));
92+
const dispatchNavAction = vi.fn();
93+
vi.mock('../../hooks/useNavActionDispatch', () => ({
94+
useNavActionDispatch: () => dispatchNavAction,
95+
}));
96+
vi.mock('../../context/NavigationContext', () => ({
97+
useNavigationContext: () => ({ context: 'app', currentAppName: 'crm' }),
98+
}));
99+
// The sidebar also imports the per-selector scope-key derivation (#3500) to
100+
// build Studio's home link; keep those exports on the mock or the module is
101+
// missing them at import time.
102+
vi.mock('../ContextSelectors', () => ({
103+
useAppContextSelectors: () => ({ contextValues: {}, element: null }),
104+
contextSelectorQueryKey: (id: string) => (id === 'active_package' ? 'package' : id),
105+
STUDIO_PACKAGE_SELECTOR_ID: 'active_package',
106+
}));
107+
vi.mock('../LocalizedSidebarTrigger', () => ({
108+
LocalizedSidebarTrigger: () => null,
109+
}));
110+
111+
import { SidebarProvider } from '@object-ui/components';
112+
import { UnifiedSidebar } from '../UnifiedSidebar';
113+
114+
import { SidebarProvider } from '@object-ui/components';
115+
import { UnifiedSidebar } from '../UnifiedSidebar';
116+
117+
// ---------------------------------------------------------------------------
118+
// Fixtures — labels are pairwise distinct so a hit is unambiguous.
119+
// ---------------------------------------------------------------------------
120+
121+
const salesArea: NavigationArea = {
122+
id: 'area-sales',
123+
label: 'Sales',
124+
navigation: [
125+
{ id: 'nav-opportunity', type: 'object', label: 'Opportunities', objectName: 'opportunity' },
126+
{ id: 'nav-account-sales', type: 'object', label: 'Accounts (sales)', objectName: 'account' },
127+
],
128+
};
129+
130+
const serviceArea: NavigationArea = {
131+
id: 'area-service',
132+
label: 'Service',
133+
navigation: [
134+
{
135+
id: 'grp-service',
136+
type: 'group',
137+
label: 'Support',
138+
children: [{ id: 'nav-case', type: 'object', label: 'Cases', objectName: 'case' }],
139+
},
140+
{ id: 'nav-account-service', type: 'object', label: 'Accounts (service)', objectName: 'account' },
141+
],
142+
};
143+
144+
let navigate: NavigateFunction;
145+
function NavigateProbe() {
146+
navigate = useNavigate();
147+
return null;
148+
}
149+
150+
function renderAt(path: string) {
151+
metadataState = {
152+
apps: [{ name: 'crm', label: 'CRM', active: true, areas: [salesArea, serviceArea] }],
153+
objects: [],
154+
};
155+
return render(
156+
<MemoryRouter initialEntries={[path]}>
157+
<NavigateProbe />
158+
<SidebarProvider>
159+
<UnifiedSidebar activeAppName="crm" />
160+
</SidebarProvider>
161+
</MemoryRouter>,
162+
);
163+
}
164+
165+
/** The switcher row of an area — the button whose text is the area label. */
166+
function areaButton(label: string): HTMLElement {
167+
const button = screen.getByText(label).closest('[data-sidebar="menu-button"]');
168+
if (!(button instanceof HTMLElement)) throw new Error(`no switcher row for area ${label}`);
169+
return button;
170+
}
171+
172+
function navRow(label: string): HTMLElement {
173+
const row = screen.getByText(label).closest('[data-active]');
174+
if (!(row instanceof HTMLElement)) throw new Error(`no navigation row for ${label}`);
175+
return row;
176+
}
177+
178+
beforeEach(() => {
179+
permissionsState = { can: () => true, hasCapabilities: () => true };
180+
localStorage.clear();
181+
});
182+
183+
describe('UnifiedSidebar elects the area that holds the current page', () => {
184+
it('opens on the second area when the route addresses one of its entries, with that entry highlighted', () => {
185+
renderAt('/apps/crm/case');
186+
expect(areaButton('Service')).toHaveAttribute('data-active', 'true');
187+
expect(areaButton('Sales')).toHaveAttribute('data-active', 'false');
188+
expect(navRow('Cases')).toHaveAttribute('data-active', 'true');
189+
expect(screen.queryByText('Opportunities')).not.toBeInTheDocument();
190+
});
191+
192+
it('control: a route on a first-area entry keeps the first area', () => {
193+
renderAt('/apps/crm/opportunity');
194+
expect(areaButton('Sales')).toHaveAttribute('data-active', 'true');
195+
expect(navRow('Opportunities')).toHaveAttribute('data-active', 'true');
196+
expect(screen.queryByText('Cases')).not.toBeInTheDocument();
197+
});
198+
199+
it('keeps the first area when no entry of any area addresses the route', () => {
200+
renderAt('/apps/crm/dashboard/overview');
201+
expect(areaButton('Sales')).toHaveAttribute('data-active', 'true');
202+
expect(screen.getByText('Opportunities')).toBeInTheDocument();
203+
});
204+
205+
it('follows the route to the area holding the new page when the shown area addresses none of it', () => {
206+
renderAt('/apps/crm/opportunity');
207+
expect(areaButton('Sales')).toHaveAttribute('data-active', 'true');
208+
act(() => navigate('/apps/crm/case/record/42'));
209+
expect(areaButton('Service')).toHaveAttribute('data-active', 'true');
210+
expect(navRow('Cases')).toHaveAttribute('data-active', 'true');
211+
});
212+
213+
it("holds the reader's own area pick while the page is one the picked area addresses", () => {
214+
renderAt('/apps/crm/account');
215+
// Both areas address the account list; the earlier area is elected.
216+
expect(areaButton('Sales')).toHaveAttribute('data-active', 'true');
217+
fireEvent.click(screen.getByText('Service'));
218+
expect(areaButton('Service')).toHaveAttribute('data-active', 'true');
219+
act(() => navigate('/apps/crm/account/record/7'));
220+
expect(areaButton('Service')).toHaveAttribute('data-active', 'true');
221+
expect(navRow('Accounts (service)')).toHaveAttribute('data-active', 'true');
222+
});
223+
224+
it('holds a pick of an area that does not address the page until the route moves', () => {
225+
renderAt('/apps/crm/opportunity');
226+
fireEvent.click(screen.getByText('Service'));
227+
expect(areaButton('Service')).toHaveAttribute('data-active', 'true');
228+
act(() => navigate('/apps/crm/opportunity/record/1'));
229+
expect(areaButton('Sales')).toHaveAttribute('data-active', 'true');
230+
});
231+
});

0 commit comments

Comments
 (0)