From d2450a3e6fbfdf2ed192dc2f2e154c0123d667ee Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 10:24:03 +0000 Subject: [PATCH 1/5] fix(app-shell): Back closes the phone nav drawer and stays on the page Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTvKAh25Doey2NM9Qw --- .../app-shell/src/layout/ConsoleLayout.tsx | 2 + .../src/layout/usePhoneNavDrawerHistory.ts | 163 ++++++++++++++++++ ui/packages/app-shell/src/urlParams.ts | 8 + 3 files changed, 173 insertions(+) create mode 100644 ui/packages/app-shell/src/layout/usePhoneNavDrawerHistory.ts diff --git a/ui/packages/app-shell/src/layout/ConsoleLayout.tsx b/ui/packages/app-shell/src/layout/ConsoleLayout.tsx index af15253f4d7..1c3d3bd0b3e 100644 --- a/ui/packages/app-shell/src/layout/ConsoleLayout.tsx +++ b/ui/packages/app-shell/src/layout/ConsoleLayout.tsx @@ -30,6 +30,7 @@ import { ConsoleNotificationBanners } from './ConsoleNotificationBanners.js'; import { UnifiedSidebar } from './UnifiedSidebar.js'; import { AppHeader } from './AppHeader.js'; import { useResponsiveSidebar } from '../hooks/useResponsiveSidebar.js'; +import { usePhoneNavDrawerHistory } from './usePhoneNavDrawerHistory.js'; import { usePhoneViewport } from '../hooks/usePhoneViewport.js'; import { primeConsoleSidebarOpen } from './consoleSidebarRail.js'; import { useAiSurfaceEnabled } from '../hooks/useAiSurface.js'; @@ -131,6 +132,7 @@ export function isRecordPagePath(pathname: string): boolean { /** Inner component that can access SidebarProvider context */ function ConsoleLayoutInner({ children }: { children: React.ReactNode }) { useResponsiveSidebar(); + usePhoneNavDrawerHistory(); useAdvertiseShortcut(TOGGLE_SIDEBAR_SHORTCUT); return <>{children}; } diff --git a/ui/packages/app-shell/src/layout/usePhoneNavDrawerHistory.ts b/ui/packages/app-shell/src/layout/usePhoneNavDrawerHistory.ts new file mode 100644 index 00000000000..fa50951b050 --- /dev/null +++ b/ui/packages/app-shell/src/layout/usePhoneNavDrawerHistory.ts @@ -0,0 +1,163 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * usePhoneNavDrawerHistory: on a phone, Back closes the open nav drawer and + * stays on the page (objectstack#29131). + * + * The drawer is state Back should respect (`ui/AGENTS.md` #8), so while it is + * open it owns one history entry, pushed through the router with the same + * path, search and hash and the {@link NAV_DRAWER_OPEN_STATE} flag in its + * state. There is no popstate guard: `BrowserRouter` offers no hook to veto a + * POP (the reason `chrome/unsavedEdits.ts` gives), so a guard would have to + * re-push after the router had already moved. + * + * Invariants, all while the sidebar renders as the mobile drawer: + * + * - Opening the drawer pushes the entry; nothing is pushed when the current + * entry already carries the flag. + * - Arriving on an entry without the flag while the drawer is open closes the + * drawer (Back, or a navigation from inside the drawer). + * - Every other close (Escape, an outside tap, the trigger, the edge swipe's + * counterpart) pops the entry, so Back never stops on a no-op. + * - A link chosen inside the drawer replaces the flagged entry, so Back from + * the new page goes to the page the drawer was opened on. A link to the + * page already shown pops the entry instead. + * - A flagged entry this document did not push (a reload keeps + * `history.state`) is replaced by one without the flag, and the drawer stays + * closed. Returning to one it did push (Forward) reopens the drawer. + * + * With `isMobile` false the hook writes no history at all. + * + * Must be called inside a SidebarProvider and a router. + * @module + */ + +import { useEffect, useRef } from 'react'; +import { useHref, useLocation, useNavigate, useNavigationType, type Location } from 'react-router-dom'; +import { useSidebar } from '@object-ui/components'; +import { NAV_DRAWER_OPEN_STATE } from '../urlParams.js'; + +/** The primitive's mobile drawer (`Sidebar` renders its Sheet content with these attributes). */ +const PHONE_DRAWER_SELECTOR = '[data-sidebar="sidebar"][data-mobile="true"]'; + +/** Router keys of the flagged entries this document pushed. */ +const flaggedHere = new Set(); + +function isFlagged(state: unknown): boolean { + return !!state && typeof state === 'object' && (state as Record)[NAV_DRAWER_OPEN_STATE] === true; +} + +function stateObject(state: unknown): Record { + return state && typeof state === 'object' ? (state as Record) : {}; +} + +function withoutFlag(state: unknown): Record | null { + const { [NAV_DRAWER_OPEN_STATE]: _flag, ...rest } = stateObject(state); + return Object.keys(rest).length > 0 ? rest : null; +} + +function samePlace(location: Pick) { + return { pathname: location.pathname, search: location.search, hash: location.hash }; +} + +/** A plain left click with no modifier, the only kind the router handles itself. */ +function isPlainClick(event: MouseEvent): boolean { + return event.button === 0 && !event.metaKey && !event.altKey && !event.ctrlKey && !event.shiftKey; +} + +export function usePhoneNavDrawerHistory(): void { + const { isMobile, openMobile, setOpenMobile } = useSidebar(); + const location = useLocation(); + const navigationType = useNavigationType(); + const navigate = useNavigate(); + const rootHref = useHref('/'); + const basename = rootHref.endsWith('/') ? rootHref.slice(0, -1) : rootHref; + const flagged = isFlagged(location.state); + + // Whether the router's current entry carries the flag. Updated ahead of the + // navigations this hook starts: `BrowserRouter` commits a location in a + // transition, so a close that lands in the same event as the navigation + // (the drawer's "All apps" link closes the drawer itself) renders before + // the new location does. + const entryFlagged = useRef(flagged); + const locationRef = useRef(location); + const handledKey = useRef(null); + const lastOpen = useRef(openMobile); + + // The location side: Back closes, a stale flag is dropped, Forward reopens. + useEffect(() => { + if (!isMobile || handledKey.current === location.key) return; + handledKey.current = location.key; + locationRef.current = location; + entryFlagged.current = flagged; + if (!flagged) { + if (openMobile) setOpenMobile(false); + return; + } + if (navigationType !== 'POP') { + flaggedHere.add(location.key); + return; + } + if (!flaggedHere.has(location.key)) { + entryFlagged.current = false; + navigate(samePlace(location), { replace: true, state: withoutFlag(location.state) }); + return; + } + if (!openMobile) setOpenMobile(true); + }, [isMobile, location, flagged, navigationType, openMobile, setOpenMobile, navigate]); + + // The drawer side: an open pushes the entry, any other close pops it. + useEffect(() => { + if (lastOpen.current === openMobile) return; + lastOpen.current = openMobile; + if (!isMobile) return; + if (openMobile) { + if (entryFlagged.current) return; + entryFlagged.current = true; + const here = locationRef.current; + navigate(samePlace(here), { state: { ...stateObject(here.state), [NAV_DRAWER_OPEN_STATE]: true } }); + return; + } + if (entryFlagged.current) { + entryFlagged.current = false; + navigate(-1); + } + }, [isMobile, openMobile, navigate]); + + // A link chosen inside the open drawer replaces the flagged entry. A capture + // listener on the document runs before the router's own click handler, and + // `Link` skips its navigation for a click whose default is prevented. + useEffect(() => { + if (!isMobile || !openMobile) return; + const onClick = (event: MouseEvent) => { + if (!entryFlagged.current || event.defaultPrevented || !isPlainClick(event)) return; + const target = event.target instanceof Element ? event.target : null; + const anchor = target?.closest('a[href]'); + if (!(anchor instanceof HTMLAnchorElement) || !anchor.closest(PHONE_DRAWER_SELECTOR)) return; + if ((anchor.target && anchor.target !== '_self') || anchor.hasAttribute('download')) return; + const url = new URL(anchor.href, window.location.href); + if (url.origin !== window.location.origin) return; + let pathname = url.pathname; + if (basename) { + if (pathname !== basename && !pathname.startsWith(`${basename}/`)) return; + pathname = pathname.slice(basename.length) || '/'; + } + event.preventDefault(); + entryFlagged.current = false; + const here = locationRef.current; + if (pathname === here.pathname && url.search === here.search && url.hash === here.hash) { + navigate(-1); + return; + } + navigate({ pathname, search: url.search, hash: url.hash }, { replace: true }); + }; + document.addEventListener('click', onClick, true); + return () => document.removeEventListener('click', onClick, true); + }, [isMobile, openMobile, basename, navigate]); +} diff --git a/ui/packages/app-shell/src/urlParams.ts b/ui/packages/app-shell/src/urlParams.ts index 384287160bc..cad0969a1f8 100644 --- a/ui/packages/app-shell/src/urlParams.ts +++ b/ui/packages/app-shell/src/urlParams.ts @@ -111,6 +111,14 @@ export const RECORD_RELATED_ENLARGE_PARAM = 'related'; */ export const RECORD_RELATED_ENLARGE_PUSHED_STATE = '__relatedEnlargePushed'; +/** + * History-state flag for the phone nav drawer: the entry was pushed when the + * drawer opened, so Back closes the drawer and stays on the page, and any + * other close pops it. Not a URL parameter. Written and read only by + * `usePhoneNavDrawerHistory`. + */ +export const NAV_DRAWER_OPEN_STATE = '__navDrawerOpen'; + /** Command palette overlay (ADR-0054 Phase 1; alias `cmdk`). */ export const COMMAND_PALETTE_PARAM = 'palette'; From 5a7ece611d8862960e60cd6d703098c2e2eb1194 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 10:26:27 +0000 Subject: [PATCH 2/5] test(app-shell): pin Back with the phone nav drawer open in unit and live e2e Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTvKAh25Doey2NM9Qw --- .changeset/29131-phone-nav-drawer-back.md | 15 + .../live/phone-nav-drawer-back-29131.spec.ts | 137 +++++++++ ui/package.json | 2 +- .../usePhoneNavDrawerHistory-29131.test.tsx | 284 ++++++++++++++++++ 4 files changed, 437 insertions(+), 1 deletion(-) create mode 100644 .changeset/29131-phone-nav-drawer-back.md create mode 100644 ui/e2e/live/phone-nav-drawer-back-29131.spec.ts create mode 100644 ui/packages/app-shell/src/layout/__tests__/usePhoneNavDrawerHistory-29131.test.tsx diff --git a/.changeset/29131-phone-nav-drawer-back.md b/.changeset/29131-phone-nav-drawer-back.md new file mode 100644 index 00000000000..762067dd21a --- /dev/null +++ b/.changeset/29131-phone-nav-drawer-back.md @@ -0,0 +1,15 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(app-shell): on a phone, Back with the navigation drawer open closes the drawer and stays on the page + +Clause-②: no +Metadata-protocol: none + +Below 768 px the Console's sidebar is a drawer over the page. Back with the drawer open (the browser's Back, or Android's back gesture in a WebView host) used to leave the page the drawer was opened on. The open drawer now owns one history entry: + +- **Back closes the drawer.** The URL stays the page it was on; the next Back leaves the page as before. +- **No stray entries.** Closing the drawer any other way (an outside tap, Escape, the sidebar trigger) removes its entry, so Back never stops on a page that does not change. Choosing an entry in the drawer replaces it, so Back from the new page returns to the page the drawer was opened on. +- **A reload does not reopen it.** A reload with the drawer open comes back with the drawer closed and no drawer entry left; Forward to a drawer entry reopens the drawer. +- Wider windows are unchanged: opening and closing the sidebar there writes no history. diff --git a/ui/e2e/live/phone-nav-drawer-back-29131.spec.ts b/ui/e2e/live/phone-nav-drawer-back-29131.spec.ts new file mode 100644 index 00000000000..49fe6691f95 --- /dev/null +++ b/ui/e2e/live/phone-nav-drawer-back-29131.spec.ts @@ -0,0 +1,137 @@ +import { test, expect, type Page } from '@playwright/test'; + +/** + * Live e2e: at phone width, Back with the nav drawer open closes the drawer + * and stays on the page (objectstack-ai/objectstack#29131). Before, Back left + * the list for the page behind it. + * + * The drawer owns one history entry while it is open + * (`usePhoneNavDrawerHistory` in `@object-ui/app-shell`); the unit pins of + * every path are beside the hook, in a memory router. This file drives the + * real Console in Chromium with touch, against the real history: Back is the + * browser's own, the close is an outside tap, and the reload is a real one, + * which keeps `history.state`. + * + * In `test:e2e:live:nightly`, not the required `:ci` allowlist. + */ + +const APP = 'com.example.showcase'; +const LIST = `/apps/${APP}/showcase_task`; +const DRAWER = '[data-sidebar="sidebar"][data-mobile="true"]'; +const TRIGGER = 'button[data-sidebar="trigger"]'; +const FLAG = '__navDrawerOpen'; + +async function openList(page: Page) { + // A page behind the list, so Back has somewhere to go. + await page.goto('/home'); + await expect(page.locator('#root')).not.toBeEmpty(); + await page.goto(LIST); + await expect(page.locator(TRIGGER).first()).toBeVisible(); +} + +async function openDrawer(page: Page) { + await page.locator(TRIGGER).first().tap(); + await expect(page.locator(DRAWER)).toBeVisible(); + await expect.poll(() => drawerFlag(page)).toBe(true); +} + +function drawerFlag(page: Page): Promise { + return page.evaluate((flag) => { + const usr = (window.history.state as { usr?: Record } | null)?.usr; + return !!usr && usr[flag] === true; + }, FLAG); +} + +function historyLength(page: Page): Promise { + return page.evaluate(() => window.history.length); +} + +for (const width of [375, 390]) { + test.describe(`phone nav drawer and Back at ${width} px`, () => { + test.use({ viewport: { width, height: 844 }, isMobile: true, hasTouch: true }); + + test('Back with the drawer open closes it and stays on the list', async ({ page }) => { + await openList(page); + const url = page.url(); + await openDrawer(page); + + await page.goBack(); + + await expect(page.locator(DRAWER)).toBeHidden(); + expect(page.url()).toBe(url); + expect(await drawerFlag(page)).toBe(false); + }); + + test('an outside tap closes the drawer and pops its entry: Back goes to the previous page', async ({ page }) => { + await openList(page); + const before = await historyLength(page); + await openDrawer(page); + + // Right of the 288 px drawer, on the overlay. + await page.touchscreen.tap(width - 20, 420); + await expect(page.locator(DRAWER)).toBeHidden(); + await expect.poll(() => drawerFlag(page)).toBe(false); + expect(page.url()).toContain(LIST); + + await page.goBack(); + await expect(page).toHaveURL(/\/home(?:[?#]|$)/); + // The popped entry is forward history now, not an extra stop behind the list. + expect(await historyLength(page)).toBe(before + 1); + }); + + test('choosing a nav entry replaces the drawer entry: Back returns to the list', async ({ page }) => { + await openList(page); + const listUrl = page.url(); + await openDrawer(page); + + const target = await page.evaluate(({ drawer, list }) => { + const anchors = Array.from(document.querySelectorAll(`${drawer} a[href]`)); + const other = anchors.find((a) => { + const path = new URL(a.href).pathname; + return path.includes('/apps/') && !path.endsWith(list); + }); + return other?.getAttribute('href') ?? null; + }, { drawer: DRAWER, list: LIST }); + expect(target, 'the drawer offers another entry').toBeTruthy(); + + await page.locator(`${DRAWER} a[href="${target}"]`).first().tap(); + await expect(page.locator(DRAWER)).toBeHidden(); + await expect.poll(() => new URL(page.url()).pathname).toBe(target); + + await page.goBack(); + await expect.poll(() => page.url()).toBe(listUrl); + await expect(page.locator(DRAWER)).toBeHidden(); + expect(await drawerFlag(page)).toBe(false); + }); + + test('a reload with the drawer open leaves it closed, with no flagged entry left', async ({ page }) => { + await openList(page); + await openDrawer(page); + const length = await historyLength(page); + + await page.reload(); + await expect(page.locator(TRIGGER).first()).toBeVisible(); + + await expect.poll(() => drawerFlag(page)).toBe(false); + await expect(page.locator(DRAWER)).toBeHidden(); + expect(page.url()).toContain(LIST); + expect(await historyLength(page)).toBe(length); + }); + }); +} + +test.describe('desktop sidebar', () => { + test.use({ viewport: { width: 1280, height: 800 } }); + + test('CONTROL — opening and closing the sidebar writes no history entry', async ({ page }) => { + await openList(page); + const url = page.url(); + const length = await historyLength(page); + + await page.locator(TRIGGER).first().click(); + await page.locator(TRIGGER).first().click(); + + expect(await historyLength(page)).toBe(length); + expect(page.url()).toBe(url); + }); +}); diff --git a/ui/package.json b/ui/package.json index b1fbc2d21ca..9a2bae21dd7 100644 --- a/ui/package.json +++ b/ui/package.json @@ -111,7 +111,7 @@ "test:e2e:ui": "playwright test --ui", "test:e2e:live": "playwright test --config=playwright.live.config.ts", "test:e2e:live:ci": "playwright test --config=playwright.live.config.ts screen-flow.spec.ts action-modal.spec.ts master-detail.spec.ts saved-view-filter.spec.ts studio-object-designer.spec.ts studio-editor.spec.ts record-form-direct-url.spec.ts list-row-action-cel.spec.ts", - "test:e2e:live:nightly": "playwright test --config=playwright.live.config.ts cascading-options.spec.ts declared-sharing-rules-reach-13091.spec.ts field-conditional-rules.spec.ts form-view-subforms.spec.ts grid-conditional-rules.spec.ts grid-file-upload.spec.ts grid-parent-rules.spec.ts inline-edit-polish-2572.spec.ts read-only-member-record.spec.ts record-history-display.spec.ts required-when-submit.spec.ts summary-rollup.spec.ts user-filters.spec.ts", + "test:e2e:live:nightly": "playwright test --config=playwright.live.config.ts cascading-options.spec.ts declared-sharing-rules-reach-13091.spec.ts field-conditional-rules.spec.ts form-view-subforms.spec.ts grid-conditional-rules.spec.ts grid-file-upload.spec.ts grid-parent-rules.spec.ts inline-edit-polish-2572.spec.ts read-only-member-record.spec.ts record-history-display.spec.ts required-when-submit.spec.ts summary-rollup.spec.ts user-filters.spec.ts phone-nav-drawer-back-29131.spec.ts", "test:e2e:import-harness": "playwright test --config=playwright.import-harness.config.ts", "test:e2e:import-console": "playwright test --config=playwright.import-console.config.ts" }, diff --git a/ui/packages/app-shell/src/layout/__tests__/usePhoneNavDrawerHistory-29131.test.tsx b/ui/packages/app-shell/src/layout/__tests__/usePhoneNavDrawerHistory-29131.test.tsx new file mode 100644 index 00000000000..9ab69d2e6c1 --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/usePhoneNavDrawerHistory-29131.test.tsx @@ -0,0 +1,284 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * usePhoneNavDrawerHistory — on a phone, Back with the nav drawer open closes + * the drawer and stays on the page (objectstack#29131). Before, Back left the + * page the drawer was opened on. + * + * Harness: the provider / chrome mocks of + * `UnifiedSidebar.phoneDrawerCloses-29075.test.tsx`; `@object-ui/layout` and + * `@object-ui/components` stay REAL, so the drawer is the real Sheet, its + * entries are the real `NavigationRenderer` links, and the sidebar's own + * route-change close runs beside the hook. The history is a MemoryRouter that + * starts on `/apps/hotcrm` with `/home` behind it. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, it, expect, vi } from 'vitest'; +import React from 'react'; +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MemoryRouter, useLocation, useNavigate, type Location } from 'react-router-dom'; + +vi.mock('@object-ui/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useObjectTranslation: () => ({ + t: (key: string, options?: Record) => String(options?.defaultValue ?? key), + language: 'en', + }), + useObjectLabel: () => ({ + objectLabel: ({ label }: { label?: string }) => label, + viewLabel: (_o: string, _v: string, fallback?: string) => fallback, + dashboardLabel: ({ label }: { label?: string }) => label, + appLabel: ({ name, label }: { name: string; label?: string }) => label || name, + }), +})); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: null, activeOrganization: null }), + useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }), +})); + +vi.mock('@object-ui/permissions', async (importOriginal) => ({ + ...(await importOriginal()), + usePermissions: () => ({ can: () => true, hasCapabilities: () => true }), +})); + +const NAV = [{ id: 'n1', type: 'object', label: 'Leads', objectName: 'lead' }]; +const HOTCRM = { name: 'hotcrm', label: 'HotCRM', icon: 'flame', active: true, navigation: NAV }; + +vi.mock('../../providers/MetadataProvider', () => ({ + useMetadata: () => ({ apps: [HOTCRM], objects: [] }), +})); + +vi.mock('../../providers/ExpressionProvider', () => ({ + useExpressionContext: () => ({ evaluator: null }), + evaluateVisibility: (expr: unknown) => expr !== false && expr !== 'false', + evaluateNavigationVisibility: (expr: unknown) => expr !== false && expr !== 'false', + useHasExpressionScope: () => true, +})); + +vi.mock('../../utils', () => ({ + resolveKeyedI18nLabel: (label: unknown) => (typeof label === 'string' ? label : ''), + matchAppBySegment: (apps: Array<{ name?: string }>, segment?: string) => + apps.find((a) => a?.name === segment), + appRouteSegment: (app: { name?: string }) => app?.name, +})); + +vi.mock('../../utils/getIcon', () => ({ + getIcon: (name?: string) => () => , +})); +vi.mock('../../hooks/useRecentItems', () => ({ useRecentItems: () => ({ recentItems: [] }) })); +vi.mock('../../hooks/useFavorites', () => ({ + useFavorites: () => ({ favorites: [], removeFavorite: vi.fn() }), +})); +vi.mock('../../hooks/useNavPins', () => ({ + useNavPins: () => ({ togglePin: vi.fn(), applyPins: (items: unknown) => items }), +})); +vi.mock('../../hooks/useNavActionDispatch', () => ({ + useNavActionDispatch: () => vi.fn(), +})); +vi.mock('../../context/NavigationContext', () => ({ + useNavigationContext: () => ({ context: 'app', currentAppName: 'hotcrm' }), +})); +vi.mock('../ContextSelectors', () => ({ + useAppContextSelectors: () => ({ contextValues: {}, element: null }), + contextSelectorQueryKey: (id: string) => (id === 'active_package' ? 'package' : id), + STUDIO_PACKAGE_SELECTOR_ID: 'active_package', +})); +vi.mock('../LocalizedSidebarTrigger', () => ({ + LocalizedSidebarTrigger: () => null, +})); + +import { SidebarProvider, useSidebar } from '@object-ui/components'; +import { UnifiedSidebar } from '../UnifiedSidebar'; +import { usePhoneNavDrawerHistory } from '../usePhoneNavDrawerHistory'; +import { NAV_DRAWER_OPEN_STATE } from '../../urlParams'; + +interface Probed { + isMobile: boolean; + openMobile: boolean; + open: boolean; + setOpenMobile: (open: boolean) => void; + toggleSidebar: () => void; + location: Location; + navigate: ReturnType; +} + +let probed: Probed | null = null; +/** Every location the router committed, in order (one per entry change). */ +let committed: Location[] = []; + +function Probe() { + const { isMobile, openMobile, open, setOpenMobile, toggleSidebar } = useSidebar(); + const location = useLocation(); + const navigate = useNavigate(); + // Published after each commit, not during render (react-hooks/globals). + React.useEffect(() => { + probed = { isMobile, openMobile, open, setOpenMobile, toggleSidebar, location, navigate }; + }); + React.useEffect(() => { + committed.push(location); + }, [location]); + return null; +} + +function Mounted() { + usePhoneNavDrawerHistory(); + return null; +} + +type Entry = string | { pathname: string; state?: unknown }; + +function setViewportWidth(width: number) { + Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: width }); +} + +function renderConsole(width: number, entries: Entry[] = ['/home', '/apps/hotcrm']) { + setViewportWidth(width); + return render( + + + + + + + , + ); +} + +const current = () => probed!.location; +const flagged = (location: Location) => + !!location.state && (location.state as Record)[NAV_DRAWER_OPEN_STATE] === true; + +async function phoneReady() { + await waitFor(() => expect(probed?.isMobile).toBe(true)); +} + +async function openDrawer() { + act(() => probed!.setOpenMobile(true)); + await screen.findByTestId('mobile-sidebar-app'); + await waitFor(() => expect(flagged(current())).toBe(true)); +} + +async function back() { + act(() => { + probed!.navigate(-1); + }); +} + +afterEach(() => { + cleanup(); + probed = null; + committed = []; + setViewportWidth(1024); +}); + +describe('Back with the phone nav drawer open (objectstack#29131)', () => { + it('Back closes the drawer and stays on the same URL', async () => { + renderConsole(375); + await phoneReady(); + await openDrawer(); + expect(current().pathname).toBe('/apps/hotcrm'); + + await back(); + + await waitFor(() => expect(probed?.openMobile).toBe(false)); + expect(current().pathname).toBe('/apps/hotcrm'); + expect(flagged(current())).toBe(false); + await waitFor(() => expect(screen.queryByTestId('mobile-sidebar-app')).not.toBeInTheDocument()); + + // And the next Back leaves the page, as it does with the drawer closed. + await back(); + await waitFor(() => expect(current().pathname).toBe('/home')); + }); + + it('closing the drawer (Escape) pops its entry, so Back goes to the previous page', async () => { + renderConsole(390); + await phoneReady(); + await openDrawer(); + + fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' }); + + await waitFor(() => expect(probed?.openMobile).toBe(false)); + await waitFor(() => expect(flagged(current())).toBe(false)); + expect(current().pathname).toBe('/apps/hotcrm'); + + await back(); + await waitFor(() => expect(current().pathname).toBe('/home')); + }); + + it('choosing a nav entry replaces the drawer entry: Back goes to the page the drawer was opened on', async () => { + renderConsole(375); + await phoneReady(); + await openDrawer(); + + fireEvent.click(screen.getByRole('link', { name: 'Leads' })); + + await waitFor(() => expect(current().pathname).toBe('/apps/hotcrm/lead')); + await waitFor(() => expect(probed?.openMobile).toBe(false)); + expect(flagged(current())).toBe(false); + + await back(); + await waitFor(() => expect(current().pathname).toBe('/apps/hotcrm')); + expect(flagged(current())).toBe(false); + expect(probed?.openMobile).toBe(false); + }); + + it('the drawer\'s "All apps" link, which closes the drawer itself, does not pop as well', async () => { + renderConsole(375); + await phoneReady(); + await openDrawer(); + + fireEvent.click(screen.getByTestId('mobile-sidebar-home')); + + await waitFor(() => expect(current().pathname).toBe('/home')); + await waitFor(() => expect(probed?.openMobile).toBe(false)); + + await back(); + await waitFor(() => expect(current().pathname).toBe('/apps/hotcrm')); + expect(flagged(current())).toBe(false); + }); + + it('a reload on the drawer entry leaves the drawer closed and the entry without the flag', async () => { + // A reload keeps `history.state`, so the document starts on a flagged entry it never pushed. + renderConsole(375, ['/home', '/apps/hotcrm', { pathname: '/apps/hotcrm', state: { [NAV_DRAWER_OPEN_STATE]: true } }]); + await phoneReady(); + + await waitFor(() => expect(flagged(current())).toBe(false)); + expect(current().pathname).toBe('/apps/hotcrm'); + expect(probed?.openMobile).toBe(false); + expect(screen.queryByTestId('mobile-sidebar-app')).not.toBeInTheDocument(); + }); + + it('Forward to the drawer entry this page pushed opens the drawer again', async () => { + renderConsole(375); + await phoneReady(); + await openDrawer(); + await back(); + await waitFor(() => expect(probed?.openMobile).toBe(false)); + + act(() => { + probed!.navigate(1); + }); + + await waitFor(() => expect(probed?.openMobile).toBe(true)); + expect(flagged(current())).toBe(true); + }); + + it('CONTROL — at desktop width, opening and closing the sidebar writes no history entry', async () => { + renderConsole(1280); + await waitFor(() => expect(probed?.isMobile).toBe(false)); + const before = committed.length; + const start = current().key; + + act(() => probed!.toggleSidebar()); + await waitFor(() => expect(probed?.open).toBe(false)); + act(() => probed!.toggleSidebar()); + await waitFor(() => expect(probed?.open).toBe(true)); + + expect(committed.length).toBe(before); + expect(current().key).toBe(start); + }); + +}); From 05f09f35de707d704674f8d1a59c21e5a47f32c4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 11:01:20 +0000 Subject: [PATCH 3/5] fix(app-shell): a Back pressed before the drawer's entry commits still closes the drawer Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTvKAh25Doey2NM9Qw --- .../src/layout/usePhoneNavDrawerHistory.ts | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/ui/packages/app-shell/src/layout/usePhoneNavDrawerHistory.ts b/ui/packages/app-shell/src/layout/usePhoneNavDrawerHistory.ts index fa50951b050..c1e91b459ba 100644 --- a/ui/packages/app-shell/src/layout/usePhoneNavDrawerHistory.ts +++ b/ui/packages/app-shell/src/layout/usePhoneNavDrawerHistory.ts @@ -22,7 +22,8 @@ * - Opening the drawer pushes the entry; nothing is pushed when the current * entry already carries the flag. * - Arriving on an entry without the flag while the drawer is open closes the - * drawer (Back, or a navigation from inside the drawer). + * drawer (Back, or a navigation from inside the drawer), and so does any + * history move off the flagged entry, even one the router never commits. * - Every other close (Escape, an outside tap, the trigger, the edge swipe's * counterpart) pops the entry, so Back never stops on a no-op. * - A link chosen inside the drawer replaces the flagged entry, so Back from @@ -130,11 +131,21 @@ export function usePhoneNavDrawerHistory(): void { } }, [isMobile, openMobile, navigate]); - // A link chosen inside the open drawer replaces the flagged entry. A capture - // listener on the document runs before the router's own click handler, and - // `Link` skips its navigation for a click whose default is prevented. + // While the drawer is open on its flagged entry: any history move leaves + // that entry, and a link chosen inside the drawer replaces it. useEffect(() => { if (!isMobile || !openMobile) return; + // `BrowserRouter` commits the push and a Back pressed before the push + // committed as one transition, so the router reports no location change + // at all; the document's own popstate still says the entry was left. + const onPopState = () => { + if (!entryFlagged.current) return; + entryFlagged.current = false; + setOpenMobile(false); + }; + // A capture listener on the document runs before the router's own click + // handler, and `Link` skips its navigation for a click whose default is + // prevented. const onClick = (event: MouseEvent) => { if (!entryFlagged.current || event.defaultPrevented || !isPlainClick(event)) return; const target = event.target instanceof Element ? event.target : null; @@ -157,7 +168,11 @@ export function usePhoneNavDrawerHistory(): void { } navigate({ pathname, search: url.search, hash: url.hash }, { replace: true }); }; + window.addEventListener('popstate', onPopState); document.addEventListener('click', onClick, true); - return () => document.removeEventListener('click', onClick, true); - }, [isMobile, openMobile, basename, navigate]); + return () => { + window.removeEventListener('popstate', onPopState); + document.removeEventListener('click', onClick, true); + }; + }, [isMobile, openMobile, basename, navigate, setOpenMobile]); } From 1789809418cc650d35427b5d1a411710c56b6e0b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 11:27:12 +0000 Subject: [PATCH 4/5] test(app-shell): keep the live phone drawer spec out of the script lists Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTvKAh25Doey2NM9Qw --- ui/e2e/live/phone-nav-drawer-back-29131.spec.ts | 3 ++- ui/package.json | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/ui/e2e/live/phone-nav-drawer-back-29131.spec.ts b/ui/e2e/live/phone-nav-drawer-back-29131.spec.ts index 49fe6691f95..3f1b431b36c 100644 --- a/ui/e2e/live/phone-nav-drawer-back-29131.spec.ts +++ b/ui/e2e/live/phone-nav-drawer-back-29131.spec.ts @@ -12,7 +12,8 @@ import { test, expect, type Page } from '@playwright/test'; * browser's own, the close is an outside tap, and the reload is a real one, * which keeps `history.state`. * - * In `test:e2e:live:nightly`, not the required `:ci` allowlist. + * Not in the required `:ci` allowlist: run it by name, or with every live spec + * through `test:e2e:live`. */ const APP = 'com.example.showcase'; diff --git a/ui/package.json b/ui/package.json index 9a2bae21dd7..b1fbc2d21ca 100644 --- a/ui/package.json +++ b/ui/package.json @@ -111,7 +111,7 @@ "test:e2e:ui": "playwright test --ui", "test:e2e:live": "playwright test --config=playwright.live.config.ts", "test:e2e:live:ci": "playwright test --config=playwright.live.config.ts screen-flow.spec.ts action-modal.spec.ts master-detail.spec.ts saved-view-filter.spec.ts studio-object-designer.spec.ts studio-editor.spec.ts record-form-direct-url.spec.ts list-row-action-cel.spec.ts", - "test:e2e:live:nightly": "playwright test --config=playwright.live.config.ts cascading-options.spec.ts declared-sharing-rules-reach-13091.spec.ts field-conditional-rules.spec.ts form-view-subforms.spec.ts grid-conditional-rules.spec.ts grid-file-upload.spec.ts grid-parent-rules.spec.ts inline-edit-polish-2572.spec.ts read-only-member-record.spec.ts record-history-display.spec.ts required-when-submit.spec.ts summary-rollup.spec.ts user-filters.spec.ts phone-nav-drawer-back-29131.spec.ts", + "test:e2e:live:nightly": "playwright test --config=playwright.live.config.ts cascading-options.spec.ts declared-sharing-rules-reach-13091.spec.ts field-conditional-rules.spec.ts form-view-subforms.spec.ts grid-conditional-rules.spec.ts grid-file-upload.spec.ts grid-parent-rules.spec.ts inline-edit-polish-2572.spec.ts read-only-member-record.spec.ts record-history-display.spec.ts required-when-submit.spec.ts summary-rollup.spec.ts user-filters.spec.ts", "test:e2e:import-harness": "playwright test --config=playwright.import-harness.config.ts", "test:e2e:import-console": "playwright test --config=playwright.import-console.config.ts" }, From 9626c788b09d8e1e824eee03d1a41a56da27f7f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 11:59:42 +0000 Subject: [PATCH 5/5] test(app-shell): run the live phone drawer spec in the nightly live list Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTvKAh25Doey2NM9Qw --- ui/e2e/live/phone-nav-drawer-back-29131.spec.ts | 3 +-- ui/package.json | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/ui/e2e/live/phone-nav-drawer-back-29131.spec.ts b/ui/e2e/live/phone-nav-drawer-back-29131.spec.ts index 3f1b431b36c..49fe6691f95 100644 --- a/ui/e2e/live/phone-nav-drawer-back-29131.spec.ts +++ b/ui/e2e/live/phone-nav-drawer-back-29131.spec.ts @@ -12,8 +12,7 @@ import { test, expect, type Page } from '@playwright/test'; * browser's own, the close is an outside tap, and the reload is a real one, * which keeps `history.state`. * - * Not in the required `:ci` allowlist: run it by name, or with every live spec - * through `test:e2e:live`. + * In `test:e2e:live:nightly`, not the required `:ci` allowlist. */ const APP = 'com.example.showcase'; diff --git a/ui/package.json b/ui/package.json index b1fbc2d21ca..9a2bae21dd7 100644 --- a/ui/package.json +++ b/ui/package.json @@ -111,7 +111,7 @@ "test:e2e:ui": "playwright test --ui", "test:e2e:live": "playwright test --config=playwright.live.config.ts", "test:e2e:live:ci": "playwright test --config=playwright.live.config.ts screen-flow.spec.ts action-modal.spec.ts master-detail.spec.ts saved-view-filter.spec.ts studio-object-designer.spec.ts studio-editor.spec.ts record-form-direct-url.spec.ts list-row-action-cel.spec.ts", - "test:e2e:live:nightly": "playwright test --config=playwright.live.config.ts cascading-options.spec.ts declared-sharing-rules-reach-13091.spec.ts field-conditional-rules.spec.ts form-view-subforms.spec.ts grid-conditional-rules.spec.ts grid-file-upload.spec.ts grid-parent-rules.spec.ts inline-edit-polish-2572.spec.ts read-only-member-record.spec.ts record-history-display.spec.ts required-when-submit.spec.ts summary-rollup.spec.ts user-filters.spec.ts", + "test:e2e:live:nightly": "playwright test --config=playwright.live.config.ts cascading-options.spec.ts declared-sharing-rules-reach-13091.spec.ts field-conditional-rules.spec.ts form-view-subforms.spec.ts grid-conditional-rules.spec.ts grid-file-upload.spec.ts grid-parent-rules.spec.ts inline-edit-polish-2572.spec.ts read-only-member-record.spec.ts record-history-display.spec.ts required-when-submit.spec.ts summary-rollup.spec.ts user-filters.spec.ts phone-nav-drawer-back-29131.spec.ts", "test:e2e:import-harness": "playwright test --config=playwright.import-harness.config.ts", "test:e2e:import-console": "playwright test --config=playwright.import-console.config.ts" },