From 1eccf3bd9cecd45f616b699802935edd6714b025 Mon Sep 17 00:00:00 2001 From: "mastra-platform[bot]" Date: Tue, 17 Nov 2026 06:46:56 +0000 Subject: [PATCH 1/5] feat(factory-ui): swipe the session panel in from the right edge on phones On phones the session panel only opened as a popover from a header button, while navigation already slid in with a swipe from the left. The panel now behaves the same way from the other edge: a leftward swipe slides the page left to uncover it, and a rightward swipe, Escape, or a tap on the page puts it back. The sidebar's reveal gesture now takes a side and a namespace, so both drawers share one implementation. They also share one gesture scope, and whichever drawer is out claims it, so a swipe never moves both at once. Co-Authored-By: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> --- .changeset/swift-asides-slide.md | 15 ++ .../components/WorkspaceFilesToggle.tsx | 26 ++- .../__tests__/WorkspaceFiles.msw.test.tsx | 67 ++++++- .../src/ds/components/Sidebar/index.ts | 1 + .../components/Sidebar/root/aside-reveal.css | 86 +++++++++ .../Sidebar/root/aside-reveal.test.tsx | 180 ++++++++++++++++++ .../components/Sidebar/root/aside-reveal.tsx | 135 +++++++++++++ .../components/Sidebar/root/reveal-focus.ts | 28 +++ .../Sidebar/root/sidebar-reveal.tsx | 31 +-- .../Sidebar/root/use-reveal-gesture.ts | 73 ++++--- .../src/ds/new/layout/app-shell/app-shell.tsx | 1 + 11 files changed, 588 insertions(+), 55 deletions(-) create mode 100644 .changeset/swift-asides-slide.md create mode 100644 packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.css create mode 100644 packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx create mode 100644 packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx create mode 100644 packages/playground-ui/src/ds/components/Sidebar/root/reveal-focus.ts diff --git a/.changeset/swift-asides-slide.md b/.changeset/swift-asides-slide.md new file mode 100644 index 00000000000..8ffd396f596 --- /dev/null +++ b/.changeset/swift-asides-slide.md @@ -0,0 +1,15 @@ +--- +'@mastra/playground-ui': minor +--- + +Added `AsideReveal`, a right-edge drawer for phones that works like the sidebar's mobile drawer. Swiping left anywhere in the app shell slides the page left to show the panel. Swiping right, pressing Escape, or tapping the page closes it. The sidebar and the aside use the same swipe handling, so a swipe moves only one of them: with either drawer open, the opposite swipe closes it and does not open the other. + +```tsx + + {/* ... */}}> + + + + + +``` diff --git a/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesToggle.tsx b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesToggle.tsx index d89f9e7e8aa..e358e84a6cd 100644 --- a/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesToggle.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesToggle.tsx @@ -1,7 +1,8 @@ import { Button } from '@mastra/playground-ui/components/Button'; import { cn } from '@mastra/playground-ui/utils/cn'; import { Popover, PopoverContent, PopoverTrigger } from '@mastra/playground-ui/components/Popover'; -import { useState } from 'react'; +import { AsideReveal, useMaybeSidebarState } from '@mastra/playground-ui/components/Sidebar'; +import { useRef, useState } from 'react'; import { useWorkspacePanel } from '../context/useWorkspacePanel'; import { cardRadiusClass, cardWidthStyle, popoverSizeClass } from '../layout'; @@ -11,7 +12,9 @@ import { IconSidebarSimpleRightWide } from '@mastra/playground-ui/icons/central/ export function WorkspaceFilesToggle() { const { open, setOpen, workspacePath, canDock } = useWorkspacePanel(); + const isMobile = useMaybeSidebarState()?.isMobile ?? false; const [size, setSize] = useState('compact'); + const triggerRef = useRef(null); if (!workspacePath) return null; @@ -35,6 +38,27 @@ export function WorkspaceFilesToggle() { ); } + // Phones get the panel as a right-edge drawer, swiped in like the navigation drawer on the left. + if (isMobile) { + return ( + <> + + + + + + ); + } + return ( diff --git a/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/__tests__/WorkspaceFiles.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/__tests__/WorkspaceFiles.msw.test.tsx index cf8118aacd9..0a900d2bace 100644 --- a/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/__tests__/WorkspaceFiles.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/__tests__/WorkspaceFiles.msw.test.tsx @@ -1,5 +1,5 @@ import { SidebarProvider } from '@mastra/playground-ui/components/Sidebar'; -import { act, screen, waitFor, within } from '@testing-library/react'; +import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { http, HttpResponse } from 'msw'; import { MemoryRouter, Route, Routes } from 'react-router'; @@ -406,4 +406,69 @@ describe('WorkspaceFiles', () => { expect(await screen.findByRole('button', { name: /^Changes(,|$)/ })).toBeInTheDocument(); }); }); + describe('on a phone', () => { + const PANEL_WIDTH = 300; + + beforeEach(() => { + vi.spyOn(window, 'matchMedia').mockImplementation( + query => + ({ + matches: true, + media: query, + onchange: null, + addListener: () => {}, + removeListener: () => {}, + addEventListener: () => {}, + removeEventListener: () => {}, + dispatchEvent: () => false, + }) as MediaQueryList, + ); + stubContainerWidth(390); + }); + + /** jsdom lays nothing out, so the drawer's width has to be given for a drag to measure against. */ + const giveDrawerWidth = () => { + const panel = document.querySelector('[data-aside-reveal-layer="panel"]'); + if (!panel) throw new Error('The session panel drawer is not mounted'); + Object.defineProperty(panel, 'offsetWidth', { configurable: true, value: PANEL_WIDTH }); + }; + + const dragLeft = (target: Element) => { + const at = (clientX: number) => ({ + touches: [{ identifier: 1, clientX, clientY: 400 }], + changedTouches: [{ identifier: 1, clientX, clientY: 400 }], + }); + fireEvent.touchStart(target, at(350)); + for (const x of [330, 300, 250, 200, 150]) fireEvent.touchMove(target, at(x)); + fireEvent.touchEnd(target, { touches: [], changedTouches: [{ identifier: 1, clientX: 150, clientY: 400 }] }); + }; + + it('slides the panel in from the right edge when the header toggle is pressed, and out on a tap beside it', async () => { + const user = userEvent.setup(); + renderPanel(); + + await user.click(await screen.findByRole('button', { name: 'Session panel' })); + + const drawer = await screen.findByRole('dialog', { name: 'Session panel' }); + expect(drawer.querySelector('[data-aside-reveal-layer="panel"]')).not.toBeNull(); + expect(await within(drawer).findByRole('button', { name: /^Changes(,|$)/ })).toBeInTheDocument(); + + await user.click(within(drawer).getByRole('button', { name: 'Close session panel' })); + + expect(screen.queryByRole('dialog', { name: 'Session panel' })).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Session panel' })).toHaveAttribute('aria-pressed', 'false'); + }); + + it('opens the panel when the page is swiped left', async () => { + renderPanel(); + await screen.findByRole('button', { name: 'Session panel' }); + await waitFor(giveDrawerWidth); + + dragLeft(screen.getByRole('banner')); + + const drawer = await screen.findByRole('dialog', { name: 'Session panel' }); + expect(await within(drawer).findByRole('button', { name: /^Changes(,|$)/ })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Session panel', pressed: true })).toBeInTheDocument(); + }); + }); }); diff --git a/packages/playground-ui/src/ds/components/Sidebar/index.ts b/packages/playground-ui/src/ds/components/Sidebar/index.ts index f539e0bf75e..ebaaac8a0e4 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/index.ts +++ b/packages/playground-ui/src/ds/components/Sidebar/index.ts @@ -27,6 +27,7 @@ export { type SidebarState, type SidebarStateContextValue, } from './root/sidebar-context'; +export { AsideReveal, type AsideRevealProps } from './root/aside-reveal'; export { SidebarMobileTrigger, type SidebarMobileTriggerProps } from './root/sidebar-mobile-trigger'; export { SidebarProvider, type SidebarProviderProps } from './root/sidebar-provider'; export { SIDEBAR_WIDTHS } from './root/sidebar-widths'; diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.css b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.css new file mode 100644 index 00000000000..b70305f029c --- /dev/null +++ b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.css @@ -0,0 +1,86 @@ +/* The right-edge mirror of sidebar-reveal.css: the page slides left instead of right. */ +@property --aside-reveal-drag { + syntax: '*'; + inherits: false; +} + +@property --aside-reveal-duration { + syntax: '*'; + inherits: false; +} + +@property --aside-reveal-progress { + syntax: ''; + inherits: false; + initial-value: 0; +} + +@property --aside-reveal-motion { + syntax: '*'; + inherits: false; +} + +[data-aside-reveal] { + --aside-reveal-width: calc(100vw - 3.5rem); + --aside-reveal-radius: 0 var(--studio-frame-radius, 1.5rem) var(--studio-frame-radius, 1.5rem) 0; + --aside-reveal-rest: 0; + --aside-reveal-settle: 320ms; +} + +[data-aside-reveal][data-aside-reveal-open='true'] { + --aside-reveal-rest: 1; + --aside-reveal-settle: 400ms; +} + +[data-aside-reveal] [data-aside-reveal-layer] { + --aside-reveal-progress: var(--aside-reveal-drag, var(--aside-reveal-rest)); + --aside-reveal-motion: var(--aside-reveal-duration, var(--aside-reveal-settle)) var(--aside-reveal-ease); +} + +@media (prefers-reduced-motion: reduce) { + [data-aside-reveal] [data-aside-reveal-layer] { + --aside-reveal-motion: 0ms; + } +} + +[data-aside-reveal-layer='panel'] { + scale: calc(0.95 + 0.05 * var(--aside-reveal-progress)); + opacity: var(--aside-reveal-progress); + transition: + scale var(--aside-reveal-motion), + opacity var(--aside-reveal-motion); +} + +[data-aside-reveal-layer='scrim'] { + translate: calc(-1 * var(--aside-reveal-progress) * var(--aside-reveal-width)) 0; + border-radius: var(--aside-reveal-radius); + opacity: var(--aside-reveal-progress); + transition: + translate var(--aside-reveal-motion), + opacity var(--aside-reveal-motion); +} + +[data-aside-reveal][data-aside-reveal-present='true'] [data-aside-reveal-layer='panel'] { + will-change: scale, opacity; +} + +[data-aside-reveal][data-aside-reveal-present='true'] [data-aside-reveal-layer='scrim'] { + will-change: translate, opacity; +} + +[data-aside-reveal][data-aside-reveal-present='true'] [data-aside-reveal-layer='page'] { + position: relative; + z-index: 1; + overflow: clip; + border-radius: var(--aside-reveal-radius); + box-shadow: + 0 0 0 1px var(--surface-rim), + var(--elevation-overlay); + translate: calc(-1 * var(--aside-reveal-progress) * var(--aside-reveal-width)) 0; + transition: translate var(--aside-reveal-motion); + will-change: translate; +} + +[data-aside-reveal][data-aside-reveal-present='true'] [data-slot='app-shell'] { + overflow-x: clip; +} diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx new file mode 100644 index 00000000000..b41c92c01d7 --- /dev/null +++ b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx @@ -0,0 +1,180 @@ +// @vitest-environment jsdom +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { useState } from 'react'; +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { AsideReveal, Sidebar, SidebarProvider } from '..'; +import { AppShell } from '@/ds/new/layout/app-shell'; + +const PANEL_WIDTH = 300; + +beforeAll(() => { + Element.prototype.getAnimations ??= () => []; + Object.defineProperty(window, 'matchMedia', { + configurable: true, + value: vi.fn().mockImplementation((query: string) => ({ + matches: true, + media: query, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + })), + }); +}); + +afterEach(() => cleanup()); + +function SessionPage() { + const [open, setOpen] = useState(false); + return ( + <> +

Session transcript

+ + +

Changed files

+
+ + ); +} + +function renderApp() { + const view = render( + + } + sidebar={ + + + + + + + + } + > + + + , + ); + for (const panel of document.querySelectorAll( + '[data-sidebar-reveal-layer="panel"], [data-aside-reveal-layer="panel"]', + )) { + Object.defineProperty(panel, 'offsetWidth', { configurable: true, value: PANEL_WIDTH }); + } + return view; +} + +function touch(type: 'touchstart' | 'touchmove' | 'touchend', target: Element, x: number, timeStamp: number) { + const event = new Event(type, { bubbles: true, cancelable: true }); + const point = { identifier: 1, clientX: x, clientY: 300 }; + Object.defineProperties(event, { + touches: { value: type === 'touchend' ? [] : [point] }, + changedTouches: { value: [point] }, + timeStamp: { value: timeStamp }, + }); + fireEvent(target, event); +} + +function drag(target: Element, from: number, to: number) { + touch('touchstart', target, from, 0); + touch('touchmove', target, from + Math.sign(to - from) * 10, 16); + touch('touchmove', target, (from + to) / 2, 200); + touch('touchmove', target, to, 400); + touch('touchend', target, to, 420); +} + +const sessionPanel = () => screen.queryByRole('dialog', { name: 'Session panel' }); +const navigation = () => screen.queryByRole('dialog', { name: 'Navigation' }); +const transcript = () => screen.getByText('Session transcript'); + +describe('AsideReveal', () => { + describe('when the page is dragged left past halfway and released', () => { + it('opens the panel and leaves navigation closed', () => { + renderApp(); + drag(transcript(), 350, 100); + + expect(sessionPanel()).not.toBeNull(); + expect(screen.getByText('Changed files')).toBeTruthy(); + expect(navigation()).toBeNull(); + }); + }); + + describe('when the page is dragged right', () => { + it('opens navigation, not the panel', () => { + renderApp(); + drag(transcript(), 20, 250); + + expect(navigation()).not.toBeNull(); + expect(sessionPanel()).toBeNull(); + }); + }); + + describe('when the page is nudged left a few pixels and released', () => { + it('springs back closed', () => { + renderApp(); + touch('touchstart', transcript(), 350, 0); + touch('touchmove', transcript(), 340, 16); + touch('touchmove', transcript(), 325, 200); + touch('touchend', transcript(), 325, 220); + + expect(sessionPanel()).toBeNull(); + }); + }); + + describe('while the panel is open', () => { + it('closes on a rightward drag without opening navigation', async () => { + renderApp(); + await userEvent.click(screen.getByRole('button', { name: 'Show details' })); + expect(sessionPanel()).not.toBeNull(); + + drag(screen.getByText('Changed files'), 100, 350); + + expect(sessionPanel()).toBeNull(); + expect(navigation()).toBeNull(); + }); + + it('closes on Escape and returns the page to the panel-less state', async () => { + renderApp(); + await userEvent.click(screen.getByRole('button', { name: 'Show details' })); + await userEvent.keyboard('{Escape}'); + + expect(sessionPanel()).toBeNull(); + await waitFor(() => expect(screen.queryByText('Changed files')).toBeNull()); + }); + + it('closes when the uncovered page is tapped', async () => { + renderApp(); + await userEvent.click(screen.getByRole('button', { name: 'Show details' })); + await userEvent.click(screen.getByRole('button', { name: 'Close session panel' })); + + expect(sessionPanel()).toBeNull(); + }); + }); + + describe('while navigation is open', () => { + it('closes navigation on a leftward drag without opening the panel', async () => { + renderApp(); + await userEvent.click(screen.getByRole('button', { name: 'Open navigation menu' })); + expect(navigation()).not.toBeNull(); + + drag(screen.getByRole('link', { name: 'Agents' }), 280, 20); + + expect(navigation()).toBeNull(); + expect(sessionPanel()).toBeNull(); + }); + }); + + describe('after the panel settles closed', () => { + it('lets a rightward drag open navigation again', async () => { + renderApp(); + await userEvent.click(screen.getByRole('button', { name: 'Show details' })); + await userEvent.keyboard('{Escape}'); + await waitFor(() => expect(screen.queryByText('Changed files')).toBeNull()); + + drag(transcript(), 20, 250); + + expect(navigation()).not.toBeNull(); + }); + }); +}); diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx new file mode 100644 index 00000000000..a4f3957d68e --- /dev/null +++ b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx @@ -0,0 +1,135 @@ +import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from 'react'; +import type { KeyboardEvent as ReactKeyboardEvent, ReactNode, RefObject } from 'react'; +import { createPortal, flushSync } from 'react-dom'; +import { focusFirstIn, inertOutside } from './reveal-focus'; +import { useMaybeSidebarState } from './sidebar-context'; +import { REVEAL_EASE, useRevealGesture } from './use-reveal-gesture'; +import { focusRingInset } from '@/ds/primitives/transitions'; +import { cn } from '@/lib/utils'; + +import './aside-reveal.css'; + +export type AsideRevealProps = { + open: boolean; + onOpenChange: (open: boolean) => void; + /** Names the drawer while it is open. */ + label: string; + /** Takes focus back when the drawer closes. */ + triggerRef?: RefObject; + /** Mounted only while the drawer is out: open, dragged, or settling closed. */ + children: ReactNode; + className?: string; +}; + +/** + * The right-edge counterpart of the sidebar's mobile drawer: a leftward swipe anywhere in the shell + * (or `open`) slides the page left to uncover the panel, and a rightward swipe, Escape, or a tap on the + * page puts it back. Shares the sidebar's gesture and scope, so only one of the two drawers is out at a time. + * Render it inside `SidebarProvider` and `AppShell`; it mounts beside the shell, not inside the page that moves. + */ +export function AsideReveal({ open, onOpenChange, label, triggerRef, children, className }: AsideRevealProps) { + const sidebar = useMaybeSidebarState(); + if (!sidebar) throw new Error('AsideReveal must be used within a SidebarProvider.'); + const { scopeRef } = sidebar; + const [scope, setScope] = useState(null); + const [present, setPresent] = useState(open); + const rootRef = useRef(null); + const panelRef = useRef(null); + const scrimRef = useRef(null); + + if (open && !present) setPresent(true); + + // A passive effect: the provider's ref on the scope attaches after its children's layout effects run. + useEffect(() => { + const element = scopeRef.current; + if (!element) return; + element.setAttribute('data-aside-reveal', ''); + element.style.setProperty('--aside-reveal-ease', REVEAL_EASE); + setScope(element); + return () => { + element.removeAttribute('data-aside-reveal'); + element.removeAttribute('data-aside-reveal-open'); + element.removeAttribute('data-aside-reveal-present'); + element.style.removeProperty('--aside-reveal-ease'); + }; + }, [scopeRef]); + + useLayoutEffect(() => { + scope?.setAttribute('data-aside-reveal-open', String(open)); + scope?.setAttribute('data-aside-reveal-present', String(present)); + }, [scope, open, present]); + + const returnFocus = useEffectEvent((root: Element) => { + const focused = document.activeElement; + if (!focused || focused === document.body || root.contains(focused)) { + triggerRef?.current?.focus({ preventScroll: true }); + } + }); + + useEffect(() => { + const root = rootRef.current; + if (!open || !root) return; + const releaseOutside = inertOutside(root); + panelRef.current?.focus({ preventScroll: true }); + return () => { + releaseOutside(); + returnFocus(root); + }; + }, [open, scope]); + + useRevealGesture({ + scopeRef, + name: 'aside', + side: 'right', + open, + onGrab: () => flushSync(() => setPresent(true)), + onRelease: onOpenChange, + onSettled: () => { + if (!open) setPresent(false); + }, + }); + + const closeOnEscape = (event: ReactKeyboardEvent) => { + if (event.key !== 'Escape' || event.defaultPrevented) return; + event.preventDefault(); + onOpenChange(false); + }; + + if (!scope) return null; + + return createPortal( +
+ scrimRef.current?.focus()} /> +
+ {present ? children : null} +
+
, + scope, + ); +} diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/reveal-focus.ts b/packages/playground-ui/src/ds/components/Sidebar/root/reveal-focus.ts new file mode 100644 index 00000000000..29716899c09 --- /dev/null +++ b/packages/playground-ui/src/ds/components/Sidebar/root/reveal-focus.ts @@ -0,0 +1,28 @@ +const TABBABLE = 'a[href], button, input, select, textarea, summary, [tabindex]'; + +export function focusFirstIn(container: HTMLElement | null) { + if (!container) return; + for (const candidate of container.querySelectorAll(TABBABLE)) { + if (!(candidate instanceof HTMLElement) || candidate.tabIndex < 0) continue; + candidate.focus(); + if (document.activeElement === candidate) return; + } + container.focus(); +} + +export function inertOutside(root: Element) { + const marked: Element[] = []; + let node = root; + while (node !== document.body && node.parentElement) { + const parent = node.parentElement; + for (const sibling of parent.children) { + if (sibling === node || sibling.hasAttribute('inert')) continue; + sibling.setAttribute('inert', ''); + marked.push(sibling); + } + node = parent; + } + return () => { + for (const element of marked) element.removeAttribute('inert'); + }; +} diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-reveal.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-reveal.tsx index 259eeb2544b..cd706ada645 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-reveal.tsx +++ b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-reveal.tsx @@ -1,6 +1,7 @@ import { useEffect, useEffectEvent, useRef } from 'react'; import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent, ReactNode } from 'react'; import { flushSync } from 'react-dom'; +import { focusFirstIn, inertOutside } from './reveal-focus'; import { useSidebar } from './sidebar-context'; import { REVEAL_EASE, useRevealGesture } from './use-reveal-gesture'; import { focusRingInset } from '@/ds/primitives/transitions'; @@ -9,7 +10,6 @@ import { cn } from '@/lib/utils'; import './sidebar-reveal.css'; const REVEAL_EASE_VAR = '--sidebar-reveal-ease'; -const TABBABLE = 'a[href], button, input, select, textarea, summary, [tabindex]'; type SidebarRevealProps = { children: ReactNode; @@ -54,6 +54,8 @@ export function SidebarReveal({ children, className, onClick }: SidebarRevealPro useRevealGesture({ scopeRef, + name: 'sidebar', + side: 'left', open: openMobile, onGrab: () => flushSync(() => setMobileDrawerPresent(true)), onRelease: setOpenMobile, @@ -105,30 +107,3 @@ export function SidebarReveal({ children, className, onClick }: SidebarRevealPro ); } - -function focusFirstIn(container: HTMLElement | null) { - if (!container) return; - for (const candidate of container.querySelectorAll(TABBABLE)) { - if (!(candidate instanceof HTMLElement) || candidate.tabIndex < 0) continue; - candidate.focus(); - if (document.activeElement === candidate) return; - } - container.focus(); -} - -function inertOutside(root: Element) { - const marked: Element[] = []; - let node = root; - while (node !== document.body && node.parentElement) { - const parent = node.parentElement; - for (const sibling of parent.children) { - if (sibling === node || sibling.hasAttribute('inert')) continue; - sibling.setAttribute('inert', ''); - marked.push(sibling); - } - node = parent; - } - return () => { - for (const element of marked) element.removeAttribute('inert'); - }; -} diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/use-reveal-gesture.ts b/packages/playground-ui/src/ds/components/Sidebar/root/use-reveal-gesture.ts index 602eb2d4b5b..3bb8ca2763c 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/use-reveal-gesture.ts +++ b/packages/playground-ui/src/ds/components/Sidebar/root/use-reveal-gesture.ts @@ -5,8 +5,8 @@ const EASE = [0.32, 0.72, 0, 1] as const; const EASE_START_SLOPE = EASE[1] / EASE[0]; export const REVEAL_EASE = `cubic-bezier(${EASE.join(', ')})`; -const DRAG_VAR = '--sidebar-reveal-drag'; -const DURATION_VAR = '--sidebar-reveal-duration'; +/** Marks which reveal holds the shared scope, so a drawer's swipes can't start the drawer on the other edge. */ +const OWNER_ATTR = 'data-reveal-owner'; const LOCK_DISTANCE_PX = 8; const TURN_DISTANCE_PX = 8; @@ -33,16 +33,27 @@ type Track = { samples: Sample[]; }; +export type RevealSide = 'left' | 'right'; + type RevealGestureOptions = { scopeRef: RefObject; + /** Namespaces the layer attribute (`data--reveal-layer`) and the drag variables (`---reveal-*`). */ + name: string; + /** The screen edge the panel sits on. A left panel opens on a rightward swipe, a right panel on a leftward one. */ + side: RevealSide; open: boolean; onGrab: () => void; onRelease: (open: boolean) => void; onSettled: () => void; }; -export function useRevealGesture({ scopeRef, open, onGrab, onRelease, onSettled }: RevealGestureOptions) { +export function useRevealGesture({ scopeRef, name, side, open, onGrab, onRelease, onSettled }: RevealGestureOptions) { const settleRef = useRef(0); + const layerAttr = `data-${name}-reveal-layer`; + const dragVar = `--${name}-reveal-drag`; + const durationVar = `--${name}-reveal-duration`; + // Distances are tracked toward "open": positive opens whichever edge the panel is on. + const toward = side === 'left' ? 1 : -1; const isOpen = useEffectEvent(() => open); const handleGrab = useEffectEvent(onGrab); const handleRelease = useEffectEvent(onRelease); @@ -53,18 +64,21 @@ export function useRevealGesture({ scopeRef, open, onGrab, onRelease, onSettled if (!scope) return; const token = ++settleRef.current; requestAnimationFrame(() => { - const running = revealLayers(scope).flatMap(layer => layer.getAnimations()); + const running = revealLayers(scope, layerAttr).flatMap(layer => layer.getAnimations()); void Promise.allSettled(running.map(animation => animation.finished)).then(() => { if (token !== settleRef.current) return; - clearRevealVar(revealLayers(scope), DURATION_VAR); + clearRevealVar(revealLayers(scope, layerAttr), durationVar); + if (!isOpen()) releaseOwner(scope, name); handleSettled(); }); }); }); useEffect(() => { + const scope = scopeRef.current; + if (open && scope) scope.setAttribute(OWNER_ATTR, name); settle(); - }, [open]); + }, [open, scopeRef, name]); useEffect(() => { const scope = scopeRef.current; @@ -76,9 +90,9 @@ export function useRevealGesture({ scopeRef, open, onGrab, onRelease, onSettled const committed = Math.abs(ended.offset - ended.origin) >= COMMIT_DISTANCE_PX; const endsOpen = committed ? ended.heading > 0 : ended.startedOpen; const distance = Math.abs((endsOpen ? ended.width : 0) - ended.offset); - const speedTowardTarget = endsOpen ? velocity : -velocity; - setRevealVar(ended.layers, DURATION_VAR, `${settleDuration(distance, speedTowardTarget)}ms`); - clearRevealVar(ended.layers, DRAG_VAR); + const speedTowardTarget = (endsOpen ? velocity : -velocity) * toward; + setRevealVar(ended.layers, durationVar, `${settleDuration(distance, speedTowardTarget)}ms`); + clearRevealVar(ended.layers, dragVar); handleRelease(endsOpen); settle(); }; @@ -88,22 +102,26 @@ export function useRevealGesture({ scopeRef, open, onGrab, onRelease, onSettled const dy = touch.clientY - current.startY; if (Math.hypot(dx, dy) < LOCK_DISTANCE_PX) return 'pending'; - const layers = revealLayers(scope); - const width = layerNamed(layers, 'panel')?.offsetWidth ?? 0; + const owner = scope.getAttribute(OWNER_ATTR); + if (owner && owner !== name) return 'ignored'; + const layers = revealLayers(scope, layerAttr); + const width = layerNamed(layers, layerAttr, 'panel')?.offsetWidth ?? 0; const opening = !isOpen(); - if (!width || Math.abs(dx) <= Math.abs(dy) || dx > 0 !== opening) return 'ignored'; + if (!width || Math.abs(dx) <= Math.abs(dy) || dx * toward > 0 !== opening) return 'ignored'; if (ownsHorizontalSwipe(current.target, scope, dx)) return 'ignored'; current.locked = true; current.startedOpen = !opening; current.width = width; current.startX += Math.sign(dx) * LOCK_DISTANCE_PX; - current.origin = liveOffset(layerNamed(layers, 'scrim')) ?? (opening ? 0 : width); - current.heading = Math.sign(dx); + const live = liveOffset(layerNamed(layers, layerAttr, 'scrim')); + current.origin = live === undefined ? (opening ? 0 : width) : live * toward; + current.heading = Math.sign(dx * toward); current.turn = current.origin; current.layers = layers; - setRevealVar(layers, DURATION_VAR, '0ms'); + setRevealVar(layers, durationVar, '0ms'); settleRef.current++; + scope.setAttribute(OWNER_ATTR, name); handleGrab(); return 'locked'; }; @@ -149,9 +167,9 @@ export function useRevealGesture({ scopeRef, open, onGrab, onRelease, onSettled } if (event.cancelable) event.preventDefault(); - current.offset = Math.min(current.width, Math.max(0, current.origin + touch.clientX - current.startX)); + current.offset = Math.min(current.width, Math.max(0, current.origin + (touch.clientX - current.startX) * toward)); steer(current); - setRevealVar(current.layers, DRAG_VAR, String(current.offset / current.width)); + setRevealVar(current.layers, dragVar, String(current.offset / current.width)); }; const onTouchEnd = (event: TouchEvent) => { @@ -172,19 +190,24 @@ export function useRevealGesture({ scopeRef, open, onGrab, onRelease, onSettled scope.removeEventListener('touchend', onTouchEnd); scope.removeEventListener('touchcancel', onTouchEnd); settles.current++; - const layers = revealLayers(scope); - clearRevealVar(layers, DRAG_VAR); - clearRevealVar(layers, DURATION_VAR); + const layers = revealLayers(scope, layerAttr); + clearRevealVar(layers, dragVar); + clearRevealVar(layers, durationVar); + releaseOwner(scope, name); }; - }, [scopeRef]); + }, [scopeRef, layerAttr, dragVar, durationVar, name, toward]); } -function revealLayers(scope: ParentNode) { - return Array.from(scope.querySelectorAll('[data-sidebar-reveal-layer]')); +function revealLayers(scope: ParentNode, layerAttr: string) { + return Array.from(scope.querySelectorAll(`[${layerAttr}]`)); } -function layerNamed(layers: readonly HTMLElement[], name: 'panel' | 'scrim') { - return layers.find(layer => layer.dataset.sidebarRevealLayer === name); +function layerNamed(layers: readonly HTMLElement[], layerAttr: string, name: 'panel' | 'scrim') { + return layers.find(layer => layer.getAttribute(layerAttr) === name); +} + +function releaseOwner(scope: Element, name: string) { + if (scope.getAttribute(OWNER_ATTR) === name) scope.removeAttribute(OWNER_ATTR); } function setRevealVar(layers: readonly HTMLElement[], name: string, value: string) { diff --git a/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.tsx b/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.tsx index c4f6024cc06..eef5c983c89 100644 --- a/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.tsx +++ b/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.tsx @@ -30,6 +30,7 @@ export function AppShell({ children, className, edgeToEdge, mobileHeader, ref, s data-slot="app-shell-content" className="flex h-full min-h-0 min-w-0 flex-col" data-sidebar-reveal-layer="page" + data-aside-reveal-layer="page" > {mobileHeader}
Date: Tue, 17 Nov 2026 07:04:47 +0000 Subject: [PATCH 2/5] refactor(playground-ui): share one edge-drawer shell and drive reveal state from CSS Both edge drawers had their own copy of the modal markup, focus trap, Escape handling and inert-outside logic, and the aside synced attributes onto the shared scope from effects and set state during render. One RevealDrawer now owns that markup; the provider exposes its scope element through a stable callback ref so the aside can portal into it, and the stylesheets read open/present state with :has() instead of JS-written scope markers. Also closes two one-drawer-at-a-time gaps from review: the sidebar shortcut can no longer open navigation over an open aside, and focus returns to whatever opened a drawer when no trigger ref is given. Co-Authored-By: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> --- .../components/WorkspaceFilesToggle.tsx | 92 +++++++----- .../components/Sidebar/root/aside-reveal.css | 21 +-- .../Sidebar/root/aside-reveal.test.tsx | 25 +++- .../components/Sidebar/root/aside-reveal.tsx | 116 ++++----------- .../components/Sidebar/root/reveal-drawer.tsx | 136 ++++++++++++++++++ .../components/Sidebar/root/reveal-focus.ts | 28 ---- .../Sidebar/root/sidebar-context.ts | 6 +- .../Sidebar/root/sidebar-provider.tsx | 19 ++- .../Sidebar/root/sidebar-reveal.css | 16 +-- .../Sidebar/root/sidebar-reveal.tsx | 96 +++---------- .../Sidebar/root/sidebar-root.test.tsx | 2 +- .../Sidebar/root/use-reveal-gesture.ts | 9 +- .../src/ds/new/layout/app-shell/app-shell.css | 2 +- .../layout/app-shell/app-shell.stories.tsx | 60 +++++++- 14 files changed, 364 insertions(+), 264 deletions(-) create mode 100644 packages/playground-ui/src/ds/components/Sidebar/root/reveal-drawer.tsx delete mode 100644 packages/playground-ui/src/ds/components/Sidebar/root/reveal-focus.ts diff --git a/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesToggle.tsx b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesToggle.tsx index e358e84a6cd..45922f0ebea 100644 --- a/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesToggle.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesToggle.tsx @@ -1,8 +1,10 @@ import { Button } from '@mastra/playground-ui/components/Button'; +import type { ButtonProps } from '@mastra/playground-ui/components/Button'; import { cn } from '@mastra/playground-ui/utils/cn'; import { Popover, PopoverContent, PopoverTrigger } from '@mastra/playground-ui/components/Popover'; import { AsideReveal, useMaybeSidebarState } from '@mastra/playground-ui/components/Sidebar'; import { useRef, useState } from 'react'; +import type { Ref } from 'react'; import { useWorkspacePanel } from '../context/useWorkspacePanel'; import { cardRadiusClass, cardWidthStyle, popoverSizeClass } from '../layout'; @@ -13,58 +15,72 @@ import { IconSidebarSimpleRightWide } from '@mastra/playground-ui/icons/central/ export function WorkspaceFilesToggle() { const { open, setOpen, workspacePath, canDock } = useWorkspacePanel(); const isMobile = useMaybeSidebarState()?.isMobile ?? false; - const [size, setSize] = useState('compact'); - const triggerRef = useRef(null); if (!workspacePath) return null; - const setPopoverOpen = (next: boolean) => { - if (next) setSize('compact'); - setOpen(next); - }; - if (canDock) { return ( - + /> ); } // Phones get the panel as a right-edge drawer, swiped in like the navigation drawer on the left. - if (isMobile) { - return ( - <> - - - - - - ); - } + if (isMobile) return ; + + return ; +} + +type PanelProps = { open: boolean; setOpen: (open: boolean) => void }; + +function PanelButton({ + open, + ref, + ...props +}: { open: boolean; ref?: Ref } & Omit) { + return ( + + ); +} + +const keepSize = () => {}; + +function PanelDrawer({ open, setOpen }: PanelProps) { + const triggerRef = useRef(null); + return ( + <> + setOpen(!open)} /> + + {/* The drawer is full height whatever the view, so it ignores size changes. */} + + + + ); +} + +function PanelPopover({ open, setOpen }: PanelProps) { + const [size, setSize] = useState('compact'); + const onOpenChange = (next: boolean) => { + if (next) setSize('compact'); + setOpen(next); + }; return ( - + - + [data-reveal-drawer='aside']) { --aside-reveal-width: calc(100vw - 3.5rem); --aside-reveal-radius: 0 var(--studio-frame-radius, 1.5rem) var(--studio-frame-radius, 1.5rem) 0; --aside-reveal-rest: 0; --aside-reveal-settle: 320ms; } -[data-aside-reveal][data-aside-reveal-open='true'] { +[data-sidebar-scope]:has(> [data-reveal-drawer='aside'][data-open='true']) { --aside-reveal-rest: 1; --aside-reveal-settle: 400ms; } -[data-aside-reveal] [data-aside-reveal-layer] { +[data-aside-reveal-layer] { --aside-reveal-progress: var(--aside-reveal-drag, var(--aside-reveal-rest)); - --aside-reveal-motion: var(--aside-reveal-duration, var(--aside-reveal-settle)) var(--aside-reveal-ease); + --aside-reveal-motion: var(--aside-reveal-duration, var(--aside-reveal-settle)) var(--reveal-ease); } @media (prefers-reduced-motion: reduce) { - [data-aside-reveal] [data-aside-reveal-layer] { + [data-aside-reveal-layer] { --aside-reveal-motion: 0ms; } } @@ -60,15 +61,15 @@ opacity var(--aside-reveal-motion); } -[data-aside-reveal][data-aside-reveal-present='true'] [data-aside-reveal-layer='panel'] { +[data-reveal-drawer='aside'][data-present='true'] [data-aside-reveal-layer='panel'] { will-change: scale, opacity; } -[data-aside-reveal][data-aside-reveal-present='true'] [data-aside-reveal-layer='scrim'] { +[data-reveal-drawer='aside'][data-present='true'] [data-aside-reveal-layer='scrim'] { will-change: translate, opacity; } -[data-aside-reveal][data-aside-reveal-present='true'] [data-aside-reveal-layer='page'] { +[data-sidebar-scope]:has(> [data-reveal-drawer='aside'][data-present='true']) [data-aside-reveal-layer='page'] { position: relative; z-index: 1; overflow: clip; @@ -81,6 +82,6 @@ will-change: translate; } -[data-aside-reveal][data-aside-reveal-present='true'] [data-slot='app-shell'] { +[data-sidebar-scope]:has(> [data-reveal-drawer='aside'][data-present='true']) [data-slot='app-shell'] { overflow-x: clip; } diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx index b41c92c01d7..8fd49334e2e 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx +++ b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx @@ -38,9 +38,9 @@ function SessionPage() { ); } -function renderApp() { +function renderApp({ shortcut = false }: { shortcut?: boolean } = {}) { const view = render( - + } sidebar={ @@ -150,6 +150,27 @@ describe('AsideReveal', () => { expect(sessionPanel()).toBeNull(); }); + + it('returns focus to the control that opened it, even without a trigger ref', async () => { + renderApp(); + const opener = screen.getByRole('button', { name: 'Show details' }); + await userEvent.click(opener); + expect(document.activeElement).not.toBe(opener); + + await userEvent.keyboard('{Escape}'); + + expect(document.activeElement).toBe(opener); + }); + + it('ignores the sidebar shortcut, so navigation never opens over the panel', async () => { + renderApp({ shortcut: true }); + await userEvent.click(screen.getByRole('button', { name: 'Show details' })); + + fireEvent.keyDown(window, { code: 'KeyB', key: 'b', ctrlKey: true }); + + expect(navigation()).toBeNull(); + expect(sessionPanel()).not.toBeNull(); + }); }); describe('while navigation is open', () => { diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx index a4f3957d68e..6834d50cf06 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx +++ b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx @@ -1,10 +1,9 @@ -import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from 'react'; -import type { KeyboardEvent as ReactKeyboardEvent, ReactNode, RefObject } from 'react'; +import { useState } from 'react'; +import type { ReactNode, RefObject } from 'react'; import { createPortal, flushSync } from 'react-dom'; -import { focusFirstIn, inertOutside } from './reveal-focus'; +import { RevealDrawer } from './reveal-drawer'; import { useMaybeSidebarState } from './sidebar-context'; -import { REVEAL_EASE, useRevealGesture } from './use-reveal-gesture'; -import { focusRingInset } from '@/ds/primitives/transitions'; +import { useRevealGesture } from './use-reveal-gesture'; import { cn } from '@/lib/utils'; import './aside-reveal.css'; @@ -25,111 +24,48 @@ export type AsideRevealProps = { * The right-edge counterpart of the sidebar's mobile drawer: a leftward swipe anywhere in the shell * (or `open`) slides the page left to uncover the panel, and a rightward swipe, Escape, or a tap on the * page puts it back. Shares the sidebar's gesture and scope, so only one of the two drawers is out at a time. - * Render it inside `SidebarProvider` and `AppShell`; it mounts beside the shell, not inside the page that moves. + * Render it inside `SidebarProvider` and `AppShell`; it portals beside the shell, not inside the page that moves. */ export function AsideReveal({ open, onOpenChange, label, triggerRef, children, className }: AsideRevealProps) { const sidebar = useMaybeSidebarState(); if (!sidebar) throw new Error('AsideReveal must be used within a SidebarProvider.'); - const { scopeRef } = sidebar; - const [scope, setScope] = useState(null); - const [present, setPresent] = useState(open); - const rootRef = useRef(null); - const panelRef = useRef(null); - const scrimRef = useRef(null); + const { scopeRef, scope } = sidebar; + // Held out past `open` while a drag or the closing slide is still on screen. + const [held, setHeld] = useState(false); + const present = open || held; - if (open && !present) setPresent(true); - - // A passive effect: the provider's ref on the scope attaches after its children's layout effects run. - useEffect(() => { - const element = scopeRef.current; - if (!element) return; - element.setAttribute('data-aside-reveal', ''); - element.style.setProperty('--aside-reveal-ease', REVEAL_EASE); - setScope(element); - return () => { - element.removeAttribute('data-aside-reveal'); - element.removeAttribute('data-aside-reveal-open'); - element.removeAttribute('data-aside-reveal-present'); - element.style.removeProperty('--aside-reveal-ease'); - }; - }, [scopeRef]); - - useLayoutEffect(() => { - scope?.setAttribute('data-aside-reveal-open', String(open)); - scope?.setAttribute('data-aside-reveal-present', String(present)); - }, [scope, open, present]); - - const returnFocus = useEffectEvent((root: Element) => { - const focused = document.activeElement; - if (!focused || focused === document.body || root.contains(focused)) { - triggerRef?.current?.focus({ preventScroll: true }); - } - }); - - useEffect(() => { - const root = rootRef.current; - if (!open || !root) return; - const releaseOutside = inertOutside(root); - panelRef.current?.focus({ preventScroll: true }); - return () => { - releaseOutside(); - returnFocus(root); - }; - }, [open, scope]); + const close = () => { + setHeld(true); + onOpenChange(false); + }; useRevealGesture({ scopeRef, name: 'aside', side: 'right', open, - onGrab: () => flushSync(() => setPresent(true)), + onGrab: () => flushSync(() => setHeld(true)), onRelease: onOpenChange, onSettled: () => { - if (!open) setPresent(false); + if (!open) setHeld(false); }, }); - const closeOnEscape = (event: ReactKeyboardEvent) => { - if (event.key !== 'Escape' || event.defaultPrevented) return; - event.preventDefault(); - onOpenChange(false); - }; - if (!scope) return null; return createPortal( -
- scrimRef.current?.focus()} /> -
- {present ? children : null} -
-
, + {present ? children : null} + , scope, ); } diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/reveal-drawer.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/reveal-drawer.tsx new file mode 100644 index 00000000000..35c92476875 --- /dev/null +++ b/packages/playground-ui/src/ds/components/Sidebar/root/reveal-drawer.tsx @@ -0,0 +1,136 @@ +import { useEffect, useEffectEvent, useRef } from 'react'; +import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent, ReactNode, RefObject } from 'react'; +import { focusRingInset } from '@/ds/primitives/transitions'; +import { cn } from '@/lib/utils'; + +const TABBABLE = 'a[href], button, input, select, textarea, summary, [tabindex]'; + +type RevealDrawerProps = { + /** Namespaces the layer attributes the reveal gesture and stylesheet drive: `data--reveal-layer`. */ + name: 'sidebar' | 'aside'; + open: boolean; + /** Out at all: open, dragged, or settling closed. Hidden when false. */ + present: boolean; + label: string; + closeLabel: string; + onClose: () => void; + /** Takes focus back when the drawer closes. */ + triggerRef: RefObject | undefined; + /** Positions and sizes the panel against its edge. */ + panelClassName: string; + onPanelClick?: (event: MouseEvent) => void; + children: ReactNode; +}; + +/** + * The markup both edge drawers share: a modal panel, a scrim over the uncovered page, and a focus trap. + * Motion comes from the reveal stylesheets reading the layer attributes; the gesture lives in `useRevealGesture`. + */ +export function RevealDrawer({ + name, + open, + present, + label, + closeLabel, + onClose, + triggerRef, + panelClassName, + onPanelClick, + children, +}: RevealDrawerProps) { + const rootRef = useRef(null); + const panelRef = useRef(null); + const scrimRef = useRef(null); + const layerAttr = `data-${name}-reveal-layer`; + + const returnFocus = useEffectEvent((root: Element, opener: HTMLElement | null) => { + const focused = document.activeElement; + if (!focused || focused === document.body || root.contains(focused)) { + (triggerRef?.current ?? opener)?.focus({ preventScroll: true }); + } + }); + + useEffect(() => { + const root = rootRef.current; + if (!open || !root) return; + const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null; + const releaseOutside = inertOutside(root); + panelRef.current?.focus({ preventScroll: true }); + return () => { + releaseOutside(); + returnFocus(root, opener); + }; + }, [open]); + + const closeOnEscape = (event: ReactKeyboardEvent) => { + if (event.key !== 'Escape' || event.defaultPrevented) return; + event.preventDefault(); + onClose(); + }; + + return ( +
+ scrimRef.current?.focus()} /> +
+ {children} +
+
+ ); +} + +function focusFirstIn(container: HTMLElement | null) { + if (!container) return; + for (const candidate of container.querySelectorAll(TABBABLE)) { + if (!(candidate instanceof HTMLElement) || candidate.tabIndex < 0) continue; + candidate.focus(); + if (document.activeElement === candidate) return; + } + container.focus(); +} + +function inertOutside(root: Element) { + const marked: Element[] = []; + let node = root; + while (node !== document.body && node.parentElement) { + const parent = node.parentElement; + for (const sibling of parent.children) { + if (sibling === node || sibling.hasAttribute('inert')) continue; + sibling.setAttribute('inert', ''); + marked.push(sibling); + } + node = parent; + } + return () => { + for (const element of marked) element.removeAttribute('inert'); + }; +} diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/reveal-focus.ts b/packages/playground-ui/src/ds/components/Sidebar/root/reveal-focus.ts deleted file mode 100644 index 29716899c09..00000000000 --- a/packages/playground-ui/src/ds/components/Sidebar/root/reveal-focus.ts +++ /dev/null @@ -1,28 +0,0 @@ -const TABBABLE = 'a[href], button, input, select, textarea, summary, [tabindex]'; - -export function focusFirstIn(container: HTMLElement | null) { - if (!container) return; - for (const candidate of container.querySelectorAll(TABBABLE)) { - if (!(candidate instanceof HTMLElement) || candidate.tabIndex < 0) continue; - candidate.focus(); - if (document.activeElement === candidate) return; - } - container.focus(); -} - -export function inertOutside(root: Element) { - const marked: Element[] = []; - let node = root; - while (node !== document.body && node.parentElement) { - const parent = node.parentElement; - for (const sibling of parent.children) { - if (sibling === node || sibling.hasAttribute('inert')) continue; - sibling.setAttribute('inert', ''); - marked.push(sibling); - } - node = parent; - } - return () => { - for (const element of marked) element.removeAttribute('inert'); - }; -} diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-context.ts b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-context.ts index cb14d531a64..1d3f86f93b1 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-context.ts +++ b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-context.ts @@ -13,6 +13,7 @@ type SidebarContextValue = { collapsedWidth: number; isMobile: boolean; openMobile: boolean; + mobileDrawerPresent: boolean; mobileTriggerRef: React.RefObject; setOpenMobile: (open: boolean) => void; setMobileDrawerPresent: (present: boolean) => void; @@ -23,6 +24,8 @@ type SidebarContextValue = { commit: () => void; setGestureActive: (active: boolean) => void; scopeRef: React.RefObject; + /** The scope element once mounted, for drawers that portal into it. */ + scope: HTMLDivElement | null; panelRef: React.RefObject; LinkComponent?: LinkComponent; }; @@ -31,6 +34,7 @@ type SidebarContextValue = { // do not re-render when the mobile drawer toggles. export type MobileDrawerContextValue = { openMobile: boolean; + mobileDrawerPresent: boolean; mobileTriggerRef: React.RefObject; setOpenMobile: (open: boolean) => void; setMobileDrawerPresent: (present: boolean) => void; @@ -38,7 +42,7 @@ export type MobileDrawerContextValue = { export type SidebarStateContextValue = Omit< SidebarContextValue, - 'openMobile' | 'mobileTriggerRef' | 'setOpenMobile' | 'setMobileDrawerPresent' + 'openMobile' | 'mobileDrawerPresent' | 'mobileTriggerRef' | 'setOpenMobile' | 'setMobileDrawerPresent' >; export const SidebarContext = React.createContext(null); diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-provider.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-provider.tsx index 4e45cc4bbd2..a0c38235bd8 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-provider.tsx +++ b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-provider.tsx @@ -3,6 +3,7 @@ import type { CSSProperties } from 'react'; import { SidebarContext, MobileDrawerContext } from './sidebar-context'; import type { MobileDrawerContextValue, SidebarState } from './sidebar-context'; import { SIDEBAR_WIDTHS } from './sidebar-widths'; +import { REVEAL_EASE, revealOwnedByOther } from './use-reveal-gesture'; import type { LinkComponent } from '@/ds/types/link-component'; const SIDEBAR_STATE_KEY = 'sidebar:state'; @@ -18,6 +19,7 @@ type InitialSidebarState = { type SidebarScopeStyle = CSSProperties & { '--sidebar-width': string; '--sidebar-width-mobile': string; + '--reveal-ease': string; }; export type SidebarProviderProps = { @@ -107,6 +109,12 @@ export function SidebarProvider({ stateRef.current = state; const scopeRef = React.useRef(null); + const [scope, setScope] = React.useState(null); + // Stable for the provider's lifetime, so React attaches it once. + const [attachScope] = React.useState(() => (node: HTMLDivElement | null) => { + scopeRef.current = node; + setScope(node); + }); const panelRef = React.useRef(null); React.useEffect(() => { @@ -119,6 +127,8 @@ export function SidebarProvider({ }, [mobileBreakpoint]); const setOpenMobile = React.useCallback((open: boolean) => { + // One drawer at a time: a shortcut must not open navigation over an open aside. + if (open && revealOwnedByOther(scopeRef.current, 'sidebar')) return; openMobileRef.current = open; if (open) setMobileDrawerPresent(true); setOpenMobileState(open); @@ -240,6 +250,7 @@ export function SidebarProvider({ commit, setGestureActive, scopeRef, + scope, panelRef, LinkComponent, }), @@ -258,24 +269,26 @@ export function SidebarProvider({ expand, commit, setGestureActive, + scope, LinkComponent, ], ); const drawerValue = React.useMemo( - () => ({ openMobile, mobileTriggerRef, setOpenMobile, setMobileDrawerPresent }), - [openMobile, setOpenMobile], + () => ({ openMobile, mobileDrawerPresent, mobileTriggerRef, setOpenMobile, setMobileDrawerPresent }), + [openMobile, mobileDrawerPresent, setOpenMobile], ); const scopeStyle: SidebarScopeStyle = { [SIDEBAR_WIDTH_VAR]: `${initial.state === 'collapsed' ? safeCollapsed : clamp(initial.width, safeMin, safeMax)}px`, '--sidebar-width-mobile': `${mobileWidth}px`, + '--reveal-ease': REVEAL_EASE, display: 'contents', }; return (
(null); - const panelRef = useRef(null); - const scrimRef = useRef(null); - - useEffect(() => { - const scope = scopeRef.current; - if (!scope) return; - scope.setAttribute('data-sidebar-reveal', ''); - scope.style.setProperty(REVEAL_EASE_VAR, REVEAL_EASE); - return () => { - scope.removeAttribute('data-sidebar-reveal'); - scope.style.removeProperty(REVEAL_EASE_VAR); - }; - }, [scopeRef]); - - const returnFocus = useEffectEvent((root: Element) => { - const focused = document.activeElement; - if (!focused || focused === document.body || root.contains(focused)) { - mobileTriggerRef.current?.focus({ preventScroll: true }); - } - }); - - useEffect(() => { - const root = rootRef.current; - if (!openMobile || !root) return; - const releaseOutside = inertOutside(root); - panelRef.current?.focus({ preventScroll: true }); - return () => { - releaseOutside(); - returnFocus(root); - }; - }, [openMobile]); + const { scopeRef, openMobile, mobileDrawerPresent, mobileTriggerRef, setOpenMobile, setMobileDrawerPresent } = + useSidebar(); useRevealGesture({ scopeRef, @@ -64,46 +29,19 @@ export function SidebarReveal({ children, className, onClick }: SidebarRevealPro }, }); - const closeOnEscape = (event: ReactKeyboardEvent) => { - if (event.key !== 'Escape' || event.defaultPrevented) return; - event.preventDefault(); - setOpenMobile(false); - }; - return ( -
setOpenMobile(false)} + triggerRef={mobileTriggerRef} + panelClassName={cn('left-0 w-(--sidebar-reveal-width)', className)} + onPanelClick={onClick} > - scrimRef.current?.focus()} /> -
-
{children}
-
-
+
{children}
+ ); } diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-root.test.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-root.test.tsx index e84d60a2bac..3bbcbc607fa 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-root.test.tsx +++ b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-root.test.tsx @@ -993,7 +993,7 @@ describe('Sidebar', () => { const mobileTrigger = screen.getByRole('button', { name: 'Open navigation menu' }); fireEvent.click(mobileTrigger); - expect(screen.getByRole('dialog', { name: 'Navigation' }).getAttribute('data-mobile-mode')).toBe('takeover'); + expect(screen.getByRole('dialog', { name: 'Navigation' }).getAttribute('data-reveal-drawer')).toBe('sidebar'); expect(screen.getByText('Observability')).toBeDefined(); expect(screen.queryByRole('button', { name: 'Toggle sidebar' })).toBeNull(); expect(document.querySelector('[data-sidebar-scope]')?.getAttribute('data-sidebar-mobile-present')).toBe('true'); diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/use-reveal-gesture.ts b/packages/playground-ui/src/ds/components/Sidebar/root/use-reveal-gesture.ts index 3bb8ca2763c..c8be67f1232 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/use-reveal-gesture.ts +++ b/packages/playground-ui/src/ds/components/Sidebar/root/use-reveal-gesture.ts @@ -102,8 +102,7 @@ export function useRevealGesture({ scopeRef, name, side, open, onGrab, onRelease const dy = touch.clientY - current.startY; if (Math.hypot(dx, dy) < LOCK_DISTANCE_PX) return 'pending'; - const owner = scope.getAttribute(OWNER_ATTR); - if (owner && owner !== name) return 'ignored'; + if (revealOwnedByOther(scope, name)) return 'ignored'; const layers = revealLayers(scope, layerAttr); const width = layerNamed(layers, layerAttr, 'panel')?.offsetWidth ?? 0; const opening = !isOpen(); @@ -206,6 +205,12 @@ function layerNamed(layers: readonly HTMLElement[], layerAttr: string, name: 'pa return layers.find(layer => layer.getAttribute(layerAttr) === name); } +/** Whether another edge drawer is out, so this one must stay shut. */ +export function revealOwnedByOther(scope: HTMLElement | null, name: string) { + const owner = scope?.getAttribute(OWNER_ATTR); + return Boolean(owner && owner !== name); +} + function releaseOwner(scope: Element, name: string) { if (scope.getAttribute(OWNER_ATTR) === name) scope.removeAttribute(OWNER_ATTR); } diff --git a/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.css b/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.css index a1e1519e017..9fe384a52de 100644 --- a/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.css +++ b/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.css @@ -6,6 +6,6 @@ html:has([data-slot='app-shell']) { overscroll-behavior-y: none; } -[data-sidebar-reveal][data-sidebar-mobile-present='true'] [data-slot='app-shell'] { +[data-sidebar-scope]:has([data-reveal-drawer='sidebar'][data-present='true']) [data-slot='app-shell'] { overflow-x: clip; } diff --git a/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.stories.tsx b/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.stories.tsx index 90507cb5685..ee39e586f41 100644 --- a/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.stories.tsx +++ b/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.stories.tsx @@ -1,4 +1,5 @@ import type { Meta, StoryObj } from '@storybook/react-vite'; +import { useRef, useState } from 'react'; import type { ReactNode } from 'react'; import { PageHeader } from '../page-header'; @@ -7,11 +8,12 @@ import { MainCard } from './main-card'; import { Breadcrumb, Crumb } from '@/ds/components/Breadcrumb'; import { LogoWithoutText } from '@/ds/components/Logo'; import { PageLayout } from '@/ds/components/PageLayout'; -import { Sidebar, SidebarProvider } from '@/ds/components/Sidebar'; +import { AsideReveal, Sidebar, SidebarProvider } from '@/ds/components/Sidebar'; import { TooltipProvider } from '@/ds/components/Tooltip'; import { IconMagnifyingGlass } from '@/ds/icons/central/IconMagnifyingGlass'; import { IconRobot } from '@/ds/icons/central/IconRobot'; import { IconSettingsGear5 } from '@/ds/icons/central/IconSettingsGear5'; +import { IconSidebarSimpleRightWide } from '@/ds/icons/central/IconSidebarSimpleRightWide'; import { WorkflowIcon } from '@/ds/icons/WorkflowIcon'; import { raisedSurfaceStyle } from '@/ds/primitives/raised-surface'; import { cn } from '@/lib/utils'; @@ -172,6 +174,62 @@ export const Mobile: Story = { ), }; +function MobileWithAsideDemo() { + const [open, setOpen] = useState(false); + const triggerRef = useRef(null); + return ( + + +
+ } + mobileHeader={ +
+ + + Workspace + + +
+ } + > + + + +
+ +

Details panel

+

+ Swiped in from the right edge, mirroring the navigation drawer on the left. +

+
+
+
+
+ ); +} + +export const MobileWithAside: Story = { + parameters: { + viewport: { defaultViewport: 'mobile1' }, + docs: { + description: { + story: + '`AsideReveal` is the right-edge counterpart of the navigation drawer. Swipe the page left or tap the panel button to slide the page left and uncover the panel; swipe right, tap the tinted strip, or press Escape to close. Only one drawer is out at a time.', + }, + }, + }, + render: () => , +}; + export const WithoutRouteHeader: Story = { render: () => ( From b07d8695a67235fb70632f20363dd8389a1957c2 Mon Sep 17 00:00:00 2001 From: "mastra-platform[bot]" Date: Tue, 17 Nov 2026 07:20:12 +0000 Subject: [PATCH 3/5] fix(playground-ui): send navigation back when the aside opens from outside AsideReveal is controlled, so a route or command can set `open` while the navigation drawer is out. Both drawers then stayed open, and the aside's inert marks skipped what navigation had already made inert, leaving the page reachable once navigation let go. The aside now closes navigation and only comes out once it has, keeping one drawer out at a time. Co-Authored-By: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> --- .../Sidebar/root/aside-reveal.test.tsx | 18 ++++++++++++- .../components/Sidebar/root/aside-reveal.tsx | 25 ++++++++++++------- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx index 8fd49334e2e..e2f0455d003 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx +++ b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { useState } from 'react'; +import { act, useState } from 'react'; import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import { AsideReveal, Sidebar, SidebarProvider } from '..'; import { AppShell } from '@/ds/new/layout/app-shell'; @@ -23,8 +23,12 @@ beforeAll(() => { afterEach(() => cleanup()); +// Opens the panel from outside, the way a route or a command would, bypassing the page that navigation makes inert. +let openPanel: () => void = () => {}; + function SessionPage() { const [open, setOpen] = useState(false); + openPanel = () => setOpen(true); return ( <>

Session transcript

@@ -184,6 +188,18 @@ describe('AsideReveal', () => { expect(navigation()).toBeNull(); expect(sessionPanel()).toBeNull(); }); + + it('closes navigation when the panel is opened from outside, so only the panel is out', async () => { + renderApp(); + await userEvent.click(screen.getByRole('button', { name: 'Open navigation menu' })); + expect(navigation()).not.toBeNull(); + + act(() => openPanel()); + + expect(navigation()).toBeNull(); + expect(sessionPanel()).not.toBeNull(); + expect(transcript().closest('[inert]')).not.toBeNull(); + }); }); describe('after the panel settles closed', () => { diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx index 6834d50cf06..0a35a7ccb33 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx +++ b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx @@ -1,8 +1,8 @@ -import { useState } from 'react'; +import { useEffect, useState } from 'react'; import type { ReactNode, RefObject } from 'react'; import { createPortal, flushSync } from 'react-dom'; import { RevealDrawer } from './reveal-drawer'; -import { useMaybeSidebarState } from './sidebar-context'; +import { useMaybeSidebar } from './sidebar-context'; import { useRevealGesture } from './use-reveal-gesture'; import { cn } from '@/lib/utils'; @@ -27,12 +27,19 @@ export type AsideRevealProps = { * Render it inside `SidebarProvider` and `AppShell`; it portals beside the shell, not inside the page that moves. */ export function AsideReveal({ open, onOpenChange, label, triggerRef, children, className }: AsideRevealProps) { - const sidebar = useMaybeSidebarState(); + const sidebar = useMaybeSidebar(); if (!sidebar) throw new Error('AsideReveal must be used within a SidebarProvider.'); - const { scopeRef, scope } = sidebar; - // Held out past `open` while a drag or the closing slide is still on screen. + const { scopeRef, scope, openMobile, setOpenMobile } = sidebar; + // Waits for navigation to go first, so the two drawers never overlap and its inert marks are gone. + const out = open && !openMobile; + // Held out past `out` while a drag or the closing slide is still on screen. const [held, setHeld] = useState(false); - const present = open || held; + const present = out || held; + + // An `open` set from outside while navigation is out sends navigation back; `out` follows once it has. + useEffect(() => { + if (open) setOpenMobile(false); + }, [open, setOpenMobile]); const close = () => { setHeld(true); @@ -43,11 +50,11 @@ export function AsideReveal({ open, onOpenChange, label, triggerRef, children, c scopeRef, name: 'aside', side: 'right', - open, + open: out, onGrab: () => flushSync(() => setHeld(true)), onRelease: onOpenChange, onSettled: () => { - if (!open) setHeld(false); + if (!out) setHeld(false); }, }); @@ -56,7 +63,7 @@ export function AsideReveal({ open, onOpenChange, label, triggerRef, children, c return createPortal( Date: Tue, 17 Nov 2026 07:43:08 +0000 Subject: [PATCH 4/5] refactor(playground-ui): keep one drawer owner in the provider and mount both drawers in the scope Which edge drawer holds the shared scope was tracked three ways: a data-reveal-owner attribute on the scope, React state, and an effect in AsideReveal that closed navigation whenever the panel opened. The owner now lives in one ref on SidebarProvider that both gestures and the sidebar's open guard read, and the effect is gone: a panel opened while navigation is out waits for navigation to close, the same way a swipe is ignored while the other drawer holds the edge. The navigation drawer now portals into the scope like the panel does, so every scope :has() check is a direct-child match instead of a search of the whole app subtree on each DOM change. Co-Authored-By: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> --- .../Sidebar/root/aside-reveal.test.tsx | 7 ++- .../components/Sidebar/root/aside-reveal.tsx | 15 +++--- .../components/Sidebar/root/reveal-drawer.tsx | 3 +- .../Sidebar/root/sidebar-context.ts | 3 ++ .../Sidebar/root/sidebar-provider.tsx | 7 ++- .../Sidebar/root/sidebar-reveal.css | 14 +++--- .../Sidebar/root/sidebar-reveal.tsx | 23 +++++++-- .../Sidebar/root/use-reveal-gesture.ts | 49 +++++++++++-------- .../src/ds/new/layout/app-shell/app-shell.css | 2 +- 9 files changed, 76 insertions(+), 47 deletions(-) diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx index e2f0455d003..b95d758255c 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx +++ b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx @@ -189,13 +189,18 @@ describe('AsideReveal', () => { expect(sessionPanel()).toBeNull(); }); - it('closes navigation when the panel is opened from outside, so only the panel is out', async () => { + it('holds a panel opened from outside until navigation closes, so only one drawer is out', async () => { renderApp(); await userEvent.click(screen.getByRole('button', { name: 'Open navigation menu' })); expect(navigation()).not.toBeNull(); act(() => openPanel()); + expect(navigation()).not.toBeNull(); + expect(sessionPanel()).toBeNull(); + + await userEvent.keyboard('{Escape}'); + expect(navigation()).toBeNull(); expect(sessionPanel()).not.toBeNull(); expect(transcript().closest('[inert]')).not.toBeNull(); diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx index 0a35a7ccb33..633d1148e6e 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx +++ b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useState } from 'react'; import type { ReactNode, RefObject } from 'react'; import { createPortal, flushSync } from 'react-dom'; import { RevealDrawer } from './reveal-drawer'; @@ -23,24 +23,20 @@ export type AsideRevealProps = { /** * The right-edge counterpart of the sidebar's mobile drawer: a leftward swipe anywhere in the shell * (or `open`) slides the page left to uncover the panel, and a rightward swipe, Escape, or a tap on the - * page puts it back. Shares the sidebar's gesture and scope, so only one of the two drawers is out at a time. + * page puts it back. Shares the sidebar's gesture and scope, so only one of the two drawers is out at a time: + * an `open` set while navigation is out waits for navigation to close. * Render it inside `SidebarProvider` and `AppShell`; it portals beside the shell, not inside the page that moves. */ export function AsideReveal({ open, onOpenChange, label, triggerRef, children, className }: AsideRevealProps) { const sidebar = useMaybeSidebar(); if (!sidebar) throw new Error('AsideReveal must be used within a SidebarProvider.'); - const { scopeRef, scope, openMobile, setOpenMobile } = sidebar; - // Waits for navigation to go first, so the two drawers never overlap and its inert marks are gone. + const { scopeRef, scope, drawerOwnerRef, openMobile } = sidebar; + // Navigation keeps the edge while it is out; the panel follows once it closes. const out = open && !openMobile; // Held out past `out` while a drag or the closing slide is still on screen. const [held, setHeld] = useState(false); const present = out || held; - // An `open` set from outside while navigation is out sends navigation back; `out` follows once it has. - useEffect(() => { - if (open) setOpenMobile(false); - }, [open, setOpenMobile]); - const close = () => { setHeld(true); onOpenChange(false); @@ -48,6 +44,7 @@ export function AsideReveal({ open, onOpenChange, label, triggerRef, children, c useRevealGesture({ scopeRef, + ownerRef: drawerOwnerRef, name: 'aside', side: 'right', open: out, diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/reveal-drawer.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/reveal-drawer.tsx index 35c92476875..409a9ef877f 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/reveal-drawer.tsx +++ b/packages/playground-ui/src/ds/components/Sidebar/root/reveal-drawer.tsx @@ -1,5 +1,6 @@ import { useEffect, useEffectEvent, useRef } from 'react'; import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent, ReactNode, RefObject } from 'react'; +import type { RevealName } from './use-reveal-gesture'; import { focusRingInset } from '@/ds/primitives/transitions'; import { cn } from '@/lib/utils'; @@ -7,7 +8,7 @@ const TABBABLE = 'a[href], button, input, select, textarea, summary, [tabindex]' type RevealDrawerProps = { /** Namespaces the layer attributes the reveal gesture and stylesheet drive: `data--reveal-layer`. */ - name: 'sidebar' | 'aside'; + name: RevealName; open: boolean; /** Out at all: open, dragged, or settling closed. Hidden when false. */ present: boolean; diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-context.ts b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-context.ts index 1d3f86f93b1..87513929faf 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-context.ts +++ b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-context.ts @@ -1,4 +1,5 @@ import React from 'react'; +import type { RevealName } from './use-reveal-gesture'; import type { LinkComponent } from '@/ds/types/link-component'; export type SidebarState = 'default' | 'collapsed'; @@ -26,6 +27,8 @@ type SidebarContextValue = { scopeRef: React.RefObject; /** The scope element once mounted, for drawers that portal into it. */ scope: HTMLDivElement | null; + /** The edge drawer that holds the scope, so the other one stays shut. */ + drawerOwnerRef: React.RefObject; panelRef: React.RefObject; LinkComponent?: LinkComponent; }; diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-provider.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-provider.tsx index a0c38235bd8..5472f6ee50b 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-provider.tsx +++ b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-provider.tsx @@ -3,7 +3,8 @@ import type { CSSProperties } from 'react'; import { SidebarContext, MobileDrawerContext } from './sidebar-context'; import type { MobileDrawerContextValue, SidebarState } from './sidebar-context'; import { SIDEBAR_WIDTHS } from './sidebar-widths'; -import { REVEAL_EASE, revealOwnedByOther } from './use-reveal-gesture'; +import { REVEAL_EASE } from './use-reveal-gesture'; +import type { RevealName } from './use-reveal-gesture'; import type { LinkComponent } from '@/ds/types/link-component'; const SIDEBAR_STATE_KEY = 'sidebar:state'; @@ -116,6 +117,7 @@ export function SidebarProvider({ setScope(node); }); const panelRef = React.useRef(null); + const drawerOwnerRef = React.useRef(null); React.useEffect(() => { if (typeof window === 'undefined') return; @@ -128,7 +130,7 @@ export function SidebarProvider({ const setOpenMobile = React.useCallback((open: boolean) => { // One drawer at a time: a shortcut must not open navigation over an open aside. - if (open && revealOwnedByOther(scopeRef.current, 'sidebar')) return; + if (open && drawerOwnerRef.current === 'aside') return; openMobileRef.current = open; if (open) setMobileDrawerPresent(true); setOpenMobileState(open); @@ -251,6 +253,7 @@ export function SidebarProvider({ setGestureActive, scopeRef, scope, + drawerOwnerRef, panelRef, LinkComponent, }), diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-reveal.css b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-reveal.css index 91b46ce1456..43a54e14ffa 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-reveal.css +++ b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-reveal.css @@ -20,25 +20,25 @@ inherits: false; } -[data-sidebar-scope]:has([data-reveal-drawer='sidebar']) { +[data-sidebar-scope]:has(> [data-reveal-drawer='sidebar']) { --sidebar-reveal-width: calc(100vw - 3.5rem); --sidebar-reveal-radius: var(--studio-frame-radius, 1.5rem) 0 0 var(--studio-frame-radius, 1.5rem); --sidebar-reveal-rest: 0; --sidebar-reveal-settle: 320ms; } -[data-sidebar-scope]:has([data-reveal-drawer='sidebar'][data-open='true']) { +[data-sidebar-scope]:has(> [data-reveal-drawer='sidebar'][data-open='true']) { --sidebar-reveal-rest: 1; --sidebar-reveal-settle: 400ms; } -[data-sidebar-scope]:has([data-reveal-drawer='sidebar']) [data-sidebar-reveal-layer] { +[data-sidebar-scope]:has(> [data-reveal-drawer='sidebar']) [data-sidebar-reveal-layer] { --sidebar-reveal-progress: var(--sidebar-reveal-drag, var(--sidebar-reveal-rest)); --sidebar-reveal-motion: var(--sidebar-reveal-duration, var(--sidebar-reveal-settle)) var(--reveal-ease); } @media (prefers-reduced-motion: reduce) { - [data-sidebar-scope]:has([data-reveal-drawer='sidebar']) [data-sidebar-reveal-layer] { + [data-sidebar-scope]:has(> [data-reveal-drawer='sidebar']) [data-sidebar-reveal-layer] { --sidebar-reveal-motion: 0ms; } } @@ -60,15 +60,15 @@ opacity var(--sidebar-reveal-motion); } -[data-sidebar-scope]:has([data-reveal-drawer='sidebar'][data-present='true']) [data-sidebar-reveal-layer='panel'] { +[data-reveal-drawer='sidebar'][data-present='true'] [data-sidebar-reveal-layer='panel'] { will-change: scale, opacity; } -[data-sidebar-scope]:has([data-reveal-drawer='sidebar'][data-present='true']) [data-sidebar-reveal-layer='scrim'] { +[data-reveal-drawer='sidebar'][data-present='true'] [data-sidebar-reveal-layer='scrim'] { will-change: translate, opacity; } -[data-sidebar-scope]:has([data-reveal-drawer='sidebar'][data-present='true']) [data-sidebar-reveal-layer='page'] { +[data-sidebar-scope]:has(> [data-reveal-drawer='sidebar'][data-present='true']) [data-sidebar-reveal-layer='page'] { position: relative; z-index: 1; overflow: clip; diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-reveal.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-reveal.tsx index 56e24e111e7..488704eac95 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-reveal.tsx +++ b/packages/playground-ui/src/ds/components/Sidebar/root/sidebar-reveal.tsx @@ -1,5 +1,5 @@ import type { MouseEvent, ReactNode } from 'react'; -import { flushSync } from 'react-dom'; +import { createPortal, flushSync } from 'react-dom'; import { RevealDrawer } from './reveal-drawer'; import { useSidebar } from './sidebar-context'; import { useRevealGesture } from './use-reveal-gesture'; @@ -14,11 +14,20 @@ type SidebarRevealProps = { }; export function SidebarReveal({ children, className, onClick }: SidebarRevealProps) { - const { scopeRef, openMobile, mobileDrawerPresent, mobileTriggerRef, setOpenMobile, setMobileDrawerPresent } = - useSidebar(); + const { + scopeRef, + scope, + drawerOwnerRef, + openMobile, + mobileDrawerPresent, + mobileTriggerRef, + setOpenMobile, + setMobileDrawerPresent, + } = useSidebar(); useRevealGesture({ scopeRef, + ownerRef: drawerOwnerRef, name: 'sidebar', side: 'left', open: openMobile, @@ -29,7 +38,10 @@ export function SidebarReveal({ children, className, onClick }: SidebarRevealPro }, }); - return ( + if (!scope) return null; + + // A direct child of the scope, like the aside, so the stylesheets' `:has(> …)` checks stay one level deep. + return createPortal(
{children}
-
+
, + scope, ); } diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/use-reveal-gesture.ts b/packages/playground-ui/src/ds/components/Sidebar/root/use-reveal-gesture.ts index c8be67f1232..302bd07c307 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/use-reveal-gesture.ts +++ b/packages/playground-ui/src/ds/components/Sidebar/root/use-reveal-gesture.ts @@ -5,9 +5,6 @@ const EASE = [0.32, 0.72, 0, 1] as const; const EASE_START_SLOPE = EASE[1] / EASE[0]; export const REVEAL_EASE = `cubic-bezier(${EASE.join(', ')})`; -/** Marks which reveal holds the shared scope, so a drawer's swipes can't start the drawer on the other edge. */ -const OWNER_ATTR = 'data-reveal-owner'; - const LOCK_DISTANCE_PX = 8; const TURN_DISTANCE_PX = 8; const COMMIT_DISTANCE_PX = 40; @@ -35,10 +32,18 @@ type Track = { export type RevealSide = 'left' | 'right'; +/** The two edge drawers that share a scope. */ +export type RevealName = 'sidebar' | 'aside'; + type RevealGestureOptions = { scopeRef: RefObject; + /** + * The drawer holding the scope while open, dragged, or settling closed. Shared by both drawers so only one is ever + * out: a swipe that would start one is ignored while the other holds it. + */ + ownerRef: RefObject; /** Namespaces the layer attribute (`data--reveal-layer`) and the drag variables (`---reveal-*`). */ - name: string; + name: RevealName; /** The screen edge the panel sits on. A left panel opens on a rightward swipe, a right panel on a leftward one. */ side: RevealSide; open: boolean; @@ -47,7 +52,16 @@ type RevealGestureOptions = { onSettled: () => void; }; -export function useRevealGesture({ scopeRef, name, side, open, onGrab, onRelease, onSettled }: RevealGestureOptions) { +export function useRevealGesture({ + scopeRef, + ownerRef, + name, + side, + open, + onGrab, + onRelease, + onSettled, +}: RevealGestureOptions) { const settleRef = useRef(0); const layerAttr = `data-${name}-reveal-layer`; const dragVar = `--${name}-reveal-drag`; @@ -68,17 +82,16 @@ export function useRevealGesture({ scopeRef, name, side, open, onGrab, onRelease void Promise.allSettled(running.map(animation => animation.finished)).then(() => { if (token !== settleRef.current) return; clearRevealVar(revealLayers(scope, layerAttr), durationVar); - if (!isOpen()) releaseOwner(scope, name); + if (!isOpen()) releaseOwner(ownerRef, name); handleSettled(); }); }); }); useEffect(() => { - const scope = scopeRef.current; - if (open && scope) scope.setAttribute(OWNER_ATTR, name); + if (open) ownerRef.current = name; settle(); - }, [open, scopeRef, name]); + }, [open, ownerRef, name]); useEffect(() => { const scope = scopeRef.current; @@ -102,7 +115,7 @@ export function useRevealGesture({ scopeRef, name, side, open, onGrab, onRelease const dy = touch.clientY - current.startY; if (Math.hypot(dx, dy) < LOCK_DISTANCE_PX) return 'pending'; - if (revealOwnedByOther(scope, name)) return 'ignored'; + if (ownerRef.current && ownerRef.current !== name) return 'ignored'; const layers = revealLayers(scope, layerAttr); const width = layerNamed(layers, layerAttr, 'panel')?.offsetWidth ?? 0; const opening = !isOpen(); @@ -120,7 +133,7 @@ export function useRevealGesture({ scopeRef, name, side, open, onGrab, onRelease current.layers = layers; setRevealVar(layers, durationVar, '0ms'); settleRef.current++; - scope.setAttribute(OWNER_ATTR, name); + ownerRef.current = name; handleGrab(); return 'locked'; }; @@ -192,9 +205,9 @@ export function useRevealGesture({ scopeRef, name, side, open, onGrab, onRelease const layers = revealLayers(scope, layerAttr); clearRevealVar(layers, dragVar); clearRevealVar(layers, durationVar); - releaseOwner(scope, name); + releaseOwner(ownerRef, name); }; - }, [scopeRef, layerAttr, dragVar, durationVar, name, toward]); + }, [scopeRef, ownerRef, layerAttr, dragVar, durationVar, name, toward]); } function revealLayers(scope: ParentNode, layerAttr: string) { @@ -205,14 +218,8 @@ function layerNamed(layers: readonly HTMLElement[], layerAttr: string, name: 'pa return layers.find(layer => layer.getAttribute(layerAttr) === name); } -/** Whether another edge drawer is out, so this one must stay shut. */ -export function revealOwnedByOther(scope: HTMLElement | null, name: string) { - const owner = scope?.getAttribute(OWNER_ATTR); - return Boolean(owner && owner !== name); -} - -function releaseOwner(scope: Element, name: string) { - if (scope.getAttribute(OWNER_ATTR) === name) scope.removeAttribute(OWNER_ATTR); +function releaseOwner(ownerRef: RefObject, name: RevealName) { + if (ownerRef.current === name) ownerRef.current = null; } function setRevealVar(layers: readonly HTMLElement[], name: string, value: string) { diff --git a/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.css b/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.css index 9fe384a52de..fd906254dba 100644 --- a/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.css +++ b/packages/playground-ui/src/ds/new/layout/app-shell/app-shell.css @@ -6,6 +6,6 @@ html:has([data-slot='app-shell']) { overscroll-behavior-y: none; } -[data-sidebar-scope]:has([data-reveal-drawer='sidebar'][data-present='true']) [data-slot='app-shell'] { +[data-sidebar-scope]:has(> [data-reveal-drawer='sidebar'][data-present='true']) [data-slot='app-shell'] { overflow-x: clip; } From a4ba43815476d0e9f74b4341bc31bccea392ff53 Mon Sep 17 00:00:00 2001 From: "mastra-platform[bot]" Date: Tue, 17 Nov 2026 08:02:06 +0000 Subject: [PATCH 5/5] fix(playground-ui): keep the side panel's slides whole when another source opens or closes it A panel opened while navigation was still sliding closed could take the edge before navigation had left the screen, so both drawers showed for a moment. The panel now waits until navigation is fully gone, not just marked closed. A panel closed by its parent, rather than by a swipe, Escape or the scrim, vanished at once instead of sliding out. The panel now stays mounted after any open settles, so every close plays its slide before unmounting. Co-Authored-By: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> --- .../Sidebar/root/aside-reveal.test.tsx | 63 +++++++++++++++++-- .../components/Sidebar/root/aside-reveal.tsx | 13 ++-- 2 files changed, 65 insertions(+), 11 deletions(-) diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx index b95d758255c..30c27498ed6 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx +++ b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.test.tsx @@ -21,14 +21,20 @@ beforeAll(() => { }); }); -afterEach(() => cleanup()); +let heldSlides: { mockRestore(): void } | undefined; + +afterEach(() => { + heldSlides?.mockRestore(); + cleanup(); +}); // Opens the panel from outside, the way a route or a command would, bypassing the page that navigation makes inert. -let openPanel: () => void = () => {}; +let setPanel: (open: boolean) => void = () => {}; +const openPanel = () => setPanel(true); function SessionPage() { const [open, setOpen] = useState(false); - openPanel = () => setOpen(true); + setPanel = setOpen; return ( <>

Session transcript

@@ -88,6 +94,20 @@ function drag(target: Element, from: number, to: number) { touch('touchend', target, to, 420); } +/** Keeps every slide running until the returned function finishes them. */ +function holdSlides() { + let finish!: () => void; + const finished = new Promise(resolve => (finish = resolve)); + heldSlides = vi.spyOn(Element.prototype, 'getAnimations').mockReturnValue([{ finished } as unknown as Animation]); + return async () => { + heldSlides?.mockRestore(); + await act(async () => finish()); + }; +} + +/** Lets the slides that are running now settle. */ +const settleSlides = () => act(() => new Promise(resolve => requestAnimationFrame(() => setTimeout(resolve)))); + const sessionPanel = () => screen.queryByRole('dialog', { name: 'Session panel' }); const navigation = () => screen.queryByRole('dialog', { name: 'Navigation' }); const transcript = () => screen.getByText('Session transcript'); @@ -201,10 +221,45 @@ describe('AsideReveal', () => { await userEvent.keyboard('{Escape}'); + await waitFor(() => expect(sessionPanel()).not.toBeNull()); expect(navigation()).toBeNull(); - expect(sessionPanel()).not.toBeNull(); expect(transcript().closest('[inert]')).not.toBeNull(); }); + + it('holds a panel opened from outside until navigation has finished sliding closed', async () => { + renderApp(); + await userEvent.click(screen.getByRole('button', { name: 'Open navigation menu' })); + await settleSlides(); + const finishSlides = holdSlides(); + await userEvent.keyboard('{Escape}'); + + act(() => openPanel()); + + expect(sessionPanel()).toBeNull(); + expect(screen.queryByText('Changed files')).toBeNull(); + + await finishSlides(); + + await waitFor(() => expect(sessionPanel()).not.toBeNull()); + }); + }); + + describe('when the parent closes the open panel', () => { + it('keeps the panel mounted until its closing slide settles', async () => { + renderApp(); + await userEvent.click(screen.getByRole('button', { name: 'Show details' })); + await settleSlides(); + const finishSlides = holdSlides(); + + act(() => setPanel(false)); + + expect(sessionPanel()).toBeNull(); + expect(screen.getByText('Changed files')).toBeTruthy(); + + await finishSlides(); + + await waitFor(() => expect(screen.queryByText('Changed files')).toBeNull()); + }); }); describe('after the panel settles closed', () => { diff --git a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx index 633d1148e6e..46adb58f840 100644 --- a/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx +++ b/packages/playground-ui/src/ds/components/Sidebar/root/aside-reveal.tsx @@ -30,10 +30,11 @@ export type AsideRevealProps = { export function AsideReveal({ open, onOpenChange, label, triggerRef, children, className }: AsideRevealProps) { const sidebar = useMaybeSidebar(); if (!sidebar) throw new Error('AsideReveal must be used within a SidebarProvider.'); - const { scopeRef, scope, drawerOwnerRef, openMobile } = sidebar; - // Navigation keeps the edge while it is out; the panel follows once it closes. - const out = open && !openMobile; - // Held out past `out` while a drag or the closing slide is still on screen. + const { scopeRef, scope, drawerOwnerRef, mobileDrawerPresent } = sidebar; + // Navigation keeps the edge while it is on screen, closing slide included; the panel follows once it is gone. + const out = open && !mobileDrawerPresent; + // Held out past `out` while a drag or the closing slide is on screen. Set on grab, and once an open settles, + // so a close from any source (gesture, Escape, scrim, or the parent) slides out before unmounting. const [held, setHeld] = useState(false); const present = out || held; @@ -50,9 +51,7 @@ export function AsideReveal({ open, onOpenChange, label, triggerRef, children, c open: out, onGrab: () => flushSync(() => setHeld(true)), onRelease: onOpenChange, - onSettled: () => { - if (!out) setHeld(false); - }, + onSettled: () => setHeld(out), }); if (!scope) return null;