An open source design system that's fully customizable and agent ready
TypeScript
feat(Outline): keyboard navigation, navigate callbacks, and scroll-scoping props (#2527) (#3845)
AKcbfb48e58aaa
diff --git a/.changeset/outline-keyboard-navigate-scoping.md b/.changeset/outline-keyboard-navigate-scoping.mdnew file mode 100644index 0000000000..68d406e784--- /dev/null+++ b/.changeset/outline-keyboard-navigate-scoping.md@@ -0,0 +1,18 @@+---+'@astryxdesign/core': patch+---++[feat] Outline: keyboard navigation, navigate callbacks, and scroll-scoping props (#2527)++Layers the public API deferred out of #2746 onto the scroll-spy engine and click-lock that already shipped. No visual change.++- **Keyboard navigation** — the outline is now a single tab stop (roving tabindex via `useListFocus`), seated on the _active_ heading per WAI-ARIA, so tabbing into a table of contents while reading section 7 lands on section 7 rather than sending the reader back to section 1. Arrow keys move between headings, Home/End jump to the ends, and Enter/Space activate. A 40-heading table of contents costs one Tab press instead of 40, and Tab still leaves the outline in one press.+- **`onNavigateStart(id)` / `onNavigateEnd(id)`** — fire around the smooth scroll started by a click or keyboard activation, so an app can drive an arrival effect. `onNavigateEnd` resolves on `scrollend` where supported and on a settle timeout where it is not (Safari), so it also fires correctly when reduced motion collapses the scroll into an instant jump. It fires exactly once for every `onNavigateStart` — including when the user interrupts the scroll — so a "navigating" state can never leak.+- **`offset`** — the height of a fixed header overlaying the top of the scroll root. It shifts both the activation line **and** the scroll landing by the same amount, so a heading activates exactly where navigating to it puts it: below the header, not hidden underneath it. It composes with each heading's own `scroll-margin-top` (the header, then the breathing room below it) rather than replacing it — leave `offset` at 0 when nothing overlays the content and let `scroll-margin-top` do the work, since the browser already honors it.+- **`scrollContainerRef`** — scope scroll tracking to a specific container instead of auto-detecting the nearest scrollable ancestor. Fixes the table of contents whose highlight never moves inside a split pane, modal, or dashboard panel. The default (viewport) path is unchanged.+- **`hasScrollOnClick`** (default `true`) — set to `false` to own the scrolling yourself; the outline still updates the active item, the hash, and the navigate callbacks.++Clicking an outline item whose heading is not in the DOM (lazily-rendered or virtualized content) still falls through to the browser's native fragment navigation, as before — the link is never swallowed into a no-op.++Existing props (`items`, `activeId`, `onActiveIdChange`, `label`, `density`) and the `parseOutlineFromMarkdown` / `useOutlineFromMarkdown` / `useOutlineFromDOM` helpers are unchanged.+@AKnassadiff --git a/apps/storybook/stories/Outline.stories.tsx b/apps/storybook/stories/Outline.stories.tsxindex e45ff17c69..30a7cb2d52 100644--- a/apps/storybook/stories/Outline.stories.tsx+++ b/apps/storybook/stories/Outline.stories.tsx@@ -1,6 +1,6 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {useRef, type ReactNode} from 'react';+import {useRef, useState, type ReactNode} from 'react';import type {Meta, StoryObj} from '@storybook/react';import {Outline,@@ -45,6 +45,9 @@ const outlineItems: OutlineItem[] = [{id: 'accessibility', label: 'Accessibility', level: 2},];+/** Height of the ScrollSpy story's sticky header — fed straight to `offset`. */+const STICKY_HEADER_HEIGHT = 48;+const markdownContent = ['## Overview','',@@ -130,8 +133,8 @@ export const WithDocument: Story = {<section><h2 id="installation">Installation</h2><p>- Install the package, wrap the app with Theme, and import- components from their subpaths.+ Install the package, wrap the app with Theme, and import components+ from their subpaths.</p></section><section>@@ -147,8 +150,9 @@ export const WithDocument: Story = {</p><h3 id="component-overrides">Component overrides</h3><p>- Component overrides target the stable Astryx selector surface emitted- by each component: astryx-* classes plus data-* prop reflections.+ Component overrides target the stable Astryx selector surface+ emitted by each component: astryx-* classes plus data-* prop+ reflections.</p></section><section>@@ -182,12 +186,7 @@ export const ExtractFromMarkdown: Story = {components={{heading: ({level, children}) => {const Tag = `h${level}` as- | 'h1'- | 'h2'- | 'h3'- | 'h4'- | 'h5'- | 'h6';+ 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';return <Tag id={storySlug(nodeText(children))}>{children}</Tag>;},}}>@@ -284,3 +283,163 @@ export const DeepNesting: Story = {);},};++/**+ * Scroll-spy scoped to a custom scroll container, under a sticky header.+ *+ * The content scrolls inside the pane, not the viewport — so the outline would+ * auto-detect the wrong scroll root and its highlight would never move.+ * `scrollContainerRef` scopes tracking to the pane.+ *+ * `offset` is the height of the sticky header covering the top of that pane.+ * It moves the activation line *and* the scroll landing together, so clicking+ * an item parks its heading just below the header instead of hidden underneath+ * it — and the heading activates at the same line it lands on. The heading's+ * own `scroll-margin-top` adds the breathing room below the header (8px here),+ * so the two compose: 48 + 8 = 56px.+ */+export const ScrollSpy: Story = {+ render: () => {+ const scrollContainerRef = useRef<HTMLDivElement | null>(null);++ return (+ <div+ style={{+ display: 'grid',+ gridTemplateColumns: 'minmax(0, 1fr) 220px',+ gap: 32,+ maxWidth: 960,+ }}>+ <div+ ref={scrollContainerRef}+ style={{+ overflowY: 'auto',+ height: 360,+ border: '1px solid rgba(128,128,128,0.3)',+ borderRadius: 8,+ position: 'relative',+ }}>+ <div+ style={{+ position: 'sticky',+ top: 0,+ height: STICKY_HEADER_HEIGHT,+ boxSizing: 'border-box',+ padding: '0 16px',+ display: 'flex',+ alignItems: 'center',+ background: 'var(--color-surface, #fff)',+ borderBottom: '1px solid rgba(128,128,128,0.3)',+ zIndex: 1,+ }}>+ <Badge label={`Sticky header (${STICKY_HEADER_HEIGHT}px)`} />+ </div>+ <div style={{padding: '0 16px 16px'}}>+ {outlineItems.map(item => (+ <section key={item.id}>+ {/* scroll-margin-top must sit on the element the outline+ targets — the heading carries the id, so the browser reads+ it from there, not from a wrapper. */}+ <Heading+ id={item.id}+ level={item.level === 2 ? 2 : 3}+ style={{scrollMarginTop: 8}}>+ {item.label}+ </Heading>+ <Text>+ Scroll the pane. The outline tracks the pane's scroll+ position, not the window's.+ </Text>+ <div style={{height: 160}} />+ </section>+ ))}+ </div>+ </div>+ <aside style={{alignSelf: 'start'}}>+ <Outline+ items={outlineItems}+ scrollContainerRef={scrollContainerRef}+ offset={STICKY_HEADER_HEIGHT}+ />+ </aside>+ </div>+ );+ },+};++/**+ * Navigate callbacks. `onNavigateStart` fires before the smooth scroll begins+ * and `onNavigateEnd` once it settles — here it flashes the heading on arrival.+ *+ * `onNavigateEnd` fires exactly once for every `onNavigateStart`, including+ * when the user scrolls away mid-jump, so the flash state can never get stuck.+ */+export const NavigateCallbacks: Story = {+ render: () => {+ const [status, setStatus] = useState('idle');+ const [flashId, setFlashId] = useState<string | null>(null);++ return (+ <div+ style={{+ display: 'grid',+ gridTemplateColumns: 'minmax(0, 1fr) 220px',+ gap: 32,+ maxWidth: 960,+ }}>+ <article>+ {outlineItems.map(item => (+ <section key={item.id}>+ {/* scroll-margin-top belongs on the heading (it carries the id+ the outline scrolls to), not on the section wrapper. */}+ <Heading+ id={item.id}+ level={item.level === 2 ? 2 : 3}+ style={{+ scrollMarginTop: 16,+ transition: 'background-color 600ms',+ backgroundColor:+ flashId === item.id+ ? 'var(--color-overlay-hover, rgba(128,128,128,0.2))'+ : 'transparent',+ }}>+ {item.label}+ </Heading>+ <div style={{height: 320}} />+ </section>+ ))}+ </article>+ <aside style={{position: 'sticky', top: 24, alignSelf: 'start'}}>+ <Badge label={status} />+ <Outline+ items={outlineItems}+ onNavigateStart={id => {+ setFlashId(null);+ setStatus(`scrolling to ${id}`);+ }}+ onNavigateEnd={id => {+ setFlashId(id);+ setStatus(`arrived at ${id}`);+ }}+ />+ </aside>+ </div>+ );+ },+};++/**+ * Keyboard navigation. The outline is a single tab stop: Tab moves into it+ * once, then Arrow keys move between headings, Home/End jump to the ends, and+ * Enter or Space activates — a 40-heading TOC costs one Tab press, not 40.+ */+export const KeyboardNavigation: Story = {+ render: () => (+ <div+ style={{display: 'flex', flexDirection: 'column', gap: 16, width: 240}}>+ <button type="button">Focus me, then press Tab</button>+ <Outline items={outlineItems} />+ <button type="button">Tab again lands here</button>+ </div>+ ),+};diff --git a/packages/core/src/Outline/Outline.doc.mjs b/packages/core/src/Outline/Outline.doc.mjsindex 5d0dc984c8..bd162dd5b4 100644--- a/packages/core/src/Outline/Outline.doc.mjs+++ b/packages/core/src/Outline/Outline.doc.mjs@@ -72,6 +72,38 @@ export const docs = {description: "Density variant controlling item padding. 'compact' for dense UIs, 'default' for standard spacing.",default: "'default'",},+ {+ name: 'onNavigateStart',+ type: '(id: string) => void',+ description:+ 'Called with the item id when navigation begins, before the scroll starts. Pair with onNavigateEnd to drive an arrival effect (flash, ring, pulse) on the target heading.',+ },+ {+ name: 'onNavigateEnd',+ type: '(id: string) => void',+ description:+ 'Called with the item id once the navigation resolves - when the smooth scroll settles, or when reduced motion turns it into an instant jump. Fires exactly once per onNavigateStart, including when the user interrupts the scroll, so a "navigating" state can never leak.',+ },+ {+ name: 'offset',+ type: 'number',+ description:+ "Height in px of a fixed header overlaying the top of the scroll root. Shifts both the activation line and the scroll landing by the same amount, so a heading activates exactly where navigating to it puts it - below the header, not underneath it. Composes with each heading's own scroll-margin-top (the header, then the breathing room below it); it does not replace it. Leave at 0 when nothing overlays the content and let scroll-margin-top do the work.",+ default: '0',+ },+ {+ name: 'scrollContainerRef',+ type: 'React.RefObject<HTMLElement | null>',+ description:+ 'Scroll container to track, instead of auto-detecting the nearest scrollable ancestor. Use it when content scrolls inside a split pane, modal, or dashboard panel rather than the viewport.',+ },+ {+ name: 'hasScrollOnClick',+ type: 'boolean',+ description:+ 'Whether activating an item smooth-scrolls to it. Set to false to own the scrolling yourself (virtualized content, a router): the Outline still updates the active item, the hash, and the navigate callbacks, but performs no scroll.',+ default: 'true',+ },{name: 'xstyle',type: 'StyleXStyles',@@ -137,6 +169,51 @@ function MarkdownOutline({markdown}) {const items = useOutlineFromMarkdown(markdown);return <Outline items={items} />;}+`,+ },+ {+ label: 'Scoped scroll container (split pane, modal, panel)',+ code: `+import {useRef} from 'react';+import {Outline} from '@astryxdesign/core/Outline';++function PanelDocs() {+ const scrollContainerRef = useRef(null);++ // Without scrollContainerRef the outline auto-detects the nearest scrollable+ // ancestor, which is the viewport here - so the highlight would never move.+ return (+ <div style={{display: 'flex'}}>+ <div ref={scrollContainerRef} style={{overflowY: 'auto', height: 480}}>+ <h2 id="overview">Overview</h2>+ {/* ...content... */}+ </div>+ <Outline items={items} scrollContainerRef={scrollContainerRef} offset={64} />+ </div>+ );+}+`,+ },+ {+ label: 'Navigate callbacks (flash the heading on arrival)',+ code: `+import {useState} from 'react';+import {Outline} from '@astryxdesign/core/Outline';++function FlashOnArrival() {+ const [flashId, setFlashId] = useState(null);++ // onNavigateEnd fires once the smooth scroll settles - and once per+ // onNavigateStart even if the user scrolls away mid-jump, so this never+ // gets stuck.+ return (+ <Outline+ items={items}+ onNavigateStart={() => setFlashId(null)}+ onNavigateEnd={id => setFlashId(id)}+ />+ );+}`,},],@@ -144,14 +221,17 @@ function MarkdownOutline({markdown}) {],usage: {description:- 'A table-of-contents sidebar for documentation pages, help centers, wikis, and long settings pages. Use it for navigation within a single page, not for app routes. Features a sliding indicator track that animates to the active heading.',+ 'A table-of-contents sidebar for documentation pages, help centers, wikis, and long settings pages. Use it for navigation within a single page, not for app routes. Features a sliding indicator track that animates to the active heading. The list is a single tab stop: arrow keys move between headings, Home/End jump to the ends, and Enter/Space activate.',bestPractices: [{guidance: true, description: 'Pass a flat ordered list of headings and let level control indentation.'},{guidance: true, description: 'Use activeId when custom scroll logic owns the active section.'},{guidance: true, description: 'Use density="compact" in dense sidebars where vertical space is tight.'},{guidance: true, description: 'Use useOutlineFromMarkdown or useOutlineFromDOM when headings are generated from content.'},+ {guidance: true, description: 'Pass scrollContainerRef when the content scrolls in a split pane, modal, or panel instead of the viewport.'},+ {guidance: true, description: 'Set offset to the height of a fixed header that overlays the content, so headings land below it instead of underneath it.'},{guidance: false, description: 'Use Outline for application navigation - use SideNav or TopNav for routes.'},{guidance: false, description: 'Use Outline for expandable hierarchy - use TreeList when nodes need expand and collapse.'},+ {guidance: false, description: 'Rely on onNavigateEnd to mean "arrived" - it also fires when the user interrupts the scroll.'},],},};@@ -205,6 +285,33 @@ export const docsZh = {description: "控制项目内边距的密度变体。'compact' 用于紧凑界面,'default' 为标准间距。",default: "'default'",},+ {+ name: 'onNavigateStart',+ type: '(id: string) => void',+ description: '导航开始时(滚动前)调用,传入项目 id。与 onNavigateEnd 搭配可在目标标题上实现到达效果(闪烁、描边、脉冲)。',+ },+ {+ name: 'onNavigateEnd',+ type: '(id: string) => void',+ description: '导航结束时调用(平滑滚动停止,或减弱动效将其变为瞬时跳转)。每次 onNavigateStart 必定对应一次调用,包括用户中途手动滚动打断的情况,因此“导航中”状态不会泄漏。',+ },+ {+ name: 'offset',+ type: 'number',+ description: '覆盖滚动根顶部的固定顶栏高度(px)。同时位移激活线与滚动落点,因此标题被激活的位置正是点击后停留的位置——落在顶栏下方,而非被顶栏遮住。它与每个标题自身的 scroll-margin-top 叠加(先顶栏,再留白),而非取代它。若没有元素覆盖内容,保持 0,交给 scroll-margin-top 处理。',+ default: '0',+ },+ {+ name: 'scrollContainerRef',+ type: 'React.RefObject<HTMLElement | null>',+ description: '要跟踪的滚动容器,替代自动探测最近的可滚动祖先。当内容在分栏、弹窗或面板中滚动而非视口时使用。',+ },+ {+ name: 'hasScrollOnClick',+ type: 'boolean',+ description: '激活项目时是否平滑滚动。设为 false 可自行接管滚动(虚拟列表、路由):Outline 仍会更新激活项、hash 和导航回调,但不执行滚动。',+ default: 'true',+ },{name: 'xstyle',type: 'StyleXStyles',@@ -230,7 +337,7 @@ export const docsZh = {/** @type {import('../docs-types').TranslationDoc} */export const docsDense = {description:- 'Document outline/table-of-contents nav with sliding indicator track. Flat items array {id,label,level}; anchor links; density variant (default/compact); uncontrolled scroll-spy by scroll position (last heading past its scroll-margin-top line; first item at top, last at bottom); controlled with activeId; smooth-scroll on click that pins the active item until the next manual scroll.',+ 'Document outline/table-of-contents nav with sliding indicator track. Flat items array {id,label,level}; anchor links; density variant (default/compact); uncontrolled scroll-spy by scroll position (last heading past its resting line = offset + its own scroll-margin-top; first item at top, last at bottom); controlled with activeId; smooth-scroll on click that pins the active item until the next manual scroll. Single tab stop (roving tabindex): Arrow keys move, Home/End jump, Enter/Space activate. onNavigateStart/onNavigateEnd fire around the scroll. Scroll scoping via offset / scrollContainerRef / hasScrollOnClick.',usage: {description:'A table-of-contents sidebar for documentation pages, help centers, wikis, and long settings pages. Use it for navigation within a single page, not for app routes.',@@ -239,8 +346,11 @@ export const docsDense = {{guidance: true, description: 'Use activeId when custom scroll logic owns the active section.'},{guidance: true, description: 'Use density="compact" in dense sidebars where vertical space is tight.'},{guidance: true, description: 'Use useOutlineFromMarkdown or useOutlineFromDOM when headings are generated from content.'},+ {guidance: true, description: 'Pass scrollContainerRef when the content scrolls in a split pane, modal, or panel instead of the viewport.'},+ {guidance: true, description: 'Set offset to the height of a fixed header that overlays the content, so headings land below it instead of underneath it.'},{guidance: false, description: 'Use Outline for application navigation - use SideNav or TopNav for routes.'},{guidance: false, description: 'Use Outline for expandable hierarchy - use TreeList when nodes need expand and collapse.'},+ {guidance: false, description: 'Rely on onNavigateEnd to mean "arrived" - it also fires when the user interrupts the scroll.'},],},propDescriptions: {@@ -249,6 +359,11 @@ export const docsDense = {onActiveIdChange: 'Called when active id changes from scroll-spy or click.',label: "Accessible nav label. Default: 'Table of contents'.",density: "Density variant: 'default' (standard) or 'compact'. Default: 'default'.",+ onNavigateStart: 'Called with the id when navigation begins, before the scroll.',+ onNavigateEnd: 'Called with the id once the scroll settles. Fires exactly once per onNavigateStart, including on user interruption.',+ offset: 'Height in px of a fixed header overlaying the scroll root. Shifts BOTH the activation line and the scroll landing, so a heading activates where navigating to it lands it. Composes with (does not replace) each heading scroll-margin-top. Default: 0.',+ scrollContainerRef: 'RefObject of the scroll container to track, instead of the nearest scrollable ancestor. For split panes, modals, panels.',+ hasScrollOnClick: 'Whether activating an item smooth-scrolls to it. false = you own scrolling; active id, hash and callbacks still update. Default: true.',xstyle: 'StyleX styles for layout. Must be stylex.create() value.',},components: [@@ -256,13 +371,18 @@ export const docsDense = {name: 'Outline',displayName: 'Outline',description:- 'Document outline nav with sliding indicator. Renders heading anchors with a density variant and manages scroll-spy active state when uncontrolled.',+ 'Document outline nav with sliding indicator. Renders heading anchors with a density variant, roving-tabindex keyboard nav, navigate callbacks, and scroll-spy active state when uncontrolled.',propDescriptions: {items: 'Ordered OutlineItem[]: {id,label,level}. id should match target heading DOM id.',activeId: 'Controlled active heading id. Disables built-in scroll-spy.',onActiveIdChange: 'Called when active id changes from scroll-spy or click.',label: "Accessible nav label. Default: 'Table of contents'.",density: "Density variant: 'default' | 'compact'. Default: 'default'.",+ onNavigateStart: 'Called with the id when navigation begins, before the scroll.',+ onNavigateEnd: 'Called with the id once the scroll settles. Fires exactly once per onNavigateStart, including on user interruption.',+ offset: 'Height in px of a fixed header overlaying the scroll root. Shifts both the activation line and the scroll landing. Composes with scroll-margin-top. Default: 0.',+ scrollContainerRef: 'RefObject of the scroll container to track, instead of the nearest scrollable ancestor.',+ hasScrollOnClick: 'Whether activating an item smooth-scrolls to it. Default: true.',xstyle: 'StyleX styles for layout. Must be stylex.create() value.',},},diff --git a/packages/core/src/Outline/Outline.test.tsx b/packages/core/src/Outline/Outline.test.tsxindex f655e1cdf3..1536bb9db2 100644--- a/packages/core/src/Outline/Outline.test.tsx+++ b/packages/core/src/Outline/Outline.test.tsx@@ -287,6 +287,741 @@ describe('Outline', () => {});});+/**+ * Override `scroll-margin-top` for specific elements in `getComputedStyle`.+ * jsdom's cssstyle does not resolve `scroll-margin-top`, so the real value can+ * never be read back from an inline style — the property must be faked at the+ * `getComputedStyle` boundary that useScrollSpy actually reads. Every other+ * element (and every other property) falls through to the real implementation,+ * so StyleX and Testing Library are unaffected.+ */+function mockScrollMarginTop(overrides: Map<Element, string>) {+ const original = window.getComputedStyle.bind(window);+ vi.spyOn(window, 'getComputedStyle').mockImplementation(+ (element, pseudoElement) => {+ const style = original(element, pseudoElement ?? undefined);+ const scrollMarginTop = overrides.get(element);+ if (scrollMarginTop != null) {+ // An own property shadows the prototype's accessor, so the real+ // CSSStyleDeclaration keeps working for every other property.+ Object.defineProperty(style, 'scrollMarginTop', {+ value: scrollMarginTop,+ configurable: true,+ });+ }+ return style;+ },+ );+}++/**+ * Mount real heading elements for `items` so navigation has scroll targets.+ * Returns a cleanup that removes them.+ */+function mountHeadings(ids: string[] = items.map(item => item.id)) {+ const headings = ids.map(id => {+ const heading = document.createElement('h2');+ heading.id = id;+ document.body.appendChild(heading);+ return heading;+ });+ return () => {+ for (const heading of headings) {+ heading.remove();+ }+ };+}++describe('Outline keyboard navigation', () => {+ beforeEach(() => {+ Element.prototype.scrollIntoView = vi.fn();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('exposes a single tab stop (roving tabindex) instead of one per heading', () => {+ render(<Outline items={items} />);+ const links = screen.getAllByRole('link');++ // A 40-heading TOC must not cost 40 Tab presses: exactly one link is in+ // the page tab order, the rest are reachable with arrow keys.+ expect(links.map(link => link.getAttribute('tabindex'))).toEqual([+ '0',+ '-1',+ '-1',+ ]);+ });++ it('seats the tab stop on the active heading, not always the first', () => {+ // WAI-ARIA roving tabindex: the single tab stop belongs on the *current*+ // item. Tabbing into a TOC while reading section 3 must land on section 3,+ // not send the reader back to section 1.+ render(<Outline items={items} activeId="api" />);+ const links = screen.getAllByRole('link');++ expect(links.map(link => link.getAttribute('tabindex'))).toEqual([+ '-1',+ '-1',+ '0',+ ]);+ });++ it('moves the tab stop as the active heading changes', () => {+ const {rerender} = render(<Outline items={items} activeId="intro" />);+ expect(+ screen.getAllByRole('link').map(l => l.getAttribute('tabindex')),+ ).toEqual(['0', '-1', '-1']);++ // Scroll-spy advances the active section: the tab stop must follow it.+ rerender(<Outline items={items} activeId="install" />);+ expect(+ screen.getAllByRole('link').map(l => l.getAttribute('tabindex')),+ ).toEqual(['-1', '0', '-1']);+ });++ it('does not yank the tab stop away from the item the user arrowed to', async () => {+ const user = userEvent.setup();+ const {rerender} = render(<Outline items={items} activeId="intro" />);+ const links = screen.getAllByRole('link');++ // User arrow-keys down to `api` and keeps focus there.+ links[0].focus();+ await user.keyboard('{ArrowDown}{ArrowDown}');+ expect(links[2]).toHaveFocus();+ expect(links[2]).toHaveAttribute('tabindex', '0');++ // Scroll-spy moves the active section underneath them. Focus is still+ // inside the list, so the tab stop must stay where the user put it.+ rerender(<Outline items={items} activeId="install" />);+ expect(links[2]).toHaveAttribute('tabindex', '0');+ expect(links[1]).toHaveAttribute('tabindex', '-1');+ });++ it('moves focus with ArrowDown / ArrowUp', async () => {+ const user = userEvent.setup();+ render(<Outline items={items} />);+ const [intro, install] = screen.getAllByRole('link');++ intro.focus();+ await user.keyboard('{ArrowDown}');+ expect(install).toHaveFocus();+ expect(install).toHaveAttribute('tabindex', '0');+ expect(intro).toHaveAttribute('tabindex', '-1');++ await user.keyboard('{ArrowUp}');+ expect(intro).toHaveFocus();+ });++ it('jumps to first / last with Home / End', async () => {+ const user = userEvent.setup();+ render(<Outline items={items} />);+ const links = screen.getAllByRole('link');++ links[0].focus();+ await user.keyboard('{End}');+ expect(links[2]).toHaveFocus();++ await user.keyboard('{Home}');+ expect(links[0]).toHaveFocus();+ });++ it('activates the focused link with Space', async () => {+ const user = userEvent.setup();+ const cleanup = mountHeadings();+ const onNavigateStart = vi.fn();++ render(<Outline items={items} onNavigateStart={onNavigateStart} />);+ const install = screen.getAllByRole('link')[1];+ install.focus();+ await user.keyboard('[Space]');++ expect(onNavigateStart).toHaveBeenCalledWith('install');+ expect(document.getElementById('install')?.scrollIntoView).toBeDefined();+ expect(+ (document.getElementById('install') as HTMLElement).scrollIntoView,+ ).toHaveBeenCalledWith({behavior: 'smooth', block: 'start'});++ cleanup();+ });++ it('activates the focused link with Enter', async () => {+ const user = userEvent.setup();+ const cleanup = mountHeadings();+ const onNavigateStart = vi.fn();++ render(<Outline items={items} onNavigateStart={onNavigateStart} />);+ screen.getAllByRole('link')[2].focus();+ await user.keyboard('{Enter}');++ expect(onNavigateStart).toHaveBeenCalledWith('api');+ cleanup();+ });++ it('leaves modifier chords to the browser (Cmd/Ctrl + Space is not activation)', async () => {+ const user = userEvent.setup();+ const cleanup = mountHeadings();+ const onNavigateStart = vi.fn();++ render(<Outline items={items} onNavigateStart={onNavigateStart} />);+ screen.getAllByRole('link')[1].focus();+ await user.keyboard('{Meta>}[Space]{/Meta}');++ expect(onNavigateStart).not.toHaveBeenCalled();+ cleanup();+ });++ it('does not treat its own Space activation as a manual scroll', async () => {+ const user = userEvent.setup();+ const cleanup = mountHeadings();+ const onNavigateEnd = vi.fn();++ render(<Outline items={items} onNavigateEnd={onNavigateEnd} />);+ screen.getAllByRole('link')[1].focus();+ await user.keyboard('[Space]');++ // Space is one of the keys that normally scroll the page, and the settle+ // watcher listens on window — so the very keydown that started this+ // navigation would bubble up and cancel it. Because we preventDefault it,+ // no scroll can happen and the navigation must survive.+ expect(onNavigateEnd).not.toHaveBeenCalled();++ act(() => {+ window.dispatchEvent(new Event('scrollend'));+ });+ expect(onNavigateEnd).toHaveBeenCalledTimes(1);+ expect(screen.getByRole('link', {name: 'Installation'})).toHaveAttribute(+ 'aria-current',+ 'true',+ );++ cleanup();+ });++ it('does not treat arrow-key roving focus as a manual scroll', async () => {+ const user = userEvent.setup();+ const cleanup = mountHeadings();+ const onNavigateEnd = vi.fn();++ render(<Outline items={items} onNavigateEnd={onNavigateEnd} />);+ await user.click(screen.getByRole('link', {name: 'Installation'}));++ // Arrow keys inside the outline move focus; they are prevented, so they do+ // not scroll the page and must not cancel the in-flight navigation.+ await user.keyboard('{ArrowDown}');+ expect(onNavigateEnd).not.toHaveBeenCalled();++ cleanup();+ });++ it('does not steal Tab from the page', async () => {+ const user = userEvent.setup();+ render(+ <>+ <Outline items={items} />+ <button type="button">After</button>+ </>,+ );++ screen.getAllByRole('link')[0].focus();+ await user.tab();++ // The non-tabbable links are skipped, so one Tab leaves the whole outline.+ expect(screen.getByRole('button', {name: 'After'})).toHaveFocus();+ });++ it('keeps a single tab stop with one item, and none with zero items', () => {+ const {rerender} = render(+ <Outline items={[{id: 'only', label: 'Only', level: 2}]} />,+ );+ expect(screen.getAllByRole('link')[0]).toHaveAttribute('tabindex', '0');++ rerender(<Outline items={[]} />);+ expect(screen.queryAllByRole('link')).toHaveLength(0);+ });+});++describe('Outline navigate callbacks', () => {+ beforeEach(() => {+ Element.prototype.scrollIntoView = vi.fn();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();+ });++ it('fires onNavigateStart on click and onNavigateEnd when the scroll settles', async () => {+ const user = userEvent.setup();+ const cleanup = mountHeadings();+ const onNavigateStart = vi.fn();+ const onNavigateEnd = vi.fn();++ render(+ <Outline+ items={items}+ onNavigateStart={onNavigateStart}+ onNavigateEnd={onNavigateEnd}+ />,+ );+ await user.click(screen.getByRole('link', {name: 'Installation'}));++ expect(onNavigateStart).toHaveBeenCalledWith('install');+ // Still scrolling — arrival has not happened yet.+ expect(onNavigateEnd).not.toHaveBeenCalled();++ act(() => {+ window.dispatchEvent(new Event('scrollend'));+ });+ expect(onNavigateEnd).toHaveBeenCalledTimes(1);+ expect(onNavigateEnd).toHaveBeenCalledWith('install');++ cleanup();+ });++ it('fires the callbacks in controlled mode too', async () => {+ const user = userEvent.setup();+ const cleanup = mountHeadings();+ const onNavigateStart = vi.fn();+ const onNavigateEnd = vi.fn();++ render(+ <Outline+ items={items}+ activeId="intro"+ onNavigateStart={onNavigateStart}+ onNavigateEnd={onNavigateEnd}+ />,+ );+ await user.click(screen.getByRole('link', {name: 'API'}));++ expect(onNavigateStart).toHaveBeenCalledWith('api');+ act(() => {+ window.dispatchEvent(new Event('scrollend'));+ });+ expect(onNavigateEnd).toHaveBeenCalledTimes(1);+ expect(onNavigateEnd).toHaveBeenCalledWith('api');++ cleanup();+ });++ it('falls back to a settle timeout when scrollend never fires', async () => {+ vi.useFakeTimers({shouldAdvanceTime: true});+ const user = userEvent.setup({advanceTimers: vi.advanceTimersByTime});+ const cleanup = mountHeadings();+ const onNavigateEnd = vi.fn();++ render(<Outline items={items} onNavigateEnd={onNavigateEnd} />);+ await user.click(screen.getByRole('link', {name: 'Installation'}));++ expect(onNavigateEnd).not.toHaveBeenCalled();+ act(() => {+ vi.advanceTimersByTime(2000);+ });+ expect(onNavigateEnd).toHaveBeenCalledTimes(1);+ expect(onNavigateEnd).toHaveBeenCalledWith('install');++ cleanup();+ });++ it('fires onNavigateEnd exactly once when scrollend AND the fallback both elapse', async () => {+ vi.useFakeTimers({shouldAdvanceTime: true});+ const user = userEvent.setup({advanceTimers: vi.advanceTimersByTime});+ const cleanup = mountHeadings();+ const onNavigateEnd = vi.fn();++ render(<Outline items={items} onNavigateEnd={onNavigateEnd} />);+ await user.click(screen.getByRole('link', {name: 'Installation'}));++ // Reduced motion turns the smooth scroll into an instant jump: scrollend+ // arrives immediately. The fallback timer must not fire a second time.+ act(() => {+ window.dispatchEvent(new Event('scrollend'));+ window.dispatchEvent(new Event('scrollend'));+ vi.advanceTimersByTime(5000);+ });+ expect(onNavigateEnd).toHaveBeenCalledTimes(1);+ expect(onNavigateEnd).toHaveBeenCalledWith('install');++ cleanup();+ });++ it('still fires onNavigateEnd once when a manual scroll interrupts the jump', async () => {+ const user = userEvent.setup();+ const cleanup = mountHeadings();+ const onNavigateStart = vi.fn();+ const onNavigateEnd = vi.fn();++ render(+ <Outline+ items={items}+ onNavigateStart={onNavigateStart}+ onNavigateEnd={onNavigateEnd}+ />,+ );+ await user.click(screen.getByRole('link', {name: 'Installation'}));+ expect(onNavigateStart).toHaveBeenCalledTimes(1);++ act(() => {+ window.dispatchEvent(new Event('wheel'));+ });++ // Every onNavigateStart is balanced by exactly one onNavigateEnd, so a+ // consumer's "navigating" state can never leak.+ expect(onNavigateEnd).toHaveBeenCalledTimes(1);+ expect(onNavigateEnd).toHaveBeenCalledWith('install');++ cleanup();+ });++ it('does not fire callbacks when the target heading is missing', async () => {+ const user = userEvent.setup();+ const onNavigateStart = vi.fn();+ const onNavigateEnd = vi.fn();++ render(+ <Outline+ items={items}+ onNavigateStart={onNavigateStart}+ onNavigateEnd={onNavigateEnd}+ />,+ );+ await user.click(screen.getByRole('link', {name: 'Installation'}));++ expect(onNavigateStart).not.toHaveBeenCalled();+ expect(onNavigateEnd).not.toHaveBeenCalled();+ });++ it('leaves a missing target to the browser instead of deadening the link', async () => {+ const user = userEvent.setup();+ window.location.hash = '';++ render(<Outline items={items} />);+ await user.click(screen.getByRole('link', {name: 'Installation'}));++ // The heading is not in the DOM (lazily-rendered or virtualized content).+ // We own the scroll only when we have something to scroll to; with no+ // target we must NOT preventDefault, or the anchor becomes a total no-op.+ // The browser's native fragment navigation still updates the URL, so a+ // later render / deep link can still resolve it.+ expect(window.location.hash).toBe('#install');++ window.location.hash = '';+ });++ it('does not fire callbacks for a modified (Cmd) click', async () => {+ const user = userEvent.setup();+ const cleanup = mountHeadings();+ const onNavigateStart = vi.fn();++ render(<Outline items={items} onNavigateStart={onNavigateStart} />);+ await user.keyboard('{Meta>}');+ await user.click(screen.getByRole('link', {name: 'Installation'}));+ await user.keyboard('{/Meta}');++ expect(onNavigateStart).not.toHaveBeenCalled();+ cleanup();+ });+});++describe('Outline scroll scoping', () => {+ beforeEach(() => {+ Element.prototype.scrollIntoView = vi.fn();+ // jsdom implements neither; the offset path drives the scroll through them.+ Element.prototype.scrollBy = vi.fn();+ window.scrollBy = vi.fn();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('hasScrollOnClick={false} skips the scroll but still navigates', async () => {+ const user = userEvent.setup();+ const cleanup = mountHeadings();+ const onNavigateStart = vi.fn();+ const onNavigateEnd = vi.fn();++ render(+ <Outline+ items={items}+ hasScrollOnClick={false}+ onNavigateStart={onNavigateStart}+ onNavigateEnd={onNavigateEnd}+ />,+ );+ await user.click(screen.getByRole('link', {name: 'Installation'}));++ const target = document.getElementById('install') as HTMLElement;+ expect(target.scrollIntoView).not.toHaveBeenCalled();+ // The consumer owns scrolling; they still learn where to go.+ expect(onNavigateStart).toHaveBeenCalledWith('install');+ // There is nothing to scroll, so nothing to wait for: onNavigateEnd must+ // resolve immediately rather than waiting out the settle timeout — an+ // arrival effect paired with onNavigateEnd would otherwise land ~1.2s late+ // for no reason.+ expect(onNavigateEnd).toHaveBeenCalledWith('install');+ expect(screen.getByRole('link', {name: 'Installation'})).toHaveAttribute(+ 'aria-current',+ 'true',+ );++ cleanup();+ });++ it('offset shifts the activation line for a fixed header', () => {+ const cleanup = mountHeadings();+ const [intro, install, api] = items.map(+ item => document.getElementById(item.id) as HTMLElement,+ );++ Object.defineProperty(document.documentElement, 'scrollHeight', {+ value: 4000,+ configurable: true,+ });+ vi.spyOn(intro, 'getBoundingClientRect').mockReturnValue({+ top: -200,+ } as DOMRect);+ // `install` sits 40px below the viewport top — under a 64px fixed header,+ // so it should already be active once `offset={64}` is declared.+ vi.spyOn(install, 'getBoundingClientRect').mockReturnValue({+ top: 40,+ } as DOMRect);+ vi.spyOn(api, 'getBoundingClientRect').mockReturnValue({+ top: 400,+ } as DOMRect);++ const {rerender} = render(<Outline items={items} />);+ // Without offset the activation line is the viewport top: `install` (top:40)+ // has not reached it, so `intro` stays active.+ expect(screen.getByRole('link', {name: 'Introduction'})).toHaveAttribute(+ 'aria-current',+ 'true',+ );++ rerender(<Outline items={items} offset={64} />);+ act(() => {+ window.dispatchEvent(new Event('resize'));+ });+ expect(screen.getByRole('link', {name: 'Installation'})).toHaveAttribute(+ 'aria-current',+ 'true',+ );++ cleanup();+ });++ it('lands the heading below a fixed header instead of underneath it', async () => {+ const user = userEvent.setup();+ const cleanup = mountHeadings();+ const install = document.getElementById('install') as HTMLElement;++ // The heading sits 400px down the page and asks for 8px of breathing room+ // below whatever is above it.+ vi.spyOn(install, 'getBoundingClientRect').mockReturnValue({+ top: 400,+ } as DOMRect);+ mockScrollMarginTop(new Map([[install, '8px']]));++ render(<Outline items={items} offset={48} />);+ await user.click(screen.getByRole('link', {name: 'Installation'}));++ // A 48px fixed header covers the top of the scroll root, so the heading+ // must come to rest at 48 (header) + 8 (its own scroll-margin-top) = 56px+ // — NOT at 8px, which would park it underneath the header, invisible.+ // scrollIntoView cannot know about the header, so it must not be used here.+ expect(window.scrollBy).toHaveBeenCalledWith({+ top: 400 - 56,+ behavior: 'smooth',+ });+ expect(install.scrollIntoView).not.toHaveBeenCalled();++ cleanup();+ });++ it('lands the heading below a fixed header inside a scoped container', async () => {+ const user = userEvent.setup();+ const cleanup = mountHeadings();+ const install = document.getElementById('install') as HTMLElement;++ const pane = document.createElement('div');+ document.body.appendChild(pane);+ pane.scrollBy = vi.fn();+ vi.spyOn(pane, 'getBoundingClientRect').mockReturnValue({+ top: 100,+ } as DOMRect);+ vi.spyOn(install, 'getBoundingClientRect').mockReturnValue({+ top: 500,+ } as DOMRect);++ render(+ <Outline+ items={items}+ scrollContainerRef={{current: pane}}+ offset={48}+ />,+ );+ await user.click(screen.getByRole('link', {name: 'Installation'}));++ // Measured from the pane's own top (100), not the viewport's.+ expect(pane.scrollBy).toHaveBeenCalledWith({+ top: 500 - (100 + 48),+ behavior: 'smooth',+ });+ expect(window.scrollBy).not.toHaveBeenCalled();++ cleanup();+ pane.remove();+ });++ it('keeps the CSS-native scrollIntoView path when offset is 0', async () => {+ const user = userEvent.setup();+ const cleanup = mountHeadings();++ render(<Outline items={items} />);+ await user.click(screen.getByRole('link', {name: 'Installation'}));++ // No fixed header to compensate for: let the browser honor+ // scroll-margin-top itself rather than doing the math in JS.+ const install = document.getElementById('install') as HTMLElement;+ expect(install.scrollIntoView).toHaveBeenCalledWith({+ behavior: 'smooth',+ block: 'start',+ });+ expect(window.scrollBy).not.toHaveBeenCalled();++ cleanup();+ });++ it('composes offset with the heading own scroll-margin-top for activation', () => {+ const cleanup = mountHeadings();+ const [intro, install, api] = items.map(+ item => document.getElementById(item.id) as HTMLElement,+ );++ Object.defineProperty(document.documentElement, 'scrollHeight', {+ value: 4000,+ configurable: true,+ });+ // Every heading declares 8px of scroll-margin-top; the header is 48px.+ // The activation line is therefore 48 + 8 = 56px (+1px tolerance).+ mockScrollMarginTop(+ new Map([+ [intro, '8px'],+ [install, '8px'],+ [api, '8px'],+ ]),+ );+ vi.spyOn(intro, 'getBoundingClientRect').mockReturnValue({+ top: -200,+ } as DOMRect);+ // 50 < 56: `install` has crossed the composed line, so it is active.+ vi.spyOn(install, 'getBoundingClientRect').mockReturnValue({+ top: 50,+ } as DOMRect);+ // 60 > 56: `api` has NOT crossed it. If offset and scroll-margin-top were+ // double-counted (96px) this would wrongly activate.+ vi.spyOn(api, 'getBoundingClientRect').mockReturnValue({+ top: 60,+ } as DOMRect);++ render(<Outline items={items} offset={48} />);++ expect(screen.getByRole('link', {name: 'Installation'})).toHaveAttribute(+ 'aria-current',+ 'true',+ );+ expect(screen.getByRole('link', {name: 'API'})).not.toHaveAttribute(+ 'aria-current',+ );++ cleanup();+ });++ it('scrollContainerRef scopes tracking to a custom scroll container', () => {+ const cleanup = mountHeadings();+ const [intro, install, api] = items.map(+ item => document.getElementById(item.id) as HTMLElement,+ );++ // A split-pane / modal scroll container. It is deliberately NOT a+ // scrollable ancestor of the Outline, so the auto-detect heuristic would+ // fall back to the window — the exact case that leaves a TOC's highlight+ // stuck today. Scoping must use this element's box as the activation line.+ const pane = document.createElement('div');+ document.body.appendChild(pane);+ vi.spyOn(pane, 'getBoundingClientRect').mockReturnValue({+ top: 300,+ } as DOMRect);+ Object.defineProperty(pane, 'scrollTop', {value: 0, configurable: true});+ Object.defineProperty(pane, 'clientHeight', {+ value: 500,+ configurable: true,+ });+ Object.defineProperty(pane, 'scrollHeight', {+ value: 4000,+ configurable: true,+ });++ // Relative to the pane's top (300), intro and install have passed; api not.+ // Relative to the viewport (0) all three would have passed, which would+ // make `api` active — so this asserts the pane really is the scroll root.+ vi.spyOn(intro, 'getBoundingClientRect').mockReturnValue({+ top: 100,+ } as DOMRect);+ vi.spyOn(install, 'getBoundingClientRect').mockReturnValue({+ top: 250,+ } as DOMRect);+ vi.spyOn(api, 'getBoundingClientRect').mockReturnValue({+ top: 600,+ } as DOMRect);++ render(<Outline items={items} scrollContainerRef={{current: pane}} />);++ expect(screen.getByRole('link', {name: 'Installation'})).toHaveAttribute(+ 'aria-current',+ 'true',+ );++ pane.remove();+ cleanup();+ });++ it('settles a scoped navigation on the container scrollend, not the window', async () => {+ const user = userEvent.setup();+ const cleanup = mountHeadings();+ const onNavigateEnd = vi.fn();++ const pane = document.createElement('div');+ document.body.appendChild(pane);++ render(+ <Outline+ items={items}+ scrollContainerRef={{current: pane}}+ onNavigateEnd={onNavigateEnd}+ />,+ );+ await user.click(screen.getByRole('link', {name: 'Installation'}));++ // A window scrollend must NOT settle a container-scoped navigation.+ act(() => {+ window.dispatchEvent(new Event('scrollend'));+ });+ expect(onNavigateEnd).not.toHaveBeenCalled();++ act(() => {+ pane.dispatchEvent(new Event('scrollend'));+ });+ expect(onNavigateEnd).toHaveBeenCalledTimes(1);+ expect(onNavigateEnd).toHaveBeenCalledWith('install');++ pane.remove();+ cleanup();+ });+});+describe('useOutlineFromDOM', () => {it('collects headings from DOM container', () => {function Demo() {diff --git a/packages/core/src/Outline/Outline.tsx b/packages/core/src/Outline/Outline.tsxindex 78a6e9a992..64886bc8e6 100644--- a/packages/core/src/Outline/Outline.tsx+++ b/packages/core/src/Outline/Outline.tsx@@ -4,7 +4,7 @@/*** @file Outline.tsx- * @input Uses React, StyleX, Astryx link provider integration, Outline hooks/types+ * @input Uses React, StyleX, Astryx link provider integration, Outline hooks/types, useListFocus* @output Exports Outline component and OutlineProps type* @position Core implementation; consumed by index.ts*@@ -12,6 +12,9 @@* - Sliding indicator track (vertical divider + animated active bar)* - Density variant (default/compact)* - Scroll-spy active state when uncontrolled+ * - Roving-tabindex keyboard navigation (Arrow/Home/End, Enter/Space activate)+ * - onNavigateStart / onNavigateEnd callbacks around the smooth scroll+ * - Scroll scoping (offset, scrollContainerRef, hasScrollOnClick)** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Outline/Outline.doc.mjs@@ -32,6 +35,8 @@ import {fontWeightVars,} from '../theme/tokens.stylex';import {useLinkComponent} from '../Link/useLinkComponent';+import {useListFocus} from '../hooks/useListFocus';+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import {mergeProps, mergeRefs} from '../utils';import type {BaseProps} from '../BaseProps';import {useScrollSpy} from './useScrollSpy';@@ -65,6 +70,55 @@ export interface OutlineProps extends BaseProps<HTMLElement> {*/density?: 'default' | 'compact';+ /**+ * Called when navigation to an item begins, before the scroll starts.+ * Receives the item `id`. Pair with `onNavigateEnd` to drive an arrival+ * effect (flash, ring, pulse) on the target heading.+ */+ onNavigateStart?: (id: string) => void;++ /**+ * Called once when navigation to an item resolves — when the smooth scroll+ * settles, or immediately-ish when reduced motion turns it into a jump.+ *+ * Fires exactly once for every `onNavigateStart`, including when the user+ * interrupts the scroll by scrolling manually, so a "navigating" state can+ * never leak. It does not fire if the Outline unmounts mid-scroll.+ */+ onNavigateEnd?: (id: string) => void;++ /**+ * Height in px of a fixed header overlaying the top of the scroll root.+ *+ * Shifts both the activation line *and* the scroll landing by the same+ * amount, so a heading activates exactly where navigating to it puts it —+ * below the header rather than hidden underneath it.+ *+ * It composes with each heading's own `scroll-margin-top` (the header, then+ * the breathing room below it) rather than replacing it. When nothing+ * overlays the content, leave this at 0 and let `scroll-margin-top` do the+ * work — the browser already honors it.+ *+ * @default 0+ */+ offset?: number;++ /**+ * Scroll container to track, instead of auto-detecting the nearest scrollable+ * ancestor. Use this when the content scrolls inside a split pane, modal, or+ * dashboard panel rather than the viewport.+ */+ scrollContainerRef?: React.RefObject<HTMLElement | null>;++ /**+ * Whether activating an item smooth-scrolls to it. Set to false to own the+ * scrolling yourself (virtualized content, a router) — the Outline still+ * updates the active item, the hash, and the navigate callbacks, but performs+ * no scroll and suppresses the anchor's default jump.+ * @default true+ */+ hasScrollOnClick?: boolean;+/** Test ID for testing frameworks. */'data-testid'?: string;}@@ -219,8 +273,15 @@ function getIndentStyle(level: number) {* track that animates to the active item.** When `activeId` is omitted, it tracks scroll position and marks the last- * heading whose top has passed its activation line (its scroll-margin-top)- * active — defaulting to the first item at the top and the last at the bottom.+ * heading whose top has passed its activation line — which is exactly where+ * navigating to that heading lands it: `offset` (a fixed header overlaying the+ * scroll root) plus the heading's own `scroll-margin-top`. It defaults to the+ * first item at the top and the last at the bottom.+ *+ * Keyboard: the list is a single tab stop (roving tabindex), seated on the+ * active heading. Arrow keys move between headings, Home/End jump to the ends,+ * and Enter/Space activate — so a long table of contents costs one Tab press,+ * not one per heading.** @example* ```@@ -232,6 +293,21 @@ function getIndentStyle(level: number) {* ]}* />* ```+ *+ * Scoped to a custom scroll container, under a fixed header:+ *+ * @example+ * ```+ * const scrollContainerRef = useRef<HTMLDivElement>(null);+ *+ * <div ref={scrollContainerRef} style={{overflowY: 'auto'}}>...</div>+ * <Outline+ * items={items}+ * scrollContainerRef={scrollContainerRef}+ * offset={64}+ * onNavigateEnd={id => flashHeading(id)}+ * />+ * ```*/export function Outline({items,@@ -239,6 +315,11 @@ export function Outline({onActiveIdChange,label: labelFromProps,density = 'default',+ onNavigateStart,+ onNavigateEnd,+ offset = 0,+ scrollContainerRef,+ hasScrollOnClick = true,xstyle,className,style,@@ -250,50 +331,114 @@ export function Outline({const label = labelFromProps ?? t('@astryx.outline.label');const rootRef = useRef<HTMLElement | null>(null);const LinkComponent = useLinkComponent();- const isControlled = activeId !== undefined;- const {- activeId: resolvedActiveId,- setActiveId,- lockActiveId,- } = useScrollSpy({+ const {activeId: resolvedActiveId, scrollTo} = useScrollSpy({activeId,items,onActiveIdChange,rootRef,+ offset,+ scrollContainerRef,+ hasScrollOnClick,+ onNavigateStart,+ onNavigateEnd,+ });++ // Roving tabindex over the links: the whole outline is one tab stop, and+ // arrows move between headings. The hook owns `tabindex` on the items.+ const {+ listRef,+ handleKeyDown: handleListKeyDown,+ handleFocus,+ } = useListFocus<HTMLUListElement>({+ itemSelector: 'a[href]',+ orientation: 'vertical',+ hasRovingTabIndex: true,});+ // Seat the tab stop on the *active* heading. WAI-ARIA puts the single tab+ // stop on the current item, so tabbing into a table of contents while+ // reading section 7 lands on section 7 — not back at section 1, which is+ // where useListFocus would otherwise leave it (it promotes the first item on+ // mount and then keeps whichever item already holds the stop).+ //+ // Only while focus is outside the list: once the reader has arrowed to an+ // item, the stop is theirs and scroll-spy must not yank it away. Sets+ // `tabindex` only — it never steals focus. Registered after useListFocus so+ // it runs after the hook's own layout effect and wins; on later commits the+ // hook then finds this item already holding the stop and keeps it.+ useIsomorphicLayoutEffect(() => {+ const list = listRef.current;+ if (list == null || list.contains(document.activeElement)) {+ return;+ }+ const links = Array.from(list.querySelectorAll<HTMLElement>('a[href]'));+ const active = links.find(+ link => link.getAttribute('aria-current') === 'true',+ );+ if (active == null) {+ return;+ }+ for (const link of links) {+ const tabIndex = link === active ? '0' : '-1';+ if (link.getAttribute('tabindex') !== tabIndex) {+ link.setAttribute('tabindex', tabIndex);+ }+ }+ });++ /**+ * The single navigation path, shared by click and keyboard activation:+ * push the hash, then hand off to the scroll-spy's `scrollTo`, which fires+ * the navigate callbacks and moves the indicator when the scroll settles.+ */+ const navigate = (id: string) => {+ if (scrollTo(id)) {+ window.history.pushState(null, '', `#${id}`);+ }+ };++ /** Whether an event carries a modifier chord we must leave to the browser. */+ const hasModifier = (+ event: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>,+ ) => event.metaKey || event.altKey || event.ctrlKey || event.shiftKey;+const handleClick =(id: string) => (event: React.MouseEvent<HTMLElement>) => {- const target = document.getElementById(id);-- // Let the browser handle modified clicks (open in new tab, etc.) and- // missing targets without touching the active state.- if (- target == null ||- event.defaultPrevented ||- event.metaKey ||- event.altKey ||- event.ctrlKey ||- event.shiftKey- ) {+ // Let the browser handle modified clicks (open in new tab, etc.) without+ // touching the active state.+ if (event.defaultPrevented || hasModifier(event)) {+ return;+ }++ // With no target in the DOM — lazily-rendered or virtualized content —+ // there is nothing to scroll to and nothing to make active. Leave the+ // anchor to the browser's native fragment navigation (which still+ // updates the URL) rather than swallowing the click into a dead link.+ if (document.getElementById(id) == null) {return;}+ // Suppress the anchor's default jump: we own the scroll (or, with+ // `hasScrollOnClick={false}`, deliberately leave it to the consumer).event.preventDefault();- window.history.pushState(null, '', `#${id}`);+ navigate(id);+ };- // Move the indicator to the clicked item in a single step. Controlled- // consumers own the active state (notify only); uncontrolled mode pins- // the active id and suppresses scroll-spy until the next manual scroll,- // so the click is honored — even for short/last sections — and the- // indicator doesn't chase the smooth scroll through other sections.- if (isControlled) {- setActiveId(id);- } else {- lockActiveId(id);+ const handleKeyDown =+ (id: string) => (event: React.KeyboardEvent<HTMLElement>) => {+ // Enter is a link's native activation and already produces a click.+ // Space is not, so wire it up here to match the button-like affordance.+ if (event.key !== ' ' && event.key !== 'Spacebar') {+ return;+ }+ if (event.defaultPrevented || hasModifier(event)) {+ return;}- target.scrollIntoView({behavior: 'smooth', block: 'start'});+ // preventDefault does double duty: it stops the page from scrolling, and+ // it tells useScrollSpy this Space is an activation, not a manual scroll.+ event.preventDefault();+ navigate(id);};return (@@ -308,7 +453,12 @@ export function Outline({className,style,)}>- <ul {...stylex.props(styles.list)} role="list">+ <ul+ {...stylex.props(styles.list)}+ ref={listRef}+ role="list"+ onKeyDown={handleListKeyDown}+ onFocus={handleFocus}>{items.map(item => {const isActive = item.id === resolvedActiveId;@@ -318,6 +468,7 @@ export function Outline({href={`#${item.id}`}aria-current={isActive ? 'true' : undefined}onClick={handleClick(item.id)}+ onKeyDown={handleKeyDown(item.id)}{...mergeProps(themeProps('outline-item', {active: isActive ? 'active' : null,diff --git a/packages/core/src/Outline/useScrollSpy.ts b/packages/core/src/Outline/useScrollSpy.tsindex d686cc8623..d71d78822b 100644--- a/packages/core/src/Outline/useScrollSpy.ts+++ b/packages/core/src/Outline/useScrollSpy.ts@@ -10,11 +10,26 @@** Drives the active outline item from scroll position. On each scroll* (rAF-throttled) it reads live heading positions and marks the last heading- * whose top has passed its activation line (its own scroll-margin-top, i.e.- * where it lands when navigated to). This is stable — it never compares stale- * cached positions — so the indicator moves monotonically instead of jumping.- * Defaults to the first item at the top and the last item at the bottom so- * short final sections still activate.+ * whose top has passed its activation line. This is stable — it never compares+ * stale cached positions — so the indicator moves monotonically instead of+ * jumping. Defaults to the first item at the top and the last item at the+ * bottom so short final sections still activate.+ *+ * The activation line and the scroll landing are the same number, computed once+ * in `getRestingTop`: scroll-root top + `offset` (a fixed header overlaying the+ * root) + the heading's own `scroll-margin-top`. A heading therefore activates+ * exactly where navigating to it puts it. `offset` and `scroll-margin-top`+ * compose — the header, then the breathing room below it — they do not+ * duplicate each other.+ *+ * It also owns the single navigation path (`scrollTo`), shared by click and+ * keyboard activation: it announces the jump, suppresses scroll-spy for the+ * duration of the programmatic scroll (so the indicator doesn't chase it), and+ * resolves when the scroll settles — via `scrollend` where supported, or a+ * timeout fallback where it is not.+ *+ * The scroll root is the `scrollContainerRef` element when provided, otherwise+ * the nearest scrollable ancestor of the outline, otherwise the viewport.** SYNC: When modified, update /packages/core/src/Outline/Outline.tsx*/@@ -22,6 +37,14 @@import {useCallback, useEffect, useRef, useState} from 'react';import type {OutlineItem} from './types';+/**+ * How long to wait for a programmatic smooth scroll to settle when the+ * `scrollend` event never arrives — either because the browser does not+ * support it (Safari at time of writing) or because the target was already in+ * position, so no scroll happened at all and no events were emitted.+ */+const SCROLL_SETTLE_TIMEOUT_MS = 1200;+/** Keys that scroll the viewport — used to detect a manual scroll intent. */const SCROLL_KEYS = new Set(['ArrowUp',@@ -58,26 +81,82 @@ function getScrollableAncestor(return null;}+/** The element's own `scroll-margin-top` in px (0 when unset). */+function getScrollMarginTop(element: HTMLElement): number {+ return (+ Number.parseFloat(window.getComputedStyle(element).scrollMarginTop) || 0+ );+}++/** The top of the scroll root in viewport coordinates (0 for the viewport). */+function getRootTop(scrollRoot: HTMLElement | null): number {+ return scrollRoot != null ? scrollRoot.getBoundingClientRect().top : 0;+}++/**+ * Where a heading comes to rest, in viewport coordinates: below the fixed+ * header (`offset`) and below its own `scroll-margin-top` breathing room.+ *+ * This is the single source of truth shared by the activation line and the+ * scroll landing — the two must agree, or a heading activates somewhere other+ * than where navigating to it puts it.+ */+function getRestingTop(+ target: HTMLElement,+ scrollRoot: HTMLElement | null,+ offset: number,+): number {+ return getRootTop(scrollRoot) + offset + getScrollMarginTop(target);+}++/**+ * Bring `target` to rest at the top of the scroll root, below any fixed header.+ *+ * With no `offset`, this is the CSS-native path: `scrollIntoView` already+ * honors the heading's `scroll-margin-top`, and it walks *every* scrollable+ * ancestor, so the browser does it better than we can.+ *+ * An `offset` describes a fixed header overlaying the top of the scroll root —+ * which the browser cannot know about, so `scrollIntoView` would park the+ * heading underneath it, hidden. Compute the landing explicitly instead, from+ * the same {@link getRestingTop} the activation line uses.+ */+function scrollToTarget(+ target: HTMLElement,+ scrollRoot: HTMLElement | null,+ scrollTarget: HTMLElement | Window,+ offset: number,+): void {+ if (offset === 0) {+ target.scrollIntoView({behavior: 'smooth', block: 'start'});+ return;+ }++ const delta =+ target.getBoundingClientRect().top -+ getRestingTop(target, scrollRoot, offset);+ scrollTarget.scrollBy({top: delta, behavior: 'smooth'});+}+/*** Resolve the active heading id from current scroll position.*- * A heading is "passed" once its top reaches its activation line — the scroll- * root's top plus the heading's own scroll-margin-top. The active heading is- * the last passed one (headings are in document order). When none have passed- * (scrolled above the first), the first item is active; at the bottom, the- * last item is active.+ * A heading is "passed" once its top reaches its activation line — exactly+ * where navigating to it would land it ({@link getRestingTop}): the scroll+ * root's top, plus `offset` (a fixed header overlaying the scroll root), plus+ * the heading's own scroll-margin-top. The active heading is the last passed+ * one (headings are in document order). When none have passed (scrolled above+ * the first), the first item is active; at the bottom, the last item is active.*/function resolveActiveId(items: OutlineItem[],scrollRoot: HTMLElement | null,+ offset: number,): string | undefined {if (items.length === 0) {return undefined;}- const rootTop =- scrollRoot != null ? scrollRoot.getBoundingClientRect().top : 0;-const atBottom =scrollRoot != null? scrollRoot.scrollTop + scrollRoot.clientHeight >=@@ -94,11 +173,10 @@ function resolveActiveId(if (element == null) {continue;}- const top = element.getBoundingClientRect().top;- const marginTop =- Number.parseFloat(window.getComputedStyle(element).scrollMarginTop) || 0;- if (top <= rootTop + marginTop + 1) {+ // 1px of tolerance absorbs sub-pixel rounding after a scroll lands.+ const top = element.getBoundingClientRect().top;+ if (top <= getRestingTop(element, scrollRoot, offset) + 1) {activeId = item.id;} else {break;@@ -112,6 +190,20 @@ interface UseScrollSpyOptions {items: OutlineItem[];onActiveIdChange?: (id: string) => void;rootRef: React.RefObject<HTMLElement | null>;+ /**+ * Height in px of a fixed header overlaying the top of the scroll root.+ * Shifts both the activation line and the scroll landing by the same amount,+ * on top of each heading's own `scroll-margin-top`.+ */+ offset?: number;+ /** Scroll container to track, instead of the nearest scrollable ancestor. */+ scrollContainerRef?: React.RefObject<HTMLElement | null>;+ /** Whether {@link UseScrollSpyResult.scrollTo} performs the smooth scroll. */+ hasScrollOnClick?: boolean;+ /** Called when a navigation begins, before the scroll starts. */+ onNavigateStart?: (id: string) => void;+ /** Called once per navigation, when the scroll settles or is interrupted. */+ onNavigateEnd?: (id: string) => void;}interface UseScrollSpyResult {@@ -119,13 +211,19 @@ interface UseScrollSpyResult {/** Set the active id (notifies onActiveIdChange). For controlled consumers. */setActiveId: (id: string) => void;/**- * Handle a click on the outline item with id `id`. Delays moving the- * indicator: scroll-spy is suppressed during the programmatic smooth scroll- * so the indicator doesn't chase it, then the indicator moves once to the- * clicked item when the scroll settles. If the user scrolls manually mid-way,- * scroll-position tracking resumes immediately instead.+ * Navigate to the item with id `id` — the single path shared by click and+ * keyboard activation.+ *+ * Fires `onNavigateStart(id)`, scrolls (unless `hasScrollOnClick` is false),+ * and fires `onNavigateEnd(id)` exactly once when the scroll settles or the+ * user interrupts it. While uncontrolled, scroll-spy is suppressed for the+ * duration so the indicator doesn't chase the scroll through intervening+ * sections; it lands on the target once the scroll settles, or resumes+ * position tracking if the user scrolls away mid-flight.+ *+ * Returns false (and does nothing) when no element with `id` exists.*/- lockActiveId: (id: string) => void;+ scrollTo: (id: string) => boolean;}export function useScrollSpy({@@ -133,18 +231,29 @@ export function useScrollSpy({items,onActiveIdChange,rootRef,+ offset = 0,+ scrollContainerRef,+ hasScrollOnClick = true,+ onNavigateStart,+ onNavigateEnd,}: UseScrollSpyOptions): UseScrollSpyResult {const isControlled = activeId !== undefined;const [uncontrolledActiveId, setUncontrolledActiveId] = useState<string | undefined>(items[0]?.id);const activeIdRef = useRef<string | undefined>(activeId);- // While true, scroll-spy ignores scroll updates because a click is driving a- // programmatic scroll. Released when that scroll settles or the user scrolls.+ // While true, scroll-spy ignores scroll updates because a navigation is+ // driving a programmatic scroll. Released when it settles or the user scrolls.const suppressRef = useRef(false);- const releaseSuppressionRef = useRef<(() => void) | null>(null);- // Latest scroll-position resolver, so the click handler can resume tracking- // when the user scrolls during a programmatic scroll.+ // The navigation currently in flight, if any.+ const navigationRef = useRef<{+ /** End it (without resuming tracking) because a new one is starting. */+ supersede: () => void;+ /** Drop its listeners without firing onNavigateEnd (unmount). */+ teardown: () => void;+ } | null>(null);+ // Latest scroll-position resolver, so a navigation can resume tracking when+ // the user scrolls during the programmatic scroll.const syncRef = useRef<(() => void) | null>(null);// Keep latest items/callback in refs so the scroll listener effect doesn't// re-subscribe on every render (items is a fresh array each render).@@ -155,12 +264,23 @@ export function useScrollSpy({const itemIds = items.map(item => item.id).join('\n');activeIdRef.current = isControlled ? activeId : uncontrolledActiveId;+ /**+ * The element whose scroll position drives the outline: the explicit+ * container when scoped, else the nearest scrollable ancestor, else null+ * (meaning the viewport).+ */+ const getScrollRoot = useCallback((): HTMLElement | null => {+ return (+ scrollContainerRef?.current ?? getScrollableAncestor(rootRef.current)+ );+ }, [rootRef, scrollContainerRef]);+useEffect(() => {if (isControlled || typeof window === 'undefined') {return;}- const scrollRoot = getScrollableAncestor(rootRef.current);+ const scrollRoot = getScrollRoot();const scrollTarget: HTMLElement | Window = scrollRoot ?? window;let frame = 0;@@ -169,7 +289,11 @@ export function useScrollSpy({if (suppressRef.current) {return;}- const nextActiveId = resolveActiveId(itemsRef.current, scrollRoot);+ const nextActiveId = resolveActiveId(+ itemsRef.current,+ scrollRoot,+ offset,+ );if (nextActiveId != null && nextActiveId !== activeIdRef.current) {activeIdRef.current = nextActiveId;setUncontrolledActiveId(nextActiveId);@@ -195,12 +319,12 @@ export function useScrollSpy({cancelAnimationFrame(frame);}};- }, [isControlled, itemIds, rootRef]);+ }, [isControlled, itemIds, offset, getScrollRoot]);- // Tear down any pending suppression listeners when the Outline unmounts.+ // Tear down any in-flight navigation's listeners when the Outline unmounts.useEffect(() => {return () => {- releaseSuppressionRef.current?.();+ navigationRef.current?.teardown();};}, []);@@ -211,65 +335,117 @@ export function useScrollSpy({onActiveIdChange?.(nextActiveId);};- const lockActiveId = useCallback((clickedId: string) => {- if (typeof window === 'undefined') {- setUncontrolledActiveId(clickedId);- activeIdRef.current = clickedId;- onActiveIdChangeRef.current?.(clickedId);- return;+ // Defined in render (not memoized) so it always closes over the current props+ // — it only ever runs from an event handler, never during render.+ const scrollTo = (id: string): boolean => {+ const target =+ typeof document !== 'undefined' ? document.getElementById(id) : null;+ if (target == null) {+ return false;+ }++ // A second navigation replaces the first: end the old one (balancing its+ // onNavigateStart) without resuming tracking, since we are about to+ // suppress it again anyway.+ navigationRef.current?.supersede();++ onNavigateStart?.(id);++ if (isControlled) {+ // The consumer owns the active state — notify only.+ setActiveId(id);+ } else {+ // Freeze the indicator during the programmatic scroll instead of moving+ // it immediately: it lands on the target once the scroll settles, so it+ // doesn't chase the scroll through intervening sections.+ suppressRef.current = true;}- // Freeze the indicator during the programmatic smooth scroll instead of- // moving it immediately — it lands on the clicked item once the scroll- // settles, so it doesn't chase the scroll through intervening sections.- suppressRef.current = true;- // Replace any in-flight handlers from a previous click.- releaseSuppressionRef.current?.();+ const scrollRoot = getScrollRoot();+ const scrollTarget: HTMLElement | Window = scrollRoot ?? window;let settleTimer = 0;+ let isSettled = false;+const cleanup = () => {- window.removeEventListener('scrollend', onSettle);- window.removeEventListener('wheel', onManual);- window.removeEventListener('touchmove', onManual);+ scrollTarget.removeEventListener('scrollend', onSettle);+ scrollTarget.removeEventListener('wheel', onManual);+ scrollTarget.removeEventListener('touchmove', onManual);window.removeEventListener('keydown', onKeyDown);if (settleTimer !== 0) {clearTimeout(settleTimer);settleTimer = 0;}- releaseSuppressionRef.current = null;+ navigationRef.current = null;};- // Programmatic scroll finished: move the indicator to the clicked item.- const onSettle = () => {- cleanup();- suppressRef.current = false;- setUncontrolledActiveId(clickedId);- activeIdRef.current = clickedId;- onActiveIdChangeRef.current?.(clickedId);- };- // User scrolled mid-flight: hand control back to scroll-position tracking.- const onManual = () => {++ /**+ * End the navigation exactly once. `didArrive` is false when the user took+ * over with a manual scroll mid-flight. `onNavigateEnd` fires either way,+ * so every `onNavigateStart` is balanced and a consumer's "navigating"+ * state can never leak.+ */+ const finish = (didArrive: boolean, shouldResume = true) => {+ if (isSettled) {+ return;+ }+ isSettled = true;cleanup();- suppressRef.current = false;- syncRef.current?.();++ if (!isControlled) {+ suppressRef.current = false;+ if (didArrive) {+ setUncontrolledActiveId(id);+ activeIdRef.current = id;+ onActiveIdChangeRef.current?.(id);+ } else if (shouldResume) {+ // Hand control back to scroll-position tracking.+ syncRef.current?.();+ }+ }++ onNavigateEnd?.(id);};++ const onSettle = () => finish(true);+ const onManual = () => finish(false);const onKeyDown = (event: KeyboardEvent) => {- if (SCROLL_KEYS.has(event.key)) {- onManual();+ // A key the outline itself consumed (arrow roving focus, Space+ // activation) is prevented, so the browser will not scroll — it is not a+ // manual scroll intent and must not cancel the navigation it just began.+ if (!event.defaultPrevented && SCROLL_KEYS.has(event.key)) {+ finish(false);}};- window.addEventListener('scrollend', onSettle, {once: true});- window.addEventListener('wheel', onManual, {passive: true});- window.addEventListener('touchmove', onManual, {passive: true});- window.addEventListener('keydown', onKeyDown);- // Fallback when scrollend is unsupported or no scroll is needed.- settleTimer = window.setTimeout(onSettle, 1200);- releaseSuppressionRef.current = cleanup;- }, []);+ if (hasScrollOnClick) {+ // Arm settle detection *before* scrolling so an instant jump (a target+ // already in position, or prefers-reduced-motion collapsing the smooth+ // scroll) cannot land before anyone is listening.+ scrollTarget.addEventListener('scrollend', onSettle, {once: true});+ scrollTarget.addEventListener('wheel', onManual, {passive: true});+ scrollTarget.addEventListener('touchmove', onManual, {passive: true});+ window.addEventListener('keydown', onKeyDown);+ settleTimer = window.setTimeout(onSettle, SCROLL_SETTLE_TIMEOUT_MS);+ navigationRef.current = {+ supersede: () => finish(false, false),+ teardown: cleanup,+ };+ scrollToTarget(target, scrollRoot, scrollTarget, offset);+ } else {+ // The consumer owns scrolling — there is no scroll to wait for, so the+ // navigation is already at rest. Resolving immediately (instead of+ // waiting on the settle timeout) keeps onNavigateEnd usable for arrival+ // effects even when hasScrollOnClick is false.+ finish(true);+ }++ return true;+ };return {activeId: isControlled ? activeId : uncontrolledActiveId,setActiveId,- lockActiveId,+ scrollTo,};}