diff --git a/.changeset/29141-phone-nav-drawer-open.md b/.changeset/29141-phone-nav-drawer-open.md new file mode 100644 index 00000000000..74f8a492398 --- /dev/null +++ b/.changeset/29141-phone-nav-drawer-open.md @@ -0,0 +1,16 @@ +--- +'@object-ui/layout': patch +--- + +perf(layout): the phone nav drawer opens in one render, and its opening frame draws only the rows that fit + +Clause-②: no +Metadata-protocol: none + +Opening the Console's nav drawer on a phone took 300 to 580 ms at 4x CPU on an app with a long menu (the showcase, 50 entries in 8 groups). A profile of the open named three costs in `NavigationRenderer`, and each is gone: + +- **One render per row.** Every row asked `useIsMobile()` for itself. That hook answers "not a phone" on its first render and corrects itself in an effect, so each time the drawer opened (the sheet mounts the menu afresh) the whole menu rendered at desktop size, then every row set state and the menu rendered and restyled a second time. The rows now read one answer from the menu's root: the sidebar provider's own phone flag, which settled when the shell mounted. A menu drawn with no sidebar provider asks the viewport once for all its rows, as before. +- **No hidden tooltips.** A row's tooltip names it in the collapsed icon rail. On a phone the sidebar primitive draws that tooltip hidden, so a phone row now skips it. Desktop rows keep their tooltip. +- **The opening frame draws what fits.** On a phone, a menu longer than the window draws the rows that fit (and a few more) in the frame the drawer opens with, and the rest join right after it, while the drawer is still sliding in. The rows drawn first are not drawn again. The full menu, its order, labels, icons, badges, pins and active entry are unchanged. Desktop draws the whole menu at once, as before. + +Measured on the production Console at 4x CPU, 390 px wide, from the tap to the first painted frame, 20 opens each on one backend: the showcase drawer went from 203 to 640 ms (0 of 20 opens under 200 ms, median 305) to 60 to 368 ms (17 of 20 under 200 ms, median 116). The CRM drawer went from 14 to 19 of 20 opens under 200 ms. The group toggle was and stays under 90 ms in the page. No request is added to the open, and no metadata key or option changes. diff --git a/ui/packages/layout/src/NavigationRenderer.tsx b/ui/packages/layout/src/NavigationRenderer.tsx index 9f866973628..72e69e433c9 100644 --- a/ui/packages/layout/src/NavigationRenderer.tsx +++ b/ui/packages/layout/src/NavigationRenderer.tsx @@ -72,6 +72,7 @@ import { Separator, cn, useIsMobile, + useOptionalSidebar, } from '@object-ui/components'; import type { NavigationItem, KeyedI18nLabel } from '@object-ui/types'; import { isElementApiDataSourceShape } from '@object-ui/react'; @@ -1244,6 +1245,148 @@ export function resolveActiveNavItem( */ const ActiveNavIdContext = React.createContext(null); +/** + * Whether the rows draw at phone size (44 px rows, larger text and icons), + * provided once at the tree root by {@link NavMobileSource} (objectstack#29141). + */ +const NavIsMobileContext = React.createContext(false); + +/** + * The phone-size answer the rows read, decided once for the whole tree. + * + * Inside a sidebar provider it is the provider's own `isMobile`, which settled + * when the shell mounted. Each row used to ask `useIsMobile()` itself, and that + * hook answers `false` on its first render and corrects itself in an effect: + * every time the phone drawer opened, its whole tree mounted at desktop size, + * then each row's effect read the viewport and set state, and the tree rendered + * and restyled a second time. On the showcase (54 rows) that second pass was + * about a third of the open at 4x CPU. + * + * With no sidebar provider the tree keeps the viewport answer it had, asked + * once here for every row. The provider's value does not change when the + * sidebar opens or closes, so the rows below do not re-render on a toggle: + * `children` is the element the root rendered, and the provided value is the + * same boolean. + */ +function NavMobileSource({ children }: { children: React.ReactNode }) { + const sidebar = useOptionalSidebar(); + if (sidebar) { + return {children}; + } + return {children}; +} + +function ViewportMobileSource({ children }: { children: React.ReactNode }) { + const isMobile = useIsMobile(); + return {children}; +} + +/** + * Whether a group is open on first view (objectui#13336): + * + * 1. A group that holds the current route opens, whatever it declares — a + * closed group would hide the active item and the user would lose + * orientation. + * 2. Otherwise the author's declaration decides. `expanded` is the spec field + * name; `defaultOpen` is the legacy objectui field name. Either one, when + * set, is honoured as written. + * 3. A group that declares neither opens. Its length does not decide: + * collapsing an undeclared group because it is long hid entries the + * navigation never asked to hide, so a group is closed on first view only + * when it says `expanded: false` (or `defaultOpen: false`). + * + * A group row and the phone drawer's first-frame budget (below) both read it. + */ +function groupOpensOnFirstView(item: NavigationItem, activeNavId: string | null): boolean { + if (item.type === 'group' && activeNavId) { + const visit = (nodes: NavigationItem[] | undefined): boolean => + !!nodes?.some((node) => node.id === activeNavId || (node.type === 'group' && visit(node.children))); + if (visit(item.children)) return true; + } + if (typeof item.expanded === 'boolean') return item.expanded; + if (typeof item.defaultOpen === 'boolean') return item.defaultOpen; + return true; +} + +/** The height of one phone drawer row, `min-h-[44px]` on the rows below. */ +const PHONE_ROW_PX = 44; + +/** + * How many rows the phone drawer draws in the frame it opens with: as many as + * fit the window, and a few more (objectstack#29141). The rest of a long menu + * lies below the fold, so it renders right after that frame instead of in it. + */ +function phoneFirstFrameRows(): number { + const height = typeof window === 'undefined' ? 0 : window.innerHeight; + return Math.ceil(height / PHONE_ROW_PX) + 4; +} + +/** + * The rows `item` draws on first view: one for an entry or a separator; for a + * group, its label and, when it opens, its children's rows. Nothing for an + * entry or a group the guards hide, under the very statements the rows run. + */ +function firstViewRowCount( + item: NavigationItem, + guards: NavigationVisibilityOptions, + activeNavId: string | null, +): number { + if (!passesNavItemGuards(item, guards)) return 0; + if (item.type === 'action' && !guards.hasActionHandler) return 0; + if (item.type !== 'group') return 1; + const children = item.children ?? []; + if (!hasVisibleNavigationItems(children, guards)) return 0; + if (!groupOpensOnFirstView(item, activeNavId)) return 1; + return children.reduce((rows, child) => rows + firstViewRowCount(child, guards, activeNavId), 1); +} + +/** + * How many of `sections` the phone drawer's first frame draws: the sections, + * in order, until their rows fill {@link phoneFirstFrameRows}. + */ +function firstFrameSectionCount(sectionRows: number[], rowsAbove: number): number { + const budget = phoneFirstFrameRows(); + let rows = rowsAbove; + for (let i = 0; i < sectionRows.length; i += 1) { + if (rows >= budget) return i; + rows += sectionRows[i]; + } + return sectionRows.length; +} + +/** + * Draws `children` (the tree's sections, or a flat menu's rows) whole, except + * when a phone drawer opens on a menu longer than the window: then the first + * `firstFrame()` of them draw in the frame the drawer opens with, and the rest + * join in a transition right after it (objectstack#29141). Those are below the + * fold, and the drawer slides in over several frames, so what the drawer shows + * is unchanged; the opening frame just stops paying for rows nobody sees yet. + * + * The rows already drawn are not drawn again when the rest join: they are the + * same elements, under the same keys. Desktop and every later update draw the + * whole tree at once. + */ +function PhoneFirstFrame({ + firstFrame, + children, +}: { + /** How many of `children` the first frame draws; asked only on a phone, once. */ + firstFrame: () => number; + children: React.ReactNode[]; +}) { + const isMobile = React.useContext(NavIsMobileContext); + // Once whole, always whole: a menu that grows later draws its new rows at once. + const [drawn, setDrawn] = useState(() => { + const first = isMobile ? firstFrame() : Number.POSITIVE_INFINITY; + return first >= children.length ? Number.POSITIVE_INFINITY : first; + }); + const whole = drawn === Number.POSITIVE_INFINITY; + React.useEffect(() => { + if (!whole) React.startTransition(() => setDrawn(Number.POSITIVE_INFINITY)); + }, [whole]); + return <>{whole ? children : children.slice(0, drawn)}; +} + // --------------------------------------------------------------------------- // Search filter helper // --------------------------------------------------------------------------- @@ -1541,36 +1684,18 @@ function NavigationItemRenderer({ }) { // iOS-native mobile drawer polish: >=44px tap targets, larger text and // icons, rounder rows. Desktop (>=768px) keeps the compact rail untouched. - const isMobile = useIsMobile(); + // Decided once for the tree (`NavMobileSource`), not by a hook per row. + const isMobile = React.useContext(NavIsMobileContext); const mobileBtnClass = isMobile ? 'min-h-[44px] text-[15px] gap-3 rounded-xl' : undefined; + // A row's tooltip names it in the icon rail. On a phone the primitive draws + // the tooltip `hidden`, so a row there skips the Tooltip it would never show: + // one Radix Tooltip per row was a measurable part of every drawer open + // (objectstack#29141). + const rowTooltip = (label: string) => (isMobile ? undefined : label); const navIconClass = cn('shrink-0', isMobile ? 'h-5 w-5' : 'h-4 w-4'); - // Resolve the initial open state (objectui#13336): - // - // 1. A group that holds the current route opens, whatever it declares — - // a closed group would hide the active item and the user would lose - // orientation. - // 2. Otherwise the author's declaration decides. `expanded` is the spec - // field name; `defaultOpen` is the legacy objectui field name. Either - // one, when set, is honoured as written. - // 3. A group that declares neither opens. Its length does not decide: - // collapsing an undeclared group because it is long hid entries the - // navigation never asked to hide, so a group is closed on first view - // only when it says `expanded: false` (or `defaultOpen: false`). - const explicitOpen = (() => { - if (typeof item.expanded === 'boolean') return item.expanded; - if (typeof item.defaultOpen === 'boolean') return item.defaultOpen; - return undefined; - })(); + // The initial open state (objectui#13336): see `groupOpensOnFirstView`. const activeNavId = React.useContext(ActiveNavIdContext); - const hasActiveDescendant = React.useMemo(() => { - if (item.type !== 'group' || !activeNavId) return false; - const visit = (nodes: NavigationItem[] | undefined): boolean => - !!nodes?.some( - (node) => node.id === activeNavId || (node.type === 'group' && visit(node.children)), - ); - return visit(item.children); - }, [item, activeNavId]); - const initialOpen = hasActiveDescendant ? true : (explicitOpen ?? true); + const initialOpen = React.useMemo(() => groupOpensOnFirstView(item, activeNavId), [item, activeNavId]); const [isOpen, setIsOpen] = useState(initialOpen); // --- Per-item guards: `visible`, `requiredPermissions`, and the @@ -1708,7 +1833,7 @@ function NavigationItemRenderer({ {row?.dropIndicator && } onAction?.(item)} className={cn(mobileBtnClass, dragActivator && 'cursor-grab')} {...(dragActivator ? dragActivatorProps(dragActivator) : {})} @@ -1777,7 +1902,7 @@ function NavigationItemRenderer({ {external ? ( @@ -1933,6 +2058,18 @@ export function NavigationRenderer({ const hasGroups = sorted.some((i) => i.type === 'group'); + // --- The phone drawer's first frame (objectstack#29141) --- the rows each + // top-level entry draws on first view, and the rows the Favorites section + // draws above them; read only when a phone drawer opens (`PhoneFirstFrame`). + const firstViewGuards: NavigationVisibilityOptions = { + evaluateVisibility: evalVis, + checkPermission: checkPerm, + checkCapability: checkCap, + checkDocTarget, + hasActionHandler: !!onAction, + }; + const firstViewRows = (item: NavigationItem) => firstViewRowCount(item, firstViewGuards, activeNavId); + // --- Favorites section (pinned items) --- the one place a user orders the // sidebar (objectui#12059): sortable when the host stores the order. The // host's own favorite rows follow the pinned ones (objectui#12427), outside @@ -1967,37 +2104,49 @@ export function NavigationRenderer({ ) : null; + const favoritesRows = favoritesSection + ? 1 + (showPinned ? pinnedItems.length : 0) + React.Children.toArray(extraFavorites).length + : 0; // --- No explicit groups → wrap in a single SidebarGroup --- if (!hasGroups) { return ( - - {favoritesSection} - - - - {sorted.map((item) => ( - - ))} - - - - + + + {favoritesSection} + + + + firstFrameSectionCount(sorted.map(firstViewRows), favoritesRows)} + > + {sorted.map((item) => ( + + ))} + + + + + + ); } // Mixed content: render groups inline, wrap consecutive leaf items const fragments: React.ReactNode[] = []; + // The top-level entries each fragment draws, for the phone first frame. + const fragmentItems: NavigationItem[][] = []; let leafBuffer: NavigationItem[] = []; const flushLeaves = (key: string) => { if (leafBuffer.length === 0) return; const leaves = leafBuffer; leafBuffer = []; + fragmentItems.push(leaves); fragments.push( @@ -2018,6 +2167,7 @@ export function NavigationRenderer({ sorted.forEach((item, idx) => { if (item.type === 'group') { flushLeaves(`leaf-${idx}`); + fragmentItems.push([item]); fragments.push( - {favoritesSection} - {fragments} - + + + {favoritesSection} + + firstFrameSectionCount( + fragmentItems.map((entries) => entries.reduce((rows, entry) => rows + firstViewRows(entry), 0)), + favoritesRows, + ) + } + > + {fragments} + + + ); } diff --git a/ui/packages/layout/src/__tests__/NavigationRenderer.phoneDrawerOpen-29141.test.tsx b/ui/packages/layout/src/__tests__/NavigationRenderer.phoneDrawerOpen-29141.test.tsx new file mode 100644 index 00000000000..bcebf5563f8 --- /dev/null +++ b/ui/packages/layout/src/__tests__/NavigationRenderer.phoneDrawerOpen-29141.test.tsx @@ -0,0 +1,177 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#29141 — opening the phone nav drawer renders each row once, and + * a long menu's opening frame draws only the rows that fit the window. + * + * Before: every row asked `useIsMobile()` itself. That hook answers `false` on + * its first render and corrects itself in an effect, so each time the drawer + * opened (the sheet mounts the tree afresh) the whole tree rendered at desktop + * size, then every row set state and the tree rendered a second time. At 4x + * CPU the showcase drawer (54 rows) took 300-580 ms to open. + * + * The harness opens the "drawer" the way the shell does: the sidebar provider + * is already mounted and settled at a phone's width, and the tree mounts under + * it. Each row with no `label` asks `resolveTargetLabel` for its text once per + * render, so the spy counts row renders. A `Profiler` records the links in the + * DOM at each commit of the tree. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import React from 'react'; +import { act, cleanup, render, screen } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import type { NavigationItem } from '@object-ui/types'; +import { SidebarProvider } from '@object-ui/components'; +import { NavigationRenderer, type NavTargetLabelResolver } from '../NavigationRenderer'; + +const BASE = '/apps/showcase'; + +beforeAll(() => { + // jsdom has no `matchMedia`; the sidebar provider's `useIsMobile` reads it. + window.matchMedia ??= ((query: string) => ({ + matches: false, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + })) as typeof window.matchMedia; +}); + +const ORIGINAL = { width: window.innerWidth, height: window.innerHeight }; +function setWindow(width: number, height: number) { + Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: width }); + Object.defineProperty(window, 'innerHeight', { configurable: true, writable: true, value: height }); +} + +afterEach(() => { + cleanup(); + setWindow(ORIGINAL.width, ORIGINAL.height); +}); + +/** `count` unlabelled object entries: each shows its target's label. */ +const entries = (count: number): NavigationItem[] => + Array.from({ length: count }, (_, i) => ({ + id: `entry_${i + 1}`, + type: 'object', + objectName: `object_${i + 1}`, + })) as NavigationItem[]; + +/** + * Mounts the provider, lets it settle at the window's width, then opens the + * tree under it. Returns the label spy and the link count at each commit. + */ +async function openDrawer(items: NavigationItem[], width: number, height: number) { + setWindow(width, height); + const labelOf = vi.fn((target) => + target.kind === 'object' ? `Label ${target.objectName}` : undefined, + ); + const linksPerCommit: number[] = []; + let open: () => void = () => {}; + function Drawer() { + const [shown, setShown] = React.useState(false); + open = () => setShown(true); + if (!shown) return null; + return ( + { + linksPerCommit.push(document.querySelectorAll('a[href]').length); + }} + > + + + ); + } + render( + + + + + , + ); + await act(async () => { + open(); + }); + return { labelOf, linksPerCommit }; +} + +/** How many times each object's row rendered. */ +function rendersPerRow(labelOf: ReturnType): Map { + const counts = new Map(); + for (const [target] of labelOf.mock.calls) { + const name = (target as { objectName: string }).objectName; + counts.set(name, (counts.get(name) ?? 0) + 1); + } + return counts; +} + +describe('NavigationRenderer — opening the phone drawer (objectstack#29141)', () => { + it('renders each row once, in one commit, when the menu fits the window', async () => { + const { labelOf, linksPerCommit } = await openDrawer(entries(6), 375, 844); + const counts = rendersPerRow(labelOf); + expect([...counts.keys()]).toEqual(entries(6).map((e) => (e as { objectName: string }).objectName)); + expect([...counts.values()].every((n) => n === 1)).toBe(true); + expect(linksPerCommit).toEqual([6]); + // Drawn at phone size, from the first commit. + expect(screen.getByRole('link', { name: 'Label object_1' })).toHaveClass('min-h-[44px]'); + }); + + it('a long menu draws the rows that fit in the opening frame, the rest right after, each row once', async () => { + const fit = Math.ceil(844 / 44); + const { labelOf, linksPerCommit } = await openDrawer(entries(60), 375, 844); + // The opening frame holds at least the rows the window shows, and not the whole menu. + expect(linksPerCommit.length).toBe(2); + expect(linksPerCommit[0]).toBeGreaterThanOrEqual(fit); + expect(linksPerCommit[0]).toBeLessThan(60); + // Then every entry, in order, each rendered once: the rows drawn first are not drawn again. + expect(linksPerCommit[1]).toBe(60); + const counts = rendersPerRow(labelOf); + expect(counts.size).toBe(60); + expect([...counts.values()].every((n) => n === 1)).toBe(true); + const names = screen.getAllByRole('link').map((a) => a.textContent); + expect(names).toEqual(entries(60).map((_, i) => `Label object_${i + 1}`)); + }); + + it('a group counts its open children toward the opening frame, and every row still shows', async () => { + const items: NavigationItem[] = [ + { id: 'grp_a', type: 'group', label: 'Group A', children: entries(30) }, + { + id: 'grp_b', + type: 'group', + label: 'Group B', + children: entries(40).slice(30).map((e) => ({ ...e, id: `b_${e.id}` })), + }, + ] as NavigationItem[]; + const { linksPerCommit } = await openDrawer(items, 375, 844); + // Group A (31 rows) fills the window, so Group B joins after the opening frame. + expect(linksPerCommit[0]).toBe(30); + expect(linksPerCommit[linksPerCommit.length - 1]).toBe(40); + expect(screen.getByRole('button', { name: 'Group B' })).toHaveAttribute('aria-expanded', 'true'); + }); + + it('on a wide window the whole menu draws at once, and each row keeps its icon-rail tooltip', async () => { + const { labelOf, linksPerCommit } = await openDrawer(entries(60), 1280, 844); + // Every row from the first commit (the tooltips' own state may commit again; no row re-renders). + expect(linksPerCommit[0]).toBe(60); + expect([...rendersPerRow(labelOf).values()].every((n) => n === 1)).toBe(true); + // The tooltip trigger marks the row; on a phone the primitive would draw that tooltip hidden. + expect(screen.getByRole('link', { name: 'Label object_1' })).toHaveAttribute('data-state', 'closed'); + expect(screen.getByRole('link', { name: 'Label object_1' })).not.toHaveClass('min-h-[44px]'); + }); + + it('a phone row carries no tooltip trigger', async () => { + await openDrawer(entries(3), 375, 844); + expect(screen.getByRole('link', { name: 'Label object_1' })).not.toHaveAttribute('data-state'); + }); +});