diff --git a/.changeset/36347-cmd-b-docks-sidebar.md b/.changeset/36347-cmd-b-docks-sidebar.md new file mode 100644 index 00000000000..a6d4f699a8e --- /dev/null +++ b/.changeset/36347-cmd-b-docks-sidebar.md @@ -0,0 +1,12 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(app-shell): ⌘B / Ctrl+B does what the sidebar's expand / collapse button does + +Clause-②: no +Metadata-protocol: none + +From 768 px up, ⌘B / Ctrl+B is now a press on the console sidebar's expand / collapse button, on a window of any width. With the sidebar beside the page it collapses it; with the sidebar collapsed it puts it back beside the page; either way the browser remembers the choice for that side of 1280 px, as it does for the button, and a reload keeps it. On a window narrower than 1280 px, where the sidebar starts collapsed, ⌘B puts it beside the page and keeps it there. While the menu floats over the page, ⌘B puts it beside the page where it is. The key moves no focus, as a press on the button moves none. + +Before, ⌘B floated the menu over the page without changing the collapsed state. The temporary float now comes only from the window's left edge: rest the pointer there, or press there. Unchanged: Esc, a chosen entry and a press outside fold the float; the phone's drawer, which ⌘B still opens and closes; the 1280 px threshold; the sidebar's width. The button's tooltip keeps naming ⌘B, which now does what it says. diff --git a/docs/qa/platform-checklist/areas/platform-core.json b/docs/qa/platform-checklist/areas/platform-core.json index e9031e08b28..b43c584dd76 100644 --- a/docs/qa/platform-checklist/areas/platform-core.json +++ b/docs/qa/platform-checklist/areas/platform-core.json @@ -640,7 +640,7 @@ "title": "The built-in apps a stock boot REGISTERS (Setup / Account) render every merged-nav destination; app-level and entry-level gates are enforced, not errored — and Studio's deliberate absence is asserted, never hunted", "since": "v15", "status": "active", - "revision": 18, + "revision": 19, "priority": "P0", "surface": "browser", "personas": [ @@ -662,7 +662,7 @@ "steps": [ "as admin, GET /api/v1/meta/app?id=setup and extract every merged nav destination — Setup is a SHELL of empty group anchors (packages/platform-objects/src/apps/setup.app.ts: group_overview/apps/people_org/access_control/approvals/configuration/diagnostics/integrations/advanced) filled by SETUP_NAV_CONTRIBUTIONS (setup-nav.contributions.ts) plus capability-plugin contributions (plugin-security Positions/Permission Sets, plugin-sharing Sharing Rules/Record Shares, plugin-approvals, plugin-webhooks)", "GET /api/v1/meta/app with NO query first and record the names actually served — a stock boot answers exactly showcase_app, setup, account. Then GET /api/v1/meta/app?id=account (account.app.ts — Profile + Inbox/Security/Developer groups). ⚠️ GET /api/v1/meta/app?id=studio answers 200 {\"items\":[]} on every stock boot and that is the expected result (knownGap): record the absence as an assertion and move on — do NOT install @objectstack/studio to make the step runnable", - "as admin, hand-walk each destination in each app. At a window narrower than 1280 px a browser with no choice kept opens Setup and Account with the sidebar collapsed, and from 1280 px expanded (ui/packages/app-shell/src/layout/consoleSidebarRail.ts CONSOLE_SIDEBAR_RAIL_BELOW_WIDTH, ruling 7069868269 on objectstack#36112); a reader's own collapse or expand is kept per browser, on each side of that width. Collapsed, the sidebar is hidden, with no icon column (ruling 6973617688 on objectstack#35062): press the expand button at the page header's left edge to put it back beside the page before expanding any group — or press Ctrl/⌘+B, or rest the pointer on the window's left edge, to float the full menu over the page; the float folds back after each chosen entry, so float it again for the next destination. EXPAND every nav group first: some render collapsed by default — Setup's Advanced group and Account's Developer group declare `expanded: false` (packages/platform-objects/src/apps/setup.app.ts, account.app.ts), and QA run #24557 found Setup's Configuration group collapsed as well — so a walk that never expands them never reaches their entries. Then navigate, wait for render, SCREENSHOT FIRST, then read the DOM — assert no pageerror, no 'failed to load', no blank
, no 'no actions configured' placeholder", + "as admin, hand-walk each destination in each app. At a window narrower than 1280 px a browser with no choice kept opens Setup and Account with the sidebar collapsed, and from 1280 px expanded (ui/packages/app-shell/src/layout/consoleSidebarRail.ts CONSOLE_SIDEBAR_RAIL_BELOW_WIDTH, ruling 7069868269 on objectstack#36112); a reader's own collapse or expand is kept per browser, on each side of that width. Collapsed, the sidebar is hidden, with no icon column (ruling 6973617688 on objectstack#35062): press the expand button at the page header's left edge, or press Ctrl/⌘+B, which does the same (ruling 7074574380 on objectstack#36112), to put it back beside the page before expanding any group — or rest the pointer on the window's left edge to float the full menu over the page; the float folds back after each chosen entry, so float it again for the next destination. EXPAND every nav group first: some render collapsed by default — Setup's Advanced group and Account's Developer group declare `expanded: false` (packages/platform-objects/src/apps/setup.app.ts, account.app.ts), and QA run #24557 found Setup's Configuration group collapsed as well — so a walk that never expands them never reaches their entries. Then navigate, wait for render, SCREENSHOT FIRST, then read the DOM — assert no pageerror, no 'failed to load', no blank
, no 'no actions configured' placeholder", "Setup detail: confirm each settings URL entry (nav_settings_* → /apps/setup/system/settings/) opens the settings namespace form — the 11 namespaces of a stock single-posture boot, localization/company/branding/auth/access_policy/mail/sms/storage/ai/knowledge/lifecycle: the nav_settings_* entries of packages/platform-objects/src/apps/setup-nav.contributions.ts, plus nav_settings_branding, which packages/services/service-settings/src/settings-service-plugin.ts contributes only where no organization wall stands, and Users / Organization / Business Units / Teams / Sessions / OAuth Applications render. User preferences and identity links are not Setup destinations: open a user's record page, /_console/apps/setup/sys_user/record/ID (a row click on the Users list opens a side panel at ?recordId=, which is not that page: take the id from the row or the panel), and confirm the user page's Preferences and Linked Accounts tabs (packages/platform-objects/src/pages/sys-user.page.ts#SysUserDetailPage) render that user's rows", "Studio detail is NOT walked from here — the app is not registered on a stock boot (knownGap), so there is no merged nav to render. Its metadata:resource lists and component surfaces (App Builder, All Metadata Types, Packages, API Console, Flow Runs, Public Forms) are reached through the console surface at /_console/studio// and are covered by area studio-authoring. What THIS item asserts about Studio is the absence itself, per clause 6", "Account detail: confirm Profile (account:profile_card), Notifications (sys_inbox_message/mine), Approvals (nav_account_approvals, the approvals:inbox component, served as …/component/approvals/inbox — the Approvals Inbox, not the sys_approval_request grid; account.app.ts), Linked Accounts (sys_account), Active Sessions (sys_session/mine), API Keys (sys_api_key/mine), OAuth Applications (sys_oauth_application/mine) and Connect an Agent (nav_connect_agent) each render — 8 Account destinations and 47 Setup destinations for the admin on a stock single-org showcase boot, read from source after objectstack#34724 retired Setup › Packaged Actions (nav_packaged_actions; its switch moved onto the action in Studio); QA runs #32953 (at 5fb79bc0) and #33087 (at 8e3d4a54) read 48 before it (GET /api/v1/meta/app leaves, which match the nav source minus its gates). QA run #29877 read 46 at 589049b0, before Access policy (nav_settings_access_policy, the access_policy namespace) joined the Configuration group. Since QA run #28545's reading Setup's Packaged automation page retired under ADR-0146 D11, leaving Packaged Actions (nav_packaged_actions, automation:packaged-actions; #28785, itself retired by objectstack#34724), and its unfiltered Packages entry moved to Studio (#29547) (47 for #28927, 50 at eeec88d1 for QA run #28545, 48 re-measured at 3fd80337 for #28338, QA run #27481 read 44 and 8, QA run #24557 read 42 at 5b14b7f3, 45 on 2026-10-01, and #9453 recorded 43 and 7). Recount from the payload each run", @@ -828,6 +828,12 @@ "date": "2026-11-22", "change": "steps[2]: the threshold is 1280 px, not 1416 px, and it sets only where a browser with no choice kept starts — collapsed below it, expanded from it (ruling 7069868269 on #36112); the reader's own collapse or expand is kept per browser on each side, and the 'Keep sidebar open' switch is gone, so the walk docks the sidebar with the page header's expand button, or floats it with Ctrl/⌘+B or the window's left edge as before. The app bar named in revision 17 is gone from 768 px up (#36187). No clause changed. Read from source; not yet re-run by a QA run.", "ref": "#36112" + }, + { + "revision": 19, + "date": "2026-11-22", + "change": "steps[2]: Ctrl/⌘+B is a press on the expand / collapse button (ruling 7074574380 on #36112, which replaces the words '⌘B unchanged' of ruling 7069868269): it docks the collapsed sidebar beside the page as the reader's choice, a float included, and collapses a docked one; it no longer floats the menu, which floats only from the window's left edge. The walk is unchanged in substance. No clause changed. Read from source; not yet re-run by a QA run.", + "ref": "#36347" } ] }, diff --git a/ui/packages/app-shell/src/chrome/advertisedShortcuts.ts b/ui/packages/app-shell/src/chrome/advertisedShortcuts.ts index 2c494e79f03..777639e4ed5 100644 --- a/ui/packages/app-shell/src/chrome/advertisedShortcuts.ts +++ b/ui/packages/app-shell/src/chrome/advertisedShortcuts.ts @@ -16,9 +16,10 @@ * chat page's `⌘⇧O` / `⌘⇧S` are advertised by that page, so they are listed * only where that page is mounted. * - * Two advertisers sit beside a handler they do not own the code of: `⌘B` is - * the Shadcn `SidebarProvider`'s own listener (a synced primitive, see - * `ConsoleLayout`), and `Esc` is Radix's dismiss handler on every dialog and + * Two advertisers sit beside a handler they do not own the code of: `⌘B` is, + * on a phone, the Shadcn `SidebarProvider`'s own listener (a synced primitive; + * from 768 px up the console sidebar answers it, see `ConsoleLayout`), and + * `Esc` is Radix's dismiss handler on every dialog and * panel (see `KeyboardShortcutsDialog`). The pin * `KeyboardShortcutsDialog.wiredOnly-11674.test.tsx` fires every listed * entry's chord against the real handler, those two included, and fails on a diff --git a/ui/packages/app-shell/src/hooks/useResponsiveSidebar.ts b/ui/packages/app-shell/src/hooks/useResponsiveSidebar.ts index c73fd4d8958..dd71dafdbbb 100644 --- a/ui/packages/app-shell/src/hooks/useResponsiveSidebar.ts +++ b/ui/packages/app-shell/src/hooks/useResponsiveSidebar.ts @@ -7,14 +7,17 @@ * that side of the threshold, else expanded on a wide window and collapsed on * a narrow one (ruling 7069868269 on objectstack#36112). Collapsed, the * console's sidebar is hidden, and its full menu floats over the content from - * the window's left edge or ⌘B (ruling 6973617688 on objectstack#35062; - * `consoleSidebarRail.ts`). Must be called inside a SidebarProvider context. + * the window's left edge (ruling 6973617688 on objectstack#35062; + * `consoleSidebarRail.ts`); ⌘B / Ctrl+B is a press on the expand / collapse + * button (ruling 7074574380 on objectstack#36112), so it collapses and docks + * the sidebar as the reader's choice. Must be called inside a SidebarProvider + * context. * * It also keeps the reader's choices, each on its own side of the threshold: * an open or close on a wide window is the wide-window choice * (objectstack#28079), a close of the docked sidebar on a narrow window the - * narrow-window choice (the page header's expand button keeps the other - * half, `useConsoleSidebarRailPanel`). The float writes neither, and a state + * narrow-window choice (the page header's expand button and ⌘B keep the + * other half, `useConsoleSidebarRailPanel`). The float writes neither, and a state * this hook gives a window is not a choice. * @module */ diff --git a/ui/packages/app-shell/src/layout/ConsoleLayout.tsx b/ui/packages/app-shell/src/layout/ConsoleLayout.tsx index c6d92d5512a..48fdfe32386 100644 --- a/ui/packages/app-shell/src/layout/ConsoleLayout.tsx +++ b/ui/packages/app-shell/src/layout/ConsoleLayout.tsx @@ -41,7 +41,7 @@ import { useResponsiveSidebar } from '../hooks/useResponsiveSidebar.js'; import { usePhoneNavDrawerHistory } from './usePhoneNavDrawerHistory.js'; import { usePhoneViewport } from '../hooks/usePhoneViewport.js'; import { isAppDocsPath, isRecordPagePath } from './consoleRoutePaths.js'; -import { primeConsoleSidebarOpen } from './consoleSidebarRail.js'; +import { SIDEBAR_TOGGLE_CHORD, primeConsoleSidebarOpen } from './consoleSidebarRail.js'; import { useAiSurfaceEnabled } from '../hooks/useAiSurface.js'; import { servedObjectLabel } from '../hooks/servedObjectLabel.js'; import { useNavigationContext } from '../context/NavigationContext.js'; @@ -82,16 +82,18 @@ interface ConsoleLayoutProps { } /** - * `⌘B` / `Ctrl+B` toggles the sidebar. The listener is `SidebarProvider`'s own - * (`@object-ui/components`' synced Shadcn primitive, mounted by `AppShell`): - * it matches `b` with ⌘ or Ctrl, and a bare `B` does nothing. That code is not - * ours to edit, so the shortcut is advertised from inside the provider it - * belongs to, by {@link ConsoleLayoutInner} (objectui#11674). + * `⌘B` / `Ctrl+B` toggles the sidebar: it matches `b` with ⌘ or Ctrl, and a + * bare `B` does nothing. From 768 px up the console sidebar answers it as a + * press on its expand / collapse button (`useConsoleSidebarRailPanel`, ruling + * 7074574380 on objectstack#36112); on a phone the listener is + * `SidebarProvider`'s own (`@object-ui/components`' synced Shadcn primitive, + * mounted by `AppShell`). The shortcut is advertised from inside that + * provider, by {@link ConsoleLayoutInner} (objectui#11674). */ const TOGGLE_SIDEBAR_SHORTCUT: AdvertisedShortcut = { id: 'toggle-sidebar', group: 'navigation', - chord: { key: 'b', mod: true }, + chord: SIDEBAR_TOGGLE_CHORD, label: (t: ShortcutLabelTranslate) => t('console.shortcuts.toggleSidebar'), }; diff --git a/ui/packages/app-shell/src/layout/LocalizedSidebarTrigger.tsx b/ui/packages/app-shell/src/layout/LocalizedSidebarTrigger.tsx index 30cbb379a21..5868169d53d 100644 --- a/ui/packages/app-shell/src/layout/LocalizedSidebarTrigger.tsx +++ b/ui/packages/app-shell/src/layout/LocalizedSidebarTrigger.tsx @@ -9,24 +9,21 @@ import { useSidebar, } from '@object-ui/components'; import { useObjectTranslation } from '@object-ui/i18n'; -import { shortcutKeycaps, type ShortcutChord } from '../chrome/advertisedShortcuts.js'; +import { shortcutKeycaps } from '../chrome/advertisedShortcuts.js'; +import { SIDEBAR_TOGGLE_CHORD } from './consoleSidebarRail.js'; /** - * The chord `SidebarProvider`'s own listener answers to (⌘B / Ctrl+B). It is - * the same chord `ConsoleLayout` advertises to the keyboard-shortcuts dialog; - * the tooltip draws it with the dialog's keycaps so the two never spell it - * differently. - */ -const TOGGLE_SIDEBAR_CHORD: ShortcutChord = { key: 'b', mod: true }; - -/** - * The shell's one sidebar trigger (objectui#12429). It lives in the app bar's - * left slot at every width: below the Shadcn mobile breakpoint it opens and - * closes the drawer, above it it collapses the sidebar and expands it again. - * In the console a collapsed sidebar is hidden, and the trigger floats its - * menu over the content instead of expanding it (objectstack#35062, - * `consoleSidebarRail`). `aria-expanded` follows whichever of the two states - * the click toggles, and the tooltip names the keyboard shortcut. + * The shell's sidebar trigger (objectui#12429): below the Shadcn mobile + * breakpoint it opens and closes the drawer, above it it collapses the + * sidebar and expands it again. In the console a collapsed sidebar is hidden, + * and the trigger docks it beside the content again as the reader's choice + * (ruling 7069868269 on objectstack#36112, `consoleSidebarRail`). + * `aria-expanded` follows whichever of the two states the click toggles. + * + * The tooltip names ⌘B / Ctrl+B ({@link SIDEBAR_TOGGLE_CHORD}), drawn with + * the keyboard-shortcuts dialog's keycaps so the two never spell it + * differently: the chord is a press on this button (ruling 7074574380 on + * objectstack#36112). */ export const LocalizedSidebarTrigger = React.forwardRef< React.ElementRef, @@ -64,7 +61,7 @@ export const LocalizedSidebarTrigger = React.forwardRef< data-testid="sidebar-trigger-shortcut" className="pointer-events-none inline-flex h-5 select-none items-center gap-0.5 rounded border bg-muted px-1.5 font-mono text-xs font-medium text-muted-foreground" > - {shortcutKeycaps(TOGGLE_SIDEBAR_CHORD).join('')} + {shortcutKeycaps(SIDEBAR_TOGGLE_CHORD).join('')} diff --git a/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx b/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx index 088aaf58383..88de4217b7b 100644 --- a/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx +++ b/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx @@ -934,7 +934,8 @@ export function UnifiedSidebar({ activeAppName, onAppChange, railOverlay = false {/* objectstack#35062 — the window's left edge while the sidebar is hidden: resting the pointer on it, or a press, floats the menu. For - the pointer only; the keyboard has the app bar's trigger and ⌘B. */} + the pointer only; the keyboard has the page header's expand button + and ⌘B, which dock the sidebar. */} {railPanel.edgeZoneProps && (
screen.queryByTestId('console-sidebar-edge'); const trigger = () => within(screen.getByTestId('app-bar')).getByRole('button', { name: 'Toggle sidebar' }); const keepOpen = () => screen.queryByTestId('sidebar-keep-open'); const narrowChoice = () => readWorkspacePreference(CONSOLE_SIDEBAR_NARROW_OPEN_PREFERENCE, 'user'); -/** ⌘B, which the provider's listener answers on the window. */ -const commandB = () => fireEvent.keyDown(window, { key: 'b', metaKey: true }); +/** + * ⌘B where a real key press lands: on the focused element, else the body. It + * bubbles through the document, where the console's sidebar answers it, to + * the window, where the provider's own listener sits. + */ +const commandB = (init: KeyboardEventInit = { metaKey: true }) => + fireEvent.keyDown(document.activeElement ?? document.body, { key: 'b', ...init }); const tokens = (el: Element) => el.className.split(/\s+/).filter(Boolean); const sidebarCookie = () => /(?:^|;\s*)sidebar_state=(\w+)/.exec(document.cookie)?.[1]; @@ -286,7 +294,7 @@ afterEach(() => { }); describe('a collapsed console sidebar is hidden, with no icon column (objectstack#35062)', () => { - it('collapsed by hand at 1600 px it takes no width and nothing in it is reachable; ⌘B floats it, the expand button docks it again, after a reload too', () => { + it('collapsed by hand at 1600 px it takes no width and nothing in it is reachable; the expand button docks it again, after a reload too', () => { renderShell(1600); expectDocked(); expect(keepOpen(), 'no "Keep sidebar open" (objectstack#36112)').toBeNull(); @@ -295,15 +303,6 @@ describe('a collapsed console sidebar is hidden, with no icon column (objectstac expectHidden(); expect(readWideWindowOpen()).toBe(false); - // ⌘B floats the menu on a hand collapse, and changes nothing the reader chose. - commandB(); - expectFloat(); - expect(keepOpen()).toBeNull(); - expect(readWideWindowOpen()).toBe(false); - expect(sidebarCookie()).toBe('false'); - commandB(); - expectHidden(); - // The way back beside the content: the expand button. fireEvent.click(trigger()); expectDocked(); @@ -484,22 +483,7 @@ describe('the left edge floats the full menu over the content (objectstack#35062 }); }); -describe('⌘B floats the collapsed menu, the expand button docks it, and the keyboard walks it (objectstack#35062, objectstack#36112)', () => { - it('collapsed by hand at 1600 px, ⌘B floats it and moves focus in; Esc folds it and focus goes back to the trigger', () => { - renderShell(1600); - fireEvent.click(trigger()); - expectHidden(); - act(() => trigger().focus()); - commandB(); - expectFloat(); - expect(panel(), 'focus moves into the floated menu').toContainElement(document.activeElement as HTMLElement); - - fireEvent.keyDown(document.activeElement!, { key: 'Escape' }); - expectHidden(); - expect(document.activeElement, 'focus goes back to the trigger').toBe(trigger()); - expect(readWideWindowOpen()).toBe(false); - }); - +describe('the expand button docks it, and the keyboard walks it (objectstack#35062, objectstack#36112)', () => { it('at 1024 px, the expand button docks it even when React renders between the capture phase and the trigger’s own click handler', () => { renderShell(1024); expectHidden(); @@ -521,58 +505,177 @@ describe('⌘B floats the collapsed menu, the expand button docks it, and the ke expect(narrowChoice()).toBe('on'); }); - it('collapsed by hand at 1600 px, ⌘B floats it and folds it again', () => { + it('an entry chosen from the keyboard in a float navigates, folds it, and gives focus back to the trigger', () => { + renderShell(1024); + act(() => trigger().focus()); + fireEvent.click(edge()!); + expectFloat(); + const entry = within(panel()).getByRole('link', { name: 'Contacts' }); + act(() => entry.focus()); + // A keyboard activation's click counts no presses. + fireEvent.click(entry, { detail: 0 }); + expect(screen.getByTestId('route')).toHaveTextContent('/apps/crm/contact'); + expectHidden(); + expect(document.activeElement).toBe(trigger()); + }); + + it('collapsing an expanded sidebar from the keyboard gives focus inside it to the trigger', () => { renderShell(1600); - commandB(); + act(() => within(panel()).getByRole('link', { name: 'Accounts' }).focus()); + commandB({ ctrlKey: true }); expectHidden(); - commandB(); - expectFloat(); - expect(sidebarCookie()).toBe('false'); + expect(document.activeElement).toBe(trigger()); + }); +}); + +describe('⌘B / Ctrl+B is a press on the expand / collapse button (objectstack#36347, ruling 7074574380 on objectstack#36112)', () => { + it('at 1600 px ⌘B collapses the docked sidebar and docks it again, as the reader’s choice, after a reload too', () => { + renderShell(1600); + expectDocked(); commandB(); expectHidden(); expect(readWideWindowOpen()).toBe(false); + expect(sidebarCookie()).toBe('false'); + reload(1600); + expectHidden(); + + commandB(); + expectDocked(); + expect(readWideWindowOpen()).toBe(true); + expect(sidebarCookie()).toBe('true'); + reload(1600); + expectDocked(); }); - it('at 1024 px ⌘B floats it and moves focus in; Esc folds it and focus goes back to the trigger', () => { + it('at 1024 px ⌘B docks the sidebar collapsed by default and keeps the narrow-window choice expanded, after a reload too; ⌘B again collapses it', () => { renderShell(1024); - act(() => trigger().focus()); + expectHidden(); commandB(); - expectFloat(); - expect(panel(), 'focus moves into the floated menu').toContainElement(document.activeElement as HTMLElement); - expect(narrowChoice(), 'the float is not the reader’s choice').toBeUndefined(); + expectDocked(); + expect(narrowChoice()).toBe('on'); + expect(readWideWindowOpen(), 'the wide-window choice is not touched').toBeUndefined(); + reload(1024); + expectDocked(); - fireEvent.keyDown(document.activeElement!, { key: 'Escape' }); + commandB({ ctrlKey: true }); + expectHidden(); + expect(narrowChoice()).toBe('off'); + reload(1024); expectHidden(); - expect(document.activeElement, 'focus goes back to the trigger').toBe(trigger()); }); - it('at 1024 px ⌘B floats it and folds it again', () => { - renderShell(1024); - commandB(); - expectFloat(); - commandB(); + it('on either window, collapsed or docked, ⌘B leaves what a press on the button leaves', () => { + for (const width of [1600, 1024]) { + for (const [start, ends] of [ + [reloadCollapsed, 'expanded'], + [reloadDocked, 'collapsed'], + ] as const) { + start(width); + fireEvent.click(trigger()); + const byButton = readChoices(); + start(width); + commandB(); + expect(readChoices(), `${width} px, from ${start.name}`).toEqual(byButton); + expect(byButton.state, `${width} px, from ${start.name}`).toBe(ends); + } + } + }); + + it('collapsed by hand at 1600 px, ⌘B docks it and moves no focus', () => { + renderShell(1600); + fireEvent.click(trigger()); expectHidden(); - expect(narrowChoice()).toBeUndefined(); + act(() => trigger().focus()); + commandB(); + expectDocked(); + expect(document.activeElement, 'focus stays where it was, as with a press').toBe(trigger()); }); - it('an entry chosen from the keyboard navigates, folds it, and gives focus back to the trigger', () => { + it('while the menu floats from the left edge, ⌘B docks it where it is, on either window, and a reload keeps it', () => { + // At 1024 px, collapsed by default: the float docks as the narrow-window choice. renderShell(1024); act(() => trigger().focus()); + fireEvent.click(edge()!); + expectFloat(); commandB(); - const entry = within(panel()).getByRole('link', { name: 'Contacts' }); - act(() => entry.focus()); - // A keyboard activation's click counts no presses. - fireEvent.click(entry, { detail: 0 }); - expect(screen.getByTestId('route')).toHaveTextContent('/apps/crm/contact'); - expectHidden(); - expect(document.activeElement).toBe(trigger()); - }); + expectDocked(); + expect(narrowChoice()).toBe('on'); + expect(sidebarCookie()).toBe('true'); + expect(document.activeElement, 'focus does not move').toBe(trigger()); + reload(1024); + expectDocked(); - it('collapsing an expanded sidebar from the keyboard gives focus inside it to the trigger', () => { + // At 1600 px, collapsed by hand: the float docks as the wide-window choice. + cleanup(); + localStorage.clear(); renderShell(1600); - act(() => within(panel()).getByRole('link', { name: 'Accounts' }).focus()); - fireEvent.keyDown(window, { key: 'b', ctrlKey: true }); - expectHidden(); - expect(document.activeElement).toBe(trigger()); + fireEvent.click(trigger()); + vi.useFakeTimers(); + hoverEdge(SIDEBAR_FLOAT_OPEN_DELAY_MS); + expectFloat(); + expect(readWideWindowOpen()).toBe(false); + commandB(); + expectDocked(); + expect(readWideWindowOpen()).toBe(true); + expect(sidebarCookie()).toBe('true'); + // Docked, the pointer moving away folds nothing. + fireEvent.pointerMove(screen.getByText('The page'), { pointerType: 'mouse' }); + act(() => { + vi.advanceTimersByTime(SIDEBAR_FLOAT_CLOSE_DELAY_MS * 2); + }); + expectDocked(); + vi.useRealTimers(); + reload(1600); + expectDocked(); + }); + + it('one ⌘B is one press: the provider’s own listener on the window does not also take it from 768 px up', () => { + const seen: string[] = []; + const onWindow = (event: KeyboardEvent) => { + if (event.key === 'b') seen.push(event.type); + }; + window.addEventListener('keydown', onWindow); + try { + renderShell(1600); + commandB(); + expectHidden(); + expect(seen, 'the chord does not reach the window').toEqual([]); + + // On a phone the provider's listener opens the drawer, as before. + cleanup(); + renderShell(700); + commandB(); + expect(seen).toEqual(['keydown']); + expect(document.querySelector('[data-mobile="true"][data-sidebar="sidebar"]')).not.toBeNull(); + } finally { + window.removeEventListener('keydown', onWindow); + } }); }); + +/** The state and the kept choices a press leaves: what a reload reads. */ +function readChoices() { + return { + state: sidebarRoot()?.getAttribute('data-state'), + rail: panel().getAttribute('data-console-rail'), + wide: readWideWindowOpen(), + narrow: narrowChoice(), + cookie: sidebarCookie(), + }; +} + +/** A fresh browser at `width` whose sidebar starts collapsed. */ +function reloadCollapsed(width: number) { + localStorage.clear(); + document.cookie = 'sidebar_state=; path=/; max-age=0'; + if (width >= 1280) writeWideWindowOpen(false); + return reload(width); +} + +/** A fresh browser at `width` whose sidebar starts docked. */ +function reloadDocked(width: number) { + localStorage.clear(); + document.cookie = 'sidebar_state=; path=/; max-age=0'; + if (width < 1280) writeWorkspacePreference(CONSOLE_SIDEBAR_NARROW_OPEN_PREFERENCE, 'user', 'on'); + return reload(width); +} diff --git a/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.railOverlay-27593.test.tsx b/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.railOverlay-27593.test.tsx index 5598d3c287a..1962859fc19 100644 --- a/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.railOverlay-27593.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.railOverlay-27593.test.tsx @@ -2,18 +2,19 @@ /** * UnifiedSidebar — on a narrow window (below 1280 px, objectstack#36112) the - * console sidebar starts collapsed, and ⌘B floats its menu OVER the content - * (objectstack#27593). Collapsed, the sidebar is hidden, with no icon column + * console sidebar starts collapsed, and the window's left edge floats its menu + * OVER the content (objectstack#27593; ⌘B docks it instead, ruling 7074574380 + * on objectstack#36112). Collapsed, the sidebar is hidden, with no icon column * (ruling 6973617688 on objectstack#35062, which replaced the icon rail; the * edge, the reader's own collapse and focus are pinned in * `UnifiedSidebar.hiddenCollapse-35062.test.tsx`). * * - At 1024 px the sidebar mounts collapsed and hidden; at 1440 px nothing * changes; at 700 px the phone drawer still mounts. - * - ⌘B floats the menu: the panel takes the expanded width above the page - * while the in-flow gap keeps no width, so the content beside it does not - * move. Resting the pointer on the window's left edge floats it too (the - * ruling's change to "hover alone does not expand"). + * - A press on the window's left edge floats the menu: the panel takes the + * expanded width above the page while the in-flow gap keeps no width, so + * the content beside it does not move. Resting the pointer on the edge + * floats it too (the ruling's change to "hover alone does not expand"). * - A navigation choice, a press outside it or Esc folds it again; a press in * an entry's own menu (a portal) does not, and a sidebar trigger toggles it * once. @@ -26,8 +27,8 @@ * a resize and a reload (objectstack#28079). * - A group declared `expanded: false` stays collapsed, with its count, in the * floated menu as in the expanded sidebar, and its disclosure opens it to - * the pointer and the keyboard (objectstack#32156 listed its entries in the - * icon rail, which is gone). + * the pointer, and to the keyboard in the sidebar ⌘B docks + * (objectstack#32156 listed its entries in the icon rail, which is gone). * * The test DOM computes no Tailwind and no layout, so widths are read as the * class that sets them; the rendered widths are measured in a browser on the @@ -223,9 +224,9 @@ const appBarTrigger = () => within(screen.getByTestId('app-bar')).getByRole('but const hiddenTooltip = () => Array.from(document.querySelectorAll('[role="tooltip"]')).find((el) => el.closest('[hidden]')); -/** The collapsed sidebar's menu, floated over the content by ⌘B. */ -function expandRail() { - fireEvent.keyDown(window, { key: 'b', metaKey: true }); +/** The collapsed sidebar's menu, floated over the content by a press on the window's left edge. */ +function floatRail() { + fireEvent.click(screen.getByTestId('console-sidebar-edge')); expect(sidebarRoot()).toHaveAttribute('data-state', 'expanded'); expect(panel()).toHaveAttribute('data-console-rail', 'overlay'); } @@ -267,9 +268,9 @@ describe('the narrow window’s collapsed sidebar (objectstack#27593, objectstac expect(keepOpen()).toBeNull(); }); - it('⌘B floats the menu over the content; the gap keeps no width', () => { + it('a press on the window’s left edge floats the menu over the content; the gap keeps no width', () => { renderShell(1024); - expandRail(); + floatRail(); // The panel takes the expanded width above the page… for (const token of RAIL_OVERLAY_PANEL.split(' ')) expect(tokens(panel())).toContain(token); @@ -297,7 +298,7 @@ describe('the narrow window’s collapsed sidebar (objectstack#27593, objectstac // Ruling 6973617688 on objectstack#35062 changes this pin's "hover alone // does not expand": with the icon rail gone, the left edge floats the menu - // on hover, as ⌘B does. + // on hover, as a press on it does. fireEvent.pointerEnter(screen.getByTestId('console-sidebar-edge'), { pointerType: 'mouse' }); act(() => { vi.advanceTimersByTime(SIDEBAR_FLOAT_OPEN_DELAY_MS); @@ -311,7 +312,7 @@ describe('the narrow window’s collapsed sidebar (objectstack#27593, objectstac it('choosing a navigation item folds it', () => { renderShell(1024); - expandRail(); + floatRail(); fireEvent.click(within(panel()).getByRole('link', { name: 'Contacts' })); expectRail(); expect(screen.getByTestId('route')).toHaveTextContent('/apps/crm/contact'); @@ -319,18 +320,18 @@ describe('the narrow window’s collapsed sidebar (objectstack#27593, objectstac it('a navigation from anywhere else folds it', () => { renderShell(1024); - expandRail(); + floatRail(); act(() => navigateTo('/apps/crm/account')); expectRail(); }); it('a press outside folds it; a sidebar trigger toggles it exactly once, and pressed again docks it', () => { renderShell(1024); - expandRail(); + floatRail(); fireEvent.pointerDown(screen.getByText('The page')); expectRail(); - expandRail(); + floatRail(); const trigger = within(screen.getByTestId('app-bar')).getByRole('button', { name: 'Toggle sidebar' }); fireEvent.pointerDown(trigger); fireEvent.click(trigger); @@ -344,7 +345,7 @@ describe('the narrow window’s collapsed sidebar (objectstack#27593, objectstac it('a press in an entry’s own menu, drawn in a portal, does not fold it', () => { renderShell(1024); - expandRail(); + floatRail(); fireEvent.keyDown(within(panel()).getByRole('button', { name: 'More actions for Accounts' }), { key: 'Enter' }); const item = screen.getAllByRole('menuitem')[0]; expect(panel()).not.toContainElement(item); @@ -354,11 +355,9 @@ describe('the narrow window’s collapsed sidebar (objectstack#27593, objectstac it('Esc folds it; an Esc another layer already handled does not', () => { renderShell(1024); - // Floated by a press on the edge, which moves no focus: ⌘B's float - // focuses an entry, whose hidden tooltip would take the Esc - // (objectstack#28078, below). - fireEvent.click(screen.getByTestId('console-sidebar-edge')); - expect(panel()).toHaveAttribute('data-console-rail', 'overlay'); + // Floated by a press on the edge, which moves no focus (focus on an + // entry opens its hidden tooltip, objectstack#28078, below). + floatRail(); const handled = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }); handled.preventDefault(); act(() => { @@ -373,7 +372,7 @@ describe('the narrow window’s collapsed sidebar (objectstack#27593, objectstac describe('one Esc folds it wherever the pointer or focus is inside it (objectstack#28078)', () => { it('with focus on an entry, whose hidden tooltip is open', () => { renderShell(1024); - expandRail(); + floatRail(); const entry = within(panel()).getByRole('link', { name: 'Contacts' }); act(() => entry.focus()); expect(hiddenTooltip(), 'the entry opened its hidden tooltip').toBeDefined(); @@ -383,7 +382,7 @@ describe('the narrow window’s collapsed sidebar (objectstack#27593, objectstac it('with the pointer on an entry', async () => { renderShell(1024); - expandRail(); + floatRail(); fireEvent.pointerMove(within(panel()).getByRole('link', { name: 'Accounts' }), { pointerType: 'mouse' }); await act(() => new Promise((resolve) => setTimeout(resolve, 10))); expect(hiddenTooltip(), 'the entry opened its hidden tooltip').toBeDefined(); @@ -393,7 +392,7 @@ describe('the narrow window’s collapsed sidebar (objectstack#27593, objectstac it('an entry’s open menu still takes the Esc first', () => { renderShell(1024); - expandRail(); + floatRail(); const entry = within(panel()).getByRole('link', { name: 'Accounts' }); act(() => entry.focus()); fireEvent.keyDown(within(panel()).getByRole('button', { name: 'More actions for Accounts' }), { key: 'Enter' }); @@ -510,7 +509,7 @@ describe('a collapsed group in the folded sidebar (objectstack#32156)', () => { // objectstack#32156 listed the group's entries in the icon rail. With no // rail (ruling 6973617688 on objectstack#35062) the hidden panel is inert, // and the entries are reached through the floated menu. - expandRail(); + floatRail(); expect(disclosure()).toHaveAttribute('aria-expanded', 'false'); expect(groupEntry('OAuth Applications')).toBeNull(); fireEvent.click(disclosure()); @@ -519,16 +518,14 @@ describe('a collapsed group in the folded sidebar (objectstack#32156)', () => { expect(screen.getByTestId('route')).toHaveTextContent('/apps/crm/oauth_app'); }); - it('at 1024 px the keyboard floats the menu with ⌘B, opens the group and Enter opens an entry', async () => { + it('at 1024 px the keyboard docks the sidebar with ⌘B, opens the group and Enter opens an entry; the sidebar stays docked', async () => { const user = userEvent.setup(); renderShell(1024, COLLAPSED_GROUP_NAVIGATION); act(() => appBarTrigger().focus()); - fireEvent.keyDown(window, { key: 'b', metaKey: true }); - expect(panel()).toHaveAttribute('data-console-rail', 'overlay'); - expect(panel(), '⌘B moves focus into the floated menu').toContainElement( - document.activeElement as HTMLElement, - ); - for (let press = 0; press < 8 && document.activeElement !== disclosure(); press++) { + fireEvent.keyDown(appBarTrigger(), { key: 'b', metaKey: true }); + expectDocked(); + expect(document.activeElement, '⌘B moves no focus, as a press on the button').toBe(appBarTrigger()); + for (let press = 0; press < 12 && document.activeElement !== disclosure(); press++) { await user.tab(); } expect(document.activeElement, 'Tab reaches the group’s disclosure').toBe(disclosure()); @@ -540,7 +537,7 @@ describe('a collapsed group in the folded sidebar (objectstack#32156)', () => { expect(document.activeElement, 'Tab reaches the entry').toBe(groupEntry('API Keys')); await user.keyboard('{Enter}'); expect(screen.getByTestId('route')).toHaveTextContent('/apps/crm/api_key'); - expectRail(); + expectDocked(); }); it('a wide window collapsed by hand is hidden too: no entry of the group is reachable', () => { @@ -554,14 +551,14 @@ describe('a collapsed group in the folded sidebar (objectstack#32156)', () => { it('the floated menu keeps the group collapsed, with its count, every time it floats', () => { renderShell(1024, COLLAPSED_GROUP_NAVIGATION); - expandRail(); + floatRail(); expect(disclosure()).toHaveAttribute('aria-expanded', 'false'); expect(disclosure()).toHaveTextContent('2'); expect(groupEntry('API Keys')).toBeNull(); fireEvent.keyDown(document.body, { key: 'Escape' }); expectRail(); - expandRail(); + floatRail(); expect(disclosure()).toHaveAttribute('aria-expanded', 'false'); expect(groupEntry('API Keys')).toBeNull(); }); diff --git a/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.recentThisApp-36112.test.tsx b/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.recentThisApp-36112.test.tsx index d41327e7b47..c2dde7ee9c3 100644 --- a/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.recentThisApp-36112.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.recentThisApp-36112.test.tsx @@ -186,8 +186,9 @@ describe('the sidebar’s Recent lists this app’s items (objectstack#36112)', it('the phone drawer is unchanged: it lists every app’s entries', () => { recent.items = [HR_RECORD, CRM_RECORD]; renderSidebar(700); - // The drawer is drawn on demand: open it as the phone's trigger does (the provider's toggle, ⌘B). - fireEvent.keyDown(window, { key: 'b', metaKey: true }); + // The drawer is drawn on demand: open it as the phone's trigger does (the + // provider's toggle, which answers ⌘B on a phone). + fireEvent.keyDown(document.body, { key: 'b', metaKey: true }); expect(document.querySelector('[data-mobile="true"][data-sidebar="sidebar"]')).not.toBeNull(); expect(recentEntries()).toEqual(['Jane Doe', 'Acme Corporation']); }); diff --git a/ui/packages/app-shell/src/layout/consoleSidebarRail.ts b/ui/packages/app-shell/src/layout/consoleSidebarRail.ts index a0b28815983..a8a20742c48 100644 --- a/ui/packages/app-shell/src/layout/consoleSidebarRail.ts +++ b/ui/packages/app-shell/src/layout/consoleSidebarRail.ts @@ -11,7 +11,9 @@ * objectstack#35062: one collapsed look at 768 px and up). The sidebar's * collapse button and, while it is collapsed, the page header's expand button * are the one control (ruling 7069868269 on objectstack#36112): each press is - * the reader's choice, and this browser keeps it. + * the reader's choice, and this browser keeps it. ⌘B / Ctrl+B is a press on + * that control (ruling 7074574380 on objectstack#36112): it collapses the + * docked sidebar and docks a collapsed one, a floated one included. * * Which state a window starts in is that choice, kept separately for a wide * window ({@link CONSOLE_SIDEBAR_RAIL_BELOW_WIDTH} and up) and a narrow one @@ -19,10 +21,10 @@ * starts expanded and a narrow one collapsed. * * Collapsed, the full menu, with its labels and groups, floats over the - * content without changing what the reader chose: after the pointer rests on - * the window's left edge, after a press on that edge, and from ⌘B. A pointer - * that floated it folds it back by moving away; a navigation choice, a press - * outside it or Esc folds it from any of them. + * content without changing what the reader chose, from the window's left edge + * only: after the pointer rests on it, or after a press on it. A pointer that + * floated it folds it back by moving away; a navigation choice, a press + * outside it or Esc folds it either way. * * `useResponsiveSidebar` gives each window its state as it loads and as it * crosses the width, and keeps the reader's choices; `UnifiedSidebar` draws @@ -41,6 +43,7 @@ import { } from 'react'; import { useLocation } from 'react-router-dom'; import { cn, useIsViewportBelow, useSidebar } from '@object-ui/components'; +import type { ShortcutChord } from '../chrome/advertisedShortcuts.js'; import { defineWorkspacePreference, readWorkspacePreference, @@ -189,6 +192,22 @@ function writeSidebarStateCookie(open: boolean): void { document.cookie = `${SIDEBAR_STATE_COOKIE}=${open}; path=/; max-age=${SIDEBAR_STATE_COOKIE_MAX_AGE}`; } +/** + * ⌘B / Ctrl+B: the chord of the sidebar primitive's own listener + * (`SIDEBAR_KEYBOARD_SHORTCUT` in `@object-ui/components`' `ui/sidebar.tsx`, + * which matches `b` with ⌘ or Ctrl). From the phone breakpoint up the + * console's sidebar answers it itself, as a press on its expand / collapse + * button ({@link useConsoleSidebarRailPanel}); on a phone, and where the + * console's collapse is off, the primitive's listener toggles the sidebar. + * The trigger's tooltip and the keyboard-shortcuts dialog draw this chord. + */ +export const SIDEBAR_TOGGLE_CHORD: ShortcutChord = { key: 'b', mod: true }; + +/** Does this key press carry {@link SIDEBAR_TOGGLE_CHORD}, as the primitive's listener matches it? */ +function isSidebarToggleChord(event: KeyboardEvent): boolean { + return event.key === SIDEBAR_TOGGLE_CHORD.key && (event.metaKey || event.ctrlKey); +} + /** * The phone breakpoint (`useIsMobile`'s 768 px in `@object-ui/components`): * below it the primitive's drawer takes over and the fold stays off. Read @@ -331,19 +350,8 @@ function sidebarTrigger(): HTMLElement | null { ); } -/** Where focus lands in the float: the entry of the page in view, else the first entry. */ -function floatFocusTarget(root: HTMLElement | null): HTMLElement | null { - const content = root?.querySelector('[data-sidebar="content"]'); - if (!content) return null; - return ( - content.querySelector('[data-sidebar="menu-button"][data-active="true"]') ?? - content.querySelector('a[href], button:not([disabled])') - ); -} - - -/** What floated the menu: the pointer resting on the edge, a press on it, or ⌘B. */ -type FloatOpener = 'hover' | 'press' | 'command'; +/** What floated the menu: the pointer resting on the window's left edge, or a press on it. */ +type FloatOpener = 'hover' | 'press'; /** * What folded it: a press outside it; Esc; a link chosen in it by keyboard (or @@ -383,18 +391,20 @@ export interface ConsoleSidebarRailPanel { * How the console's collapsed sidebar behaves. Collapsed from 768 px up, it is * hidden and inert, and an 8 px strip at the window's left edge floats the * menu over the content: after the pointer rests there - * ({@link SIDEBAR_FLOAT_OPEN_DELAY_MS}), at once on a press. ⌘B floats it too, - * whichever window it collapsed on (ruling 6973617688 on objectstack#35062), - * and moves focus into it. Floating changes nothing the reader chose: the - * kept choices and the cookie keep the collapsed state, so a reload comes back - * collapsed. The page header's expand button docks the sidebar instead, as the - * reader's choice (ruling 7069868269 on objectstack#36112): on a narrow window - * it keeps the narrow-window choice expanded, ahead of the provider's toggle. - * A float the pointer opened folds once the pointer has been away from it for - * {@link SIDEBAR_FLOAT_CLOSE_DELAY_MS} (not while a menu or dialog is open over - * the page); a navigation choice, a press outside it or Esc folds any float. - * Focus inside a sidebar that hides goes back where it came from, or to the - * trigger, unless a pointer folded it. `sidebarRef` is the sidebar's root (the + * ({@link SIDEBAR_FLOAT_OPEN_DELAY_MS}), at once on a press. Floating changes + * nothing the reader chose: the kept choices and the cookie keep the collapsed + * state, so a reload comes back collapsed. The page header's expand button + * docks the sidebar instead, as the reader's choice (ruling 7069868269 on + * objectstack#36112): on a narrow window it keeps the narrow-window choice + * expanded, ahead of the provider's toggle. ⌘B / Ctrl+B is a press on the + * expand / collapse button, on either window (ruling 7074574380 on + * objectstack#36112): it collapses the docked sidebar, docks the hidden one, + * and docks a float too, keeping it where it is; like a press, it moves no + * focus. A float the pointer opened folds once the pointer has been away from + * it for {@link SIDEBAR_FLOAT_CLOSE_DELAY_MS} (not while a menu or dialog is + * open over the page); a navigation choice, a press outside it or Esc folds + * any float. Focus inside a sidebar that hides goes to the trigger, unless a + * pointer folded it. `sidebarRef` is the sidebar's root (the * primitive's `data-collapsible` element). Inside the sidebar provider and a * router. */ @@ -402,7 +412,7 @@ export function useConsoleSidebarRailPanel( rail: ConsoleSidebarRail, sidebarRef: RefObject, ): ConsoleSidebarRailPanel { - const { open, setOpen } = useSidebar(); + const { open, setOpen, toggleSidebar } = useSidebar(); const { enabled, desktop, railMode, wide, narrowOpen, setNarrowOpen } = rail; const location = useLocation(); @@ -411,26 +421,19 @@ export function useConsoleSidebarRailPanel( // it (below). const width: FloatWidth = wide ? 'wide' : 'narrow'; const [floatOn, setFloatOn] = useState(null); - // The reader's own toggle while the sidebar is hidden by hand (below): the - // open it brings is a float. - const [toggleFloats, setToggleFloats] = useState(null); - if (toggleFloats !== null && open) { - setToggleFloats(null); - if (desktop && !railMode && floatOn === null && toggleFloats === width) setFloatOn(toggleFloats); - } if (floatOn !== null && (!open || !desktop || floatOn !== width)) setFloatOn(null); const overlayOpen = desktop && open && (railMode || floatOn === width); const hidden = desktop && !open; - const hiddenByHand = hidden && !railMode; const setOpenRef = useRef(setOpen); + const toggleSidebarRef = useRef(toggleSidebar); + const floatOnRef = useRef(floatOn); const overlayOpenRef = useRef(overlayOpen); const hiddenRef = useRef(hidden); const railModeRef = useRef(railMode); const widthRef = useRef(width); const openedBy = useRef(null); const closedBy = useRef(null); - const returnFocus = useRef(null); const openTimer = useRef | undefined>(undefined); const closeTimer = useRef | undefined>(undefined); // The press and the pointer move that last landed in the sidebar's React @@ -441,6 +444,8 @@ export function useConsoleSidebarRailPanel( useLayoutEffect(() => { setOpenRef.current = setOpen; + toggleSidebarRef.current = toggleSidebar; + floatOnRef.current = floatOn; overlayOpenRef.current = overlayOpen; hiddenRef.current = hidden; railModeRef.current = railMode; @@ -465,40 +470,61 @@ export function useConsoleSidebarRailPanel( setOpenRef.current(true); }, []); - // While the sidebar is hidden, the page header's expand button docks it, - // as the reader's choice (ruling 7069868269): on a narrow window it keeps - // the narrow-window choice expanded before the provider's toggle opens it, - // so the open is not the float; on a wide window the toggle's open is - // already the reader's. ⌘B floats the menu instead (ruling 6973617688): - // while the sidebar is hidden by hand on a wide window its toggle is noted - // in the capture phase, ahead of the provider's, whose open the next render - // turns into the float; on the fold every open is the float. A browser may - // render between the two (its microtask checkpoint after each listener), so - // the note waits for the open. + // A press on the sidebar's expand / collapse button is the provider's + // toggle. While the sidebar is hidden it docks it, as the reader's choice + // (ruling 7069868269): on a narrow window the narrow-window choice turns + // expanded first, so the open the toggle brings is not the float; on a wide + // window the toggle's open is already the reader's. A click on a trigger + // takes this step in the capture phase, ahead of the trigger's own handler, + // which then toggles; a browser may render between the two (its microtask + // checkpoint after each listener), and the choice is kept by then. + const beforeButtonToggle = useCallback(() => { + if (hiddenRef.current && railModeRef.current) setNarrowOpen(true); + }, [setNarrowOpen]); + + // ⌘B / Ctrl+B docking a float: the open sidebar stays where it is and turns + // docked, as the reader's choice for this window, and the cookie says so. + const dockFloat = useCallback(() => { + if (widthRef.current === 'narrow') setNarrowOpen(true); + if (floatOnRef.current !== null) { + holdWideWindowChoice(false); + setFloatOn(null); + if (widthRef.current === 'wide') writeWideWindowOpen(true); + } + writeSidebarStateCookie(true); + }, [setNarrowOpen]); + useEffect(() => { if (!hidden) return undefined; const onClickCapture = (event: globalThis.MouseEvent) => { if (!(event.target instanceof Element) || !event.target.closest('[data-sidebar="trigger"]')) return; - if (railModeRef.current) setNarrowOpen(true); - }; - // The provider's chord: `SIDEBAR_KEYBOARD_SHORTCUT` in `@object-ui/components`' `ui/sidebar.tsx`. - const onKeyDownCapture = (event: KeyboardEvent) => { - if (!hiddenByHand || event.key !== 'b' || !(event.metaKey || event.ctrlKey)) return; - holdWideWindowChoice(true); - setToggleFloats(widthRef.current); - // A toggle another listener swallowed opens nothing: drop the note. - setTimeout(() => { - setToggleFloats(null); - if (!overlayOpenRef.current) holdWideWindowChoice(false); - }, 0); + beforeButtonToggle(); }; document.addEventListener('click', onClickCapture, true); - window.addEventListener('keydown', onKeyDownCapture, true); - return () => { - document.removeEventListener('click', onClickCapture, true); - window.removeEventListener('keydown', onKeyDownCapture, true); + return () => document.removeEventListener('click', onClickCapture, true); + }, [hidden, beforeButtonToggle]); + + // ⌘B / Ctrl+B is a press on the expand / collapse button (ruling + // 7074574380): the same step and the same toggle, or, while the menu + // floats, the dock. On the document, after every listener on the way + // (an editor that takes the chord stops it there), and stopped so the + // provider's own listener on the window does not toggle a second time. + useEffect(() => { + if (!desktop) return undefined; + const onKeyDown = (event: KeyboardEvent) => { + if (!isSidebarToggleChord(event)) return; + event.preventDefault(); + event.stopPropagation(); + if (overlayOpenRef.current) { + dockFloat(); + return; + } + beforeButtonToggle(); + toggleSidebarRef.current(); }; - }, [hidden, hiddenByHand, setNarrowOpen]); + document.addEventListener('keydown', onKeyDown); + return () => document.removeEventListener('keydown', onKeyDown); + }, [desktop, beforeButtonToggle, dockFloat]); // While the menu floats, the primitive's cookie says collapsed: its setter // wrote it open, and a reload comes back to the reader's state, not the float. @@ -527,33 +553,20 @@ export function useConsoleSidebarRailPanel( setOpenRef.current(width === 'wide' ? (readWideWindowOpen() ?? true) : narrowOpen); }, [floatOn, width, desktop, open, narrowOpen]); - // Focus: into a float the trigger or ⌘B opened; out of a sidebar that hides. + // Focus: out of a sidebar that hides. const last = useRef({ open, overlayOpen, hidden }); useLayoutEffect(() => { const prev = last.current; last.current = { open, overlayOpen, hidden }; const root = sidebarRef.current; if (!hidden) clearTimeout(openTimer.current); - // Opened while folded, by neither the edge nor the pointer: ⌘B. - // (The fold switching on under an open sidebar is not an opening: - // `useResponsiveSidebar` folds it in the same frame.) - if (overlayOpen && !prev.overlayOpen && !prev.open && openedBy.current === null) { - openedBy.current = 'command'; - const active = document.activeElement; - returnFocus.current = - active instanceof HTMLElement && active !== document.body && !root?.contains(active) ? active : null; - floatFocusTarget(root)?.focus({ preventScroll: true }); - return; - } const overlayClosed = prev.overlayOpen && !overlayOpen; const becameHidden = hidden && !prev.hidden; if (!overlayClosed && !becameHidden) return; const by = openedBy.current; const closer = closedBy.current; - const back = returnFocus.current; openedBy.current = null; closedBy.current = null; - returnFocus.current = null; clearTimeout(closeTimer.current); closeTimer.current = undefined; if (!becameHidden) return; @@ -562,7 +575,7 @@ export function useConsoleSidebarRailPanel( if (closer === 'outside' || !(active instanceof HTMLElement) || !root?.contains(active)) return; const byPointer = closer === 'pointer' || closer === 'away' || (closer === null && (by === 'hover' || by === 'press')); if (byPointer) active.blur(); - else (back?.isConnected ? back : sidebarTrigger())?.focus({ preventScroll: true }); + else sidebarTrigger()?.focus({ preventScroll: true }); }, [open, overlayOpen, hidden, sidebarRef]); // The float has folded: the reader's wide-window choice is kept again.