An open source design system that's fully customizable and agent ready
TypeScript
docs(useScrollLock): add a full-screen mobile menu example block (#9595)
Parman Mohammadalizadehb9e3dc27ec8f
diff --git a/.changeset/use-scroll-lock-mobile-menu-example.md b/.changeset/use-scroll-lock-mobile-menu-example.mdnew file mode 100644index 0000000000..07cf077d87--- /dev/null+++ b/.changeset/use-scroll-lock-mobile-menu-example.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[docs] A new `useScrollLock — Full-screen Mobile Menu` example block opens a custom full-screen menu from a Menu button and locks the page behind it with `useScrollLock`, so the page neither scrolls nor shifts sideways, and closing the menu returns the reader to the same scroll position. Copy it with `astryx template useScrollLockHookUsage <path>`.++@MannXodiff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.jsonindex 07f3870fd9..e1e8acb7b3 100644--- a/apps/sandbox/scripts/next-export-routes.json+++ b/apps/sandbox/scripts/next-export-routes.json@@ -811,6 +811,7 @@"/templates/useOverflowHookUsage/","/templates/useOverlayHookUsage/","/templates/usePressFeedbackHookUsage/",+ "/templates/useScrollLockHookUsage/","/templates/useScrollOverflowHookUsage/","/templates/useScrollableAreaHookUsage/","/templates/useStreamingTextHookUsage/",diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 726c8ecf6a..cc6a254eda 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -3811,6 +3811,11 @@"path": "examples/use-press-feedback/pressable-card","aliases": []},+ {+ "name": "example-use-scroll-lock-full-screen-mobile-menu",+ "path": "examples/use-scroll-lock/full-screen-mobile-menu",+ "aliases": []+ },{"name": "example-use-scroll-overflow-filter-strip-edge-fades","path": "examples/use-scroll-overflow/filter-strip-edge-fades",diff --git a/packages/cli/api/template/use-scroll-lock-hook-usage.test.tsx b/packages/cli/api/template/use-scroll-lock-hook-usage.test.tsxnew file mode 100644index 0000000000..af56f9a39e--- /dev/null+++ b/packages/cli/api/template/use-scroll-lock-hook-usage.test.tsx@@ -0,0 +1,169 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @vitest-environment jsdom++/**+ * The useScrollLock example locks the page while its full-screen menu is open,+ * without moving it, and frees it again when the menu closes. The menu is a+ * native <dialog> opened with showModal(), so it sits in the browser top layer+ * above any page header. It keeps keyboard focus inside itself (useFocusTrap):+ * focus moves in on open, Escape closes, and focus returns to the Menu button.+ */++import {act} from 'react';+import {createRoot, type Root} from 'react-dom/client';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import UseScrollLockHookUsage from '../../assets/templates/blocks/components/Hooks/useScrollLockHookUsage';++// The node project does not compile StyleX, and the menu's styles are not under test.+vi.mock('@stylexjs/stylex', () => ({+ create: <T,>(styles: T) => styles,+ props: () => ({}),+}));++(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =+ true;++let root: Root | null = null;+let container: HTMLElement;++function renderExample(): void {+ container = document.createElement('div');+ document.body.appendChild(container);+ act(() => {+ root = createRoot(container);+ root.render(<UseScrollLockHookUsage />);+ });+}++function button(label: string): HTMLButtonElement {+ const match = Array.from(container.querySelectorAll('button')).find(+ candidate => candidate.textContent === label,+ );+ if (match == null) {+ throw new Error(`no "${label}" button rendered`);+ }+ return match;+}++function menu(): HTMLDialogElement {+ const dialog = container.querySelector('dialog');+ if (dialog == null) {+ throw new Error('no menu dialog rendered');+ }+ return dialog;+}++// jsdom has no showModal() or close().+const showModal = vi.fn(function (this: HTMLDialogElement) {+ this.setAttribute('open', '');+});++beforeEach(() => {+ showModal.mockClear();+ HTMLDialogElement.prototype.showModal = showModal;+ HTMLDialogElement.prototype.close = function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ };+});++afterEach(() => {+ act(() => root?.unmount());+ root = null;+ container.remove();+ document.body.style.cssText = '';+ document.documentElement.style.cssText = '';+ vi.restoreAllMocks();+});++describe('useScrollLock example', () => {+ it('locks the page without moving it while the menu is open', () => {+ const scrollTo = vi.spyOn(window, 'scrollTo').mockImplementation(() => {});+ renderExample();+ expect(document.documentElement.style.overflow).toBe('');++ expect(menu().open).toBe(false);++ act(() => button('Menu').click());++ expect(menu().open).toBe(true);+ expect(showModal).toHaveBeenCalledTimes(1);+ expect(document.documentElement.style.overflow).toBe('hidden');+ expect(document.body.style.position).toBe('');+ expect(scrollTo).not.toHaveBeenCalled();+ });++ it('frees the page where the reader left it when the menu closes', () => {+ const scrollTo = vi.spyOn(window, 'scrollTo').mockImplementation(() => {});+ renderExample();+ act(() => button('Menu').click());++ act(() => button('Close menu').click());++ expect(menu().open).toBe(false);+ expect(document.documentElement.style.overflow).toBe('');+ expect(scrollTo).not.toHaveBeenCalled();+ });++ it('frees the page when a menu link is followed', () => {+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});+ renderExample();+ act(() => button('Menu').click());+ expect(document.documentElement.style.overflow).toBe('hidden');++ act(() => {+ menu().querySelector<HTMLAnchorElement>('a')?.click();+ });++ expect(menu().open).toBe(false);+ expect(document.documentElement.style.overflow).toBe('');+ });++ it('moves focus into the menu and returns it to Menu on Close menu', () => {+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});+ renderExample();+ const opener = button('Menu');+ act(() => {+ opener.focus();+ opener.click();+ });+ expect(menu().contains(document.activeElement)).toBe(true);++ act(() => button('Close menu').click());++ expect(menu().open).toBe(false);+ expect(document.activeElement).toBe(opener);+ });++ it('closes on Escape and returns focus to Menu', () => {+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});+ renderExample();+ const opener = button('Menu');+ act(() => {+ opener.focus();+ opener.click();+ });++ act(() => {+ document.activeElement?.dispatchEvent(+ new KeyboardEvent('keydown', {key: 'Escape', bubbles: true}),+ );+ });++ expect(menu().open).toBe(false);+ expect(document.documentElement.style.overflow).toBe('');+ expect(document.activeElement).toBe(opener);+ });++ it('closes when the browser cancels the dialog', () => {+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});+ renderExample();+ act(() => button('Menu').click());++ act(() => {+ menu().dispatchEvent(new Event('cancel', {cancelable: true}));+ });++ expect(menu().open).toBe(false);+ expect(document.documentElement.style.overflow).toBe('');+ });+});diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useScrollLockHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Hooks/useScrollLockHookUsage.doc.mjsnew file mode 100644index 0000000000..d620dca76c--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Hooks/useScrollLockHookUsage.doc.mjs@@ -0,0 +1,14 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'useScrollLock',+ name: 'useScrollLock — Full-screen Mobile Menu',+ displayName: 'useScrollLock — Full-screen Mobile Menu',+ description:+ 'A custom full-screen menu opened from a Menu button. useScrollLock pins the page behind it while it is open, so the page does not scroll or shift sideways, and closing the menu returns the reader to the same scroll position.',+ isReady: true,+ aspectRatio: 4 / 3,+ componentsUsed: ['Button', 'Link', 'Layout'],+};diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useScrollLockHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Hooks/useScrollLockHookUsage.tsxnew file mode 100644index 0000000000..4e49a5074b--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Hooks/useScrollLockHookUsage.tsx@@ -0,0 +1,80 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useEffect, useState} from 'react';+import * as stylex from '@stylexjs/stylex';+import {Button} from '@astryxdesign/core/Button';+import {useFocusTrap, useScrollLock} from '@astryxdesign/core/hooks';+import {VStack} from '@astryxdesign/core/Layout';+import {Link} from '@astryxdesign/core/Link';+import {colorVars, spacingVars} from '@astryxdesign/core/theme/tokens.stylex';++const styles = stylex.create({+ menu: {+ width: '100%',+ height: '100%',+ maxWidth: 'none',+ maxHeight: 'none',+ margin: 0,+ borderWidth: 0,+ overflowY: 'auto',+ padding: spacingVars['--spacing-4'],+ color: colorVars['--color-text-primary'],+ backgroundColor: colorVars['--color-background-surface'],+ },+});++const MENU_ITEMS = ['Products', 'Pricing', 'Customers', 'Support'];++export default function UseScrollLockHookUsage() {+ const [isOpen, setIsOpen] = useState(false);+ useScrollLock(isOpen);+ const {containerRef, focusFirst} = useFocusTrap<HTMLDialogElement>({+ isActive: isOpen,+ onEscape: close,+ });++ // The dialog leaves the top layer before the state change, so the page is+ // no longer inert when the focus trap hands focus back to Menu.+ function close() {+ containerRef.current?.close();+ setIsOpen(false);+ }++ useEffect(() => {+ const dialog = containerRef.current;+ if (isOpen && dialog != null && !dialog.open) {+ dialog.showModal();+ focusFirst();+ }+ }, [isOpen, containerRef, focusFirst]);++ return (+ <>+ <Button label="Menu" onClick={() => setIsOpen(true)} />+ <dialog+ ref={containerRef}+ aria-label="Menu"+ onCancel={event => {+ event.preventDefault();+ close();+ }}+ {...stylex.props(styles.menu)}>+ <nav aria-label="Site menu">+ <VStack gap={4} hAlign="start">+ <Button label="Close menu" variant="secondary" onClick={close} />+ {MENU_ITEMS.map(item => (+ <Link+ key={item}+ href={`#menu-${item.toLowerCase()}`}+ onClick={close}>+ {item}+ </Link>+ ))}+ </VStack>+ </nav>+ </dialog>+ </>+ );+}