Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

add XDSOutline component (#2347)

Andrey Goder482c1728bf4c
diff --git a/apps/storybook/stories/Outline.stories.tsx b/apps/storybook/stories/Outline.stories.tsx
new file mode 100644
index 0000000000..068a37a31c
--- /dev/null
+++ b/apps/storybook/stories/Outline.stories.tsx
@@ -0,0 +1,251 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useRef, type ReactNode} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ XDSOutline,
+ useOutlineFromDOM,
+ useOutlineFromMarkdown,
+} from '@xds/core/Outline';
+import type {OutlineItem} from '@xds/core/Outline';
+import {XDSBadge} from '@xds/core/Badge';
+import {XDSMarkdown} from '@xds/core/Markdown';
+import {XDSHeading, XDSText} from '@xds/core/Text';
+
+const meta: Meta<typeof XDSOutline> = {
+ title: 'Core/Outline',
+ component: XDSOutline,
+ tags: ['autodocs'],
+ argTypes: {
+ label: {
+ control: 'text',
+ description: 'Accessible label for the nav landmark',
+ },
+ activeId: {
+ control: 'text',
+ description: 'Controlled active item id',
+ },
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof XDSOutline>;
+
+const outlineItems: OutlineItem[] = [
+ {id: 'overview', label: 'Overview', level: 2},
+ {id: 'installation', label: 'Installation', level: 2},
+ {id: 'theming', label: 'Theming', level: 2},
+ {id: 'tokens', label: 'Tokens', level: 3},
+ {id: 'component-overrides', label: 'Component overrides', level: 3},
+ {id: 'accessibility', label: 'Accessibility', level: 2},
+];
+
+const markdownContent = [
+ '## Overview',
+ '',
+ 'XDS gives teams a consistent foundation for internal product surfaces.',
+ '',
+ '## Installation',
+ '',
+ 'Install the package and wrap the app in an XDSTheme provider.',
+ '',
+ '### Package setup',
+ '',
+ 'Import components from their component subpaths for clear ownership.',
+ '',
+ '### Theme setup',
+ '',
+ 'Use a built theme in production so component overrides are present at first paint.',
+ '',
+ '## Accessibility',
+ '',
+ 'Components include semantic roles, labels, and focus behavior where applicable.',
+].join('\n');
+
+function nodeText(node: ReactNode): string {
+ if (typeof node === 'string' || typeof node === 'number') {
+ return String(node);
+ }
+ if (Array.isArray(node)) {
+ return node.map(nodeText).join('');
+ }
+ return '';
+}
+
+function storySlug(value: string): string {
+ return (
+ value
+ .trim()
+ .toLowerCase()
+ .replace(/['"]/g, '')
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '') || 'section'
+ );
+}
+
+export const Basic: Story = {
+ args: {
+ items: outlineItems,
+ },
+};
+
+export const Controlled: Story = {
+ args: {
+ items: outlineItems,
+ activeId: 'tokens',
+ },
+};
+
+export const WithDocument: Story = {
+ render: () => (
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: 'minmax(0, 1fr) 220px',
+ gap: 32,
+ maxWidth: 960,
+ }}>
+ <article style={{display: 'grid', gap: 24}}>
+ <section>
+ <h2 id="overview">Overview</h2>
+ <p>
+ XDS components provide consistent interaction, styling, and theme
+ behavior for internal tools.
+ </p>
+ </section>
+ <section>
+ <h2 id="installation">Installation</h2>
+ <p>
+ Install the package, wrap the app with XDSTheme, and import
+ components from their subpaths.
+ </p>
+ </section>
+ <section>
+ <h2 id="theming">Theming</h2>
+ <p>
+ Themes define semantic tokens and component overrides without
+ changing app code.
+ </p>
+ <h3 id="tokens">Tokens</h3>
+ <p>
+ Use semantic color, spacing, typography, radius, elevation, and
+ motion tokens.
+ </p>
+ <h3 id="component-overrides">Component overrides</h3>
+ <p>
+ Component overrides target stable xds-* class names emitted by each
+ component.
+ </p>
+ </section>
+ <section>
+ <h2 id="accessibility">Accessibility</h2>
+ <p>
+ Components include landmark, keyboard, focus, and ARIA behavior
+ where applicable.
+ </p>
+ </section>
+ </article>
+ <aside style={{position: 'sticky', top: 24, alignSelf: 'start'}}>
+ <XDSOutline items={outlineItems} />
+ </aside>
+ </div>
+ ),
+};
+
+export const ExtractFromMarkdown: Story = {
+ render: () => {
+ const items = useOutlineFromMarkdown(markdownContent);
+
+ return (
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: 'minmax(0, 1fr) 220px',
+ gap: 32,
+ maxWidth: 960,
+ }}>
+ <XDSMarkdown
+ components={{
+ heading: ({level, children}) => {
+ const Tag = `h${level}` as
+ | 'h1'
+ | 'h2'
+ | 'h3'
+ | 'h4'
+ | 'h5'
+ | 'h6';
+ return <Tag id={storySlug(nodeText(children))}>{children}</Tag>;
+ },
+ }}>
+ {markdownContent}
+ </XDSMarkdown>
+ <aside style={{position: 'sticky', top: 24, alignSelf: 'start'}}>
+ <XDSOutline items={items} />
+ </aside>
+ </div>
+ );
+ },
+};
+
+export const ExtractFromHTML: Story = {
+ render: () => {
+ const contentRef = useRef<HTMLElement | null>(null);
+ const items = useOutlineFromDOM(contentRef);
+
+ return (
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: 'minmax(0, 1fr) 220px',
+ gap: 32,
+ maxWidth: 960,
+ }}>
+ <article ref={contentRef} style={{display: 'grid', gap: 24}}>
+ <section>
+ <XDSHeading id="account-settings" level={2}>
+ Account settings
+ </XDSHeading>
+ <XDSText type="body">
+ Manage profile, authentication, and workspace preferences.
+ </XDSText>
+ <div style={{display: 'flex', gap: 8, marginTop: 12}}>
+ <XDSBadge variant="success" label="Active" />
+ <XDSBadge variant="neutral" label="Workspace" />
+ </div>
+ </section>
+ <section>
+ <XDSHeading id="notifications" level={2}>
+ Notifications
+ </XDSHeading>
+ <XDSText type="body">
+ Choose which product events should notify the team.
+ </XDSText>
+ <XDSHeading id="email-alerts" level={3}>
+ Email alerts
+ </XDSHeading>
+ <XDSText type="body">
+ Use email for low-frequency summaries and approvals.
+ </XDSText>
+ <XDSHeading id="push-alerts" level={3}>
+ Push alerts
+ </XDSHeading>
+ <XDSText type="body">
+ Use push for time-sensitive updates and incidents.
+ </XDSText>
+ </section>
+ <section>
+ <XDSHeading id="billing" level={2}>
+ Billing
+ </XDSHeading>
+ <XDSText type="body">
+ Review invoices, payment methods, and usage limits.
+ </XDSText>
+ </section>
+ </article>
+ <aside style={{position: 'sticky', top: 24, alignSelf: 'start'}}>
+ <XDSOutline items={items} />
+ </aside>
+ </div>
+ );
+ },
+};
diff --git a/packages/core/package.json b/packages/core/package.json
index a14387139b..9acd3c5a16 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -391,6 +391,12 @@
"import": "./dist/NumberInput/index.mjs",
"require": "./dist/NumberInput/index.js"
},
+ "./Outline": {
+ "source": "./src/Outline/index.ts",
+ "types": "./dist/Outline/index.d.ts",
+ "import": "./dist/Outline/index.mjs",
+ "require": "./dist/Outline/index.js"
+ },
"./OverflowList": {
"source": "./src/OverflowList/index.ts",
"types": "./dist/OverflowList/index.d.ts",
diff --git a/packages/core/src/Outline/Outline.doc.mjs b/packages/core/src/Outline/Outline.doc.mjs
new file mode 100644
index 0000000000..f904d5c4eb
--- /dev/null
+++ b/packages/core/src/Outline/Outline.doc.mjs
@@ -0,0 +1,183 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../docs-types').ComponentDoc} */
+
+export const docs = {
+ name: 'Outline',
+ group: 'Outline',
+ keywords: [
+ 'outline',
+ 'table of contents',
+ 'toc',
+ 'heading navigation',
+ 'scroll spy',
+ 'documentation',
+ 'anchors',
+ ],
+ playground: {
+ defaults: {
+ items: [
+ {id: 'overview', label: 'Overview', level: 2},
+ {id: 'installation', label: 'Installation', level: 2},
+ {id: 'configuration', label: 'Configuration', level: 3},
+ {id: 'api-reference', label: 'API reference', level: 2},
+ ],
+ },
+ },
+ theming: {
+ targets: [
+ {className: 'xds-outline'},
+ {className: 'xds-outline-item', visualProps: ['level'], states: ['active']},
+ ],
+ },
+ components: [
+ {
+ name: 'XDSOutline',
+ description:
+ 'Document outline navigation. Renders a flat heading list as anchor links and manages scroll-spy active state when uncontrolled.',
+ props: [
+ {
+ name: 'items',
+ type: 'OutlineItem[]',
+ description:
+ 'Ordered heading items. Each item has id, label, and level. The id should match the target heading element id.',
+ required: true,
+ },
+ {
+ name: 'activeId',
+ type: 'string',
+ description:
+ 'Currently active heading id. Providing this prop makes active state controlled and disables built-in scroll-spy.',
+ },
+ {
+ name: 'onActiveIdChange',
+ type: '(id: string) => void',
+ description:
+ 'Called when the active item changes from built-in scroll-spy or from an outline link click.',
+ },
+ {
+ name: 'label',
+ type: 'string',
+ description: 'Accessible label for the nav landmark.',
+ default: "'Table of contents'",
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description:
+ 'StyleX styles for layout customization. Must be a stylex.create() value.',
+ },
+ ],
+ },
+ ],
+ 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.',
+ 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 useOutlineFromMarkdown or useOutlineFromDOM when headings are generated from content.'},
+ {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.'},
+ ],
+ },
+};
+
+/** @type {import('../docs-types').ComponentDoc} */
+export const docsZh = {
+ name: 'Outline',
+ group: 'Outline',
+ theming: {
+ targets: [
+ {className: 'xds-outline'},
+ {className: 'xds-outline-item', visualProps: ['level'], states: ['active']},
+ ],
+ },
+ components: [
+ {
+ name: 'XDSOutline',
+ description:
+ '文档大纲导航。将扁平标题列表渲染为锚点链接,并在非受控模式下管理滚动监听的激活状态。',
+ props: [
+ {
+ name: 'items',
+ type: 'OutlineItem[]',
+ description:
+ '有序标题项。每项包含 id、label 和 level。id 应匹配目标标题元素的 id。',
+ required: true,
+ },
+ {
+ name: 'activeId',
+ type: 'string',
+ description:
+ '当前激活的标题 id。提供后组件进入受控模式,并禁用内置滚动监听。',
+ },
+ {
+ name: 'onActiveIdChange',
+ type: '(id: string) => void',
+ description: '当内置滚动监听或点击大纲链接改变激活项时调用。',
+ },
+ {
+ name: 'label',
+ type: 'string',
+ description: 'nav 地标的无障碍标签。',
+ default: "'Table of contents'",
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description: '用于布局自定义的 StyleX 样式。必须是 stylex.create() 值。',
+ },
+ ],
+ },
+ ],
+ 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.',
+ 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 useOutlineFromMarkdown or useOutlineFromDOM when headings are generated from content.'},
+ {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.'},
+ ],
+ },
+};
+
+/** @type {import('../docs-types').TranslationDoc} */
+export const docsDense = {
+ description:
+ 'Document outline/table-of-contents nav for same-page headings. Flat items array {id,label,level}; anchor links; uncontrolled scroll-spy via IntersectionObserver; controlled with activeId.',
+ 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.',
+ 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 useOutlineFromMarkdown or useOutlineFromDOM when headings are generated from content.'},
+ {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.'},
+ ],
+ },
+ 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'.",
+ xstyle: 'StyleX styles for layout. Must be stylex.create() value.',
+ },
+ components: [
+ {
+ name: 'XDSOutline',
+ description:
+ 'Document outline nav. Renders heading anchors and manages 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'.",
+ xstyle: 'StyleX styles for layout. Must be stylex.create() value.',
+ },
+ },
+ ],
+};
diff --git a/packages/core/src/Outline/XDSOutline.test.tsx b/packages/core/src/Outline/XDSOutline.test.tsx
new file mode 100644
index 0000000000..edf9bd7354
--- /dev/null
+++ b/packages/core/src/Outline/XDSOutline.test.tsx
@@ -0,0 +1,205 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file XDSOutline.test.tsx
+ * @input Uses vitest, @testing-library/react, XDSOutline, outline hooks/utils
+ * @output Unit tests for Outline rendering, scroll-spy behavior, and extraction helpers
+ * @position Testing; validates Outline implementation
+ *
+ * SYNC: When modified, update this header
+ */
+
+import {useRef, useState} from 'react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {act, render, screen, waitFor} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {XDSOutline} from './XDSOutline';
+import {parseOutlineFromMarkdown} from './parseOutlineFromMarkdown';
+import {useOutlineFromDOM} from './useOutlineFromDOM';
+import type {OutlineItem} from './types';
+
+const items: OutlineItem[] = [
+ {id: 'intro', label: 'Introduction', level: 2},
+ {id: 'install', label: 'Installation', level: 3},
+ {id: 'api', label: 'API', level: 3},
+];
+
+describe('parseOutlineFromMarkdown', () => {
+ it('extracts headings with generated ids', () => {
+ expect(parseOutlineFromMarkdown('# Intro\n\n## Getting Started')).toEqual([
+ {id: 'intro', label: 'Intro', level: 1},
+ {id: 'getting-started', label: 'Getting Started', level: 2},
+ ]);
+ });
+
+ it('uses rendered inline text and ignores fenced code headings', () => {
+ expect(
+ parseOutlineFromMarkdown(
+ '## **Install** `@xds/core`\n\n```\n# Not a heading\n```',
+ ),
+ ).toEqual([{id: 'install-xds-core', label: 'Install @xds/core', level: 2}]);
+ });
+
+ it('deduplicates generated ids', () => {
+ expect(parseOutlineFromMarkdown('## Usage\n## Usage\n## Usage')).toEqual([
+ {id: 'usage', label: 'Usage', level: 2},
+ {id: 'usage-1', label: 'Usage', level: 2},
+ {id: 'usage-2', label: 'Usage', level: 2},
+ ]);
+ });
+});
+
+describe('XDSOutline', () => {
+ beforeEach(() => {
+ Element.prototype.scrollIntoView = vi.fn();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('renders a labelled nav with anchor links', () => {
+ render(<XDSOutline items={items} label="On this page" />);
+ expect(
+ screen.getByRole('navigation', {name: 'On this page'}),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('link', {name: 'Introduction'})).toHaveAttribute(
+ 'href',
+ '#intro',
+ );
+ });
+
+ it('uses the default accessible label', () => {
+ render(<XDSOutline items={items} />);
+ expect(
+ screen.getByRole('navigation', {name: 'Table of contents'}),
+ ).toBeInTheDocument();
+ });
+
+ it('marks the controlled active item with aria-current', () => {
+ render(<XDSOutline items={items} activeId="install" />);
+ expect(screen.getByRole('link', {name: 'Installation'})).toHaveAttribute(
+ 'aria-current',
+ 'true',
+ );
+ expect(
+ screen.getByRole('link', {name: 'Introduction'}),
+ ).not.toHaveAttribute('aria-current');
+ });
+
+ it('smooth-scrolls and reports active id on click', async () => {
+ const user = userEvent.setup();
+ const target = document.createElement('h2');
+ target.id = 'install';
+ document.body.appendChild(target);
+ const onActiveIdChange = vi.fn();
+
+ render(<XDSOutline items={items} onActiveIdChange={onActiveIdChange} />);
+ await user.click(screen.getByRole('link', {name: 'Installation'}));
+
+ expect(target.scrollIntoView).toHaveBeenCalledWith({
+ behavior: 'smooth',
+ block: 'start',
+ });
+ expect(onActiveIdChange).toHaveBeenCalledWith('install');
+ });
+
+ it('applies stable root and item class names', () => {
+ render(<XDSOutline items={items} data-testid="outline" activeId="api" />);
+ expect(screen.getByTestId('outline').className).toContain('xds-outline');
+ expect(screen.getByRole('link', {name: 'API'}).className).toContain(
+ 'xds-outline-item',
+ );
+ expect(screen.getByRole('link', {name: 'API'}).className).toContain(
+ 'active',
+ );
+ expect(screen.getByRole('link', {name: 'API'}).className).toContain(
+ 'level-3',
+ );
+ });
+
+ it('updates uncontrolled active id from IntersectionObserver', () => {
+ let observerCallback: IntersectionObserverCallback | undefined;
+
+ class MockIntersectionObserver {
+ observe = vi.fn();
+ disconnect = vi.fn();
+
+ constructor(callback: IntersectionObserverCallback) {
+ observerCallback = callback;
+ }
+ }
+
+ vi.stubGlobal('IntersectionObserver', MockIntersectionObserver);
+
+ const intro = document.createElement('h2');
+ intro.id = 'intro';
+ const api = document.createElement('h3');
+ api.id = 'api';
+ document.body.append(intro, api);
+
+ const onActiveIdChange = vi.fn();
+ render(<XDSOutline items={items} onActiveIdChange={onActiveIdChange} />);
+
+ const entry: IntersectionObserverEntry = {
+ target: api,
+ isIntersecting: true,
+ boundingClientRect: {top: 12} as DOMRectReadOnly,
+ intersectionRatio: 1,
+ intersectionRect: {} as DOMRectReadOnly,
+ rootBounds: null,
+ time: 0,
+ };
+
+ act(() => {
+ observerCallback?.([entry], {} as IntersectionObserver);
+ });
+
+ expect(screen.getByRole('link', {name: 'API'})).toHaveAttribute(
+ 'aria-current',
+ 'true',
+ );
+ expect(onActiveIdChange).toHaveBeenCalledWith('api');
+ });
+});
+
+describe('useOutlineFromDOM', () => {
+ it('collects headings and updates after mutations', async () => {
+ const user = userEvent.setup();
+
+ function Demo() {
+ const ref = useRef<HTMLElement | null>(null);
+ const [showDetails, setShowDetails] = useState(false);
+ const outlineItems = useOutlineFromDOM(ref);
+
+ return (
+ <>
+ <button type="button" onClick={() => setShowDetails(true)}>
+ Show
+ </button>
+ <article ref={ref}>
+ <h2 id="intro">Intro</h2>
+ {showDetails ? <h3 id="details">Details</h3> : null}
+ </article>
+ <output>
+ {outlineItems
+ .map(item => `${item.level}:${item.id}:${item.label}`)
+ .join('|')}
+ </output>
+ </>
+ );
+ }
+
+ render(<Demo />);
+ await waitFor(() => {
+ expect(screen.getByText('2:intro:Intro')).toBeInTheDocument();
+ });
+
+ await user.click(screen.getByRole('button', {name: 'Show'}));
+ await waitFor(() => {
+ expect(
+ screen.getByText('2:intro:Intro|3:details:Details'),
+ ).toBeInTheDocument();
+ });
+ });
+});
diff --git a/packages/core/src/Outline/XDSOutline.tsx b/packages/core/src/Outline/XDSOutline.tsx
new file mode 100644
index 0000000000..5e5d78c47a
--- /dev/null
+++ b/packages/core/src/Outline/XDSOutline.tsx
@@ -0,0 +1,226 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file XDSOutline.tsx
+ * @input Uses React, StyleX, XDS link provider integration, Outline hooks/types
+ * @output Exports XDSOutline component and XDSOutlineProps type
+ * @position Core implementation; consumed by index.ts
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Outline/Outline.doc.mjs
+ * - /packages/core/src/Outline/index.ts
+ * - /apps/storybook/stories/Outline.stories.tsx
+ */
+
+import {useRef} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ durationVars,
+ easeVars,
+ radiusVars,
+ spacingVars,
+ typeScaleVars,
+ fontWeightVars,
+} from '../theme/tokens.stylex';
+import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';
+import {mergeProps, mergeRefs, xdsClassName} from '../utils';
+import type {XDSBaseProps} from '../XDSBaseProps';
+import {useScrollSpy} from './useScrollSpy';
+import type {OutlineItem} from './types';
+
+export type {OutlineItem} from './types';
+
+export interface XDSOutlineProps extends XDSBaseProps<HTMLElement> {
+ /** Ref forwarded to the root nav element. */
+ ref?: React.Ref<HTMLElement>;
+
+ /** Ordered list of heading items to render. */
+ items: OutlineItem[];
+
+ /** ID of the currently active item. When provided, disables built-in scroll-spy. */
+ activeId?: string;
+
+ /** Called when the active item changes from scroll-spy or click. */
+ onActiveIdChange?: (id: string) => void;
+
+ /** Accessible label for the nav landmark. @default 'Table of contents' */
+ label?: string;
+
+ /** Test ID for testing frameworks. */
+ 'data-testid'?: string;
+}
+
+const styles = stylex.create({
+ root: {
+ color: colorVars['--color-text-secondary'],
+ fontSize: typeScaleVars['--text-supporting-size'],
+ lineHeight: typeScaleVars['--text-supporting-leading'],
+ width: '100%',
+ },
+ list: {
+ listStyleType: 'none',
+ margin: 0,
+ padding: 0,
+ },
+ item: {
+ listStyleType: 'none',
+ margin: 0,
+ padding: 0,
+ },
+ link: {
+ alignItems: 'center',
+ borderRadius: radiusVars['--radius-inner'],
+ boxSizing: 'border-box',
+ color: 'inherit',
+ cursor: 'pointer',
+ display: 'flex',
+ minHeight: spacingVars['--spacing-7'],
+ outline: 'none',
+ paddingBlock: spacingVars['--spacing-1'],
+ paddingInlineEnd: spacingVars['--spacing-2'],
+ position: 'relative',
+ textAlign: 'start',
+ textDecoration: 'none',
+ transitionDuration: durationVars['--duration-fast'],
+ transitionProperty: 'background-color, color',
+ transitionTimingFunction: easeVars['--ease-standard'],
+ width: '100%',
+ ':hover': {
+ '@media (hover: hover)': {
+ backgroundColor: colorVars['--color-overlay-hover'],
+ color: colorVars['--color-text-primary'],
+ },
+ },
+ ':active': {
+ backgroundColor: colorVars['--color-overlay-pressed'],
+ },
+ ':focus-visible': {
+ outline: `2px solid ${colorVars['--color-accent']}`,
+ outlineOffset: 2,
+ },
+ },
+ activeLink: {
+ color: colorVars['--color-text-accent'],
+ fontWeight: fontWeightVars['--font-weight-medium'],
+ },
+ activeIndicator: {
+ '::before': {
+ backgroundColor: colorVars['--color-accent'],
+ borderRadius: radiusVars['--radius-full'],
+ bottom: spacingVars['--spacing-1'],
+ content: '""',
+ insetInlineStart: 0,
+ position: 'absolute',
+ top: spacingVars['--spacing-1'],
+ width: 2,
+ },
+ },
+ label: {
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
+
+const dynamicStyles = stylex.create({
+ levelIndent: (level: number) => ({
+ paddingInlineStart: `calc(${Math.max(0, Math.min(5, level - 1))} * ${spacingVars['--spacing-4']} + ${spacingVars['--spacing-2']})`,
+ }),
+});
+
+/**
+ * A table-of-contents navigation component for document headings.
+ *
+ * XDSOutline accepts a flat `items` array and renders anchor links with
+ * indentation based on each heading level. When `activeId` is omitted, it
+ * observes heading elements by id and marks the topmost visible heading active.
+ */
+export function XDSOutline({
+ items,
+ activeId,
+ onActiveIdChange,
+ label = 'Table of contents',
+ xstyle,
+ className,
+ style,
+ ref,
+ 'data-testid': testId,
+ ...props
+}: XDSOutlineProps) {
+ const rootRef = useRef<HTMLElement | null>(null);
+ const LinkComponent = useXDSLinkComponent();
+ const [resolvedActiveId, setActiveId] = useScrollSpy({
+ activeId,
+ items,
+ onActiveIdChange,
+ rootRef,
+ });
+
+ const handleClick =
+ (id: string) => (event: React.MouseEvent<HTMLElement>) => {
+ const target = document.getElementById(id);
+ setActiveId(id);
+
+ if (
+ target == null ||
+ event.defaultPrevented ||
+ event.metaKey ||
+ event.altKey ||
+ event.ctrlKey ||
+ event.shiftKey
+ ) {
+ return;
+ }
+
+ event.preventDefault();
+ window.history.pushState(null, '', `#${id}`);
+ target.scrollIntoView({behavior: 'smooth', block: 'start'});
+ };
+
+ return (
+ <nav
+ {...props}
+ ref={mergeRefs(rootRef, ref)}
+ aria-label={label}
+ data-testid={testId}
+ {...mergeProps(
+ xdsClassName('outline'),
+ stylex.props(styles.root, xstyle),
+ className,
+ style,
+ )}>
+ <ul {...stylex.props(styles.list)}>
+ {items.map(item => {
+ const isActive = item.id === resolvedActiveId;
+ return (
+ <li key={item.id} {...stylex.props(styles.item)}>
+ <LinkComponent
+ href={`#${item.id}`}
+ aria-current={isActive ? 'true' : undefined}
+ onClick={handleClick(item.id)}
+ {...mergeProps(
+ xdsClassName('outline-item', {
+ active: isActive ? 'active' : null,
+ level: item.level,
+ }),
+ stylex.props(
+ styles.link,
+ dynamicStyles.levelIndent(item.level),
+ isActive && styles.activeLink,
+ isActive && styles.activeIndicator,
+ ),
+ )}>
+ <span {...stylex.props(styles.label)}>{item.label}</span>
+ </LinkComponent>
+ </li>
+ );
+ })}
+ </ul>
+ </nav>
+ );
+}
+
+XDSOutline.displayName = 'XDSOutline';
diff --git a/packages/core/src/Outline/index.ts b/packages/core/src/Outline/index.ts
new file mode 100644
index 0000000000..eb2efb451f
--- /dev/null
+++ b/packages/core/src/Outline/index.ts
@@ -0,0 +1,19 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file index.ts
+ * @input Imports XDSOutline, outline hooks, parser utility, and types
+ * @output Exports XDSOutline component, OutlineItem type, and outline helpers
+ * @position Component entry point for Outline
+ *
+ * SYNC: When modified, update /packages/core/src/Outline/Outline.doc.mjs
+ */
+
+export {XDSOutline} from './XDSOutline';
+export type {XDSOutlineProps} from './XDSOutline';
+export type {OutlineItem} from './types';
+export {parseOutlineFromMarkdown} from './parseOutlineFromMarkdown';
+export {useOutlineFromMarkdown} from './useOutlineFromMarkdown';
+export {useOutlineFromDOM} from './useOutlineFromDOM';
diff --git a/packages/core/src/Outline/parseOutlineFromMarkdown.ts b/packages/core/src/Outline/parseOutlineFromMarkdown.ts
new file mode 100644
index 0000000000..7b45c04430
--- /dev/null
+++ b/packages/core/src/Outline/parseOutlineFromMarkdown.ts
@@ -0,0 +1,73 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file parseOutlineFromMarkdown.ts
+ * @input Uses Markdown parser internals and OutlineItem type
+ * @output Exports parseOutlineFromMarkdown for extracting heading outlines from Markdown
+ * @position Pure utility; consumed by useOutlineFromMarkdown and public exports
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Outline/Outline.doc.mjs
+ * - /packages/core/src/Outline/index.ts
+ */
+
+import {parseMarkdown, type InlineNode} from '../Markdown/parser';
+import type {OutlineItem} from './types';
+
+function inlineText(nodes: InlineNode[]): string {
+ return nodes
+ .map(node => {
+ switch (node.type) {
+ case 'text':
+ case 'code':
+ return node.content;
+ case 'bold':
+ case 'italic':
+ case 'strikethrough':
+ case 'link':
+ return inlineText(node.children);
+ case 'image':
+ return node.alt;
+ case 'citation':
+ case 'break':
+ return '';
+ }
+ })
+ .join('');
+}
+
+function slugify(value: string): string {
+ return value
+ .trim()
+ .toLowerCase()
+ .replace(/['"]/g, '')
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '');
+}
+
+function uniqueSlug(baseSlug: string, counts: Map<string, number>): string {
+ const fallbackSlug = baseSlug || 'section';
+ const count = counts.get(fallbackSlug) ?? 0;
+ counts.set(fallbackSlug, count + 1);
+ return count === 0 ? fallbackSlug : `${fallbackSlug}-${count}`;
+}
+
+/**
+ * Extract heading items from a Markdown string.
+ *
+ * Uses XDSMarkdown's parser so fenced code blocks, tables, lists, and inline
+ * formatting are interpreted consistently with rendered Markdown output.
+ */
+export function parseOutlineFromMarkdown(markdown: string): OutlineItem[] {
+ const counts = new Map<string, number>();
+ return parseMarkdown(markdown)
+ .filter(block => block.type === 'heading')
+ .map(block => {
+ const label = inlineText(block.children).trim();
+ return {
+ id: uniqueSlug(slugify(label), counts),
+ label,
+ level: block.level,
+ };
+ });
+}
diff --git a/packages/core/src/Outline/types.ts b/packages/core/src/Outline/types.ts
new file mode 100644
index 0000000000..94c29e0a24
--- /dev/null
+++ b/packages/core/src/Outline/types.ts
@@ -0,0 +1,21 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file types.ts
+ * @input None
+ * @output Exports OutlineItem type
+ * @position Shared type definitions; consumed by XDSOutline, hooks, and parser utils
+ *
+ * SYNC: When modified, update /packages/core/src/Outline/Outline.doc.mjs
+ */
+
+export interface OutlineItem {
+ /** Unique ID, typically matching the target heading's DOM id. */
+ id: string;
+
+ /** Display text for the outline item. */
+ label: string;
+
+ /** Heading depth from 1 to 6. Controls indentation. */
+ level: number;
+}
diff --git a/packages/core/src/Outline/useOutlineFromDOM.ts b/packages/core/src/Outline/useOutlineFromDOM.ts
new file mode 100644
index 0000000000..1b24c8cad7
--- /dev/null
+++ b/packages/core/src/Outline/useOutlineFromDOM.ts
@@ -0,0 +1,70 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useOutlineFromDOM.ts
+ * @input Uses React, DOM heading queries, MutationObserver
+ * @output Exports useOutlineFromDOM hook
+ * @position Hook utility; consumed by applications and Outline examples
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Outline/Outline.doc.mjs
+ * - /packages/core/src/Outline/index.ts
+ */
+
+import {useEffect, useState} from 'react';
+import type {OutlineItem} from './types';
+
+function collectOutlineItems(container: HTMLElement | null): OutlineItem[] {
+ if (container == null) {
+ return [];
+ }
+
+ return Array.from(container.querySelectorAll('h1,h2,h3,h4,h5,h6'))
+ .map(heading => {
+ const level = Number(heading.tagName.slice(1));
+ const label = heading.textContent?.trim() ?? '';
+ return {
+ id: heading.id,
+ label,
+ level,
+ };
+ })
+ .filter(item => item.id !== '' && item.label !== '');
+}
+
+/** Build outline items from h1-h6 elements inside a DOM container. */
+export function useOutlineFromDOM(
+ containerRef: React.RefObject<HTMLElement | null>,
+): OutlineItem[] {
+ const [items, setItems] = useState<OutlineItem[]>(() =>
+ collectOutlineItems(containerRef.current),
+ );
+
+ useEffect(() => {
+ const container = containerRef.current;
+ setItems(collectOutlineItems(container));
+
+ if (container == null || typeof MutationObserver === 'undefined') {
+ return;
+ }
+
+ const observer = new MutationObserver(() => {
+ setItems(collectOutlineItems(container));
+ });
+ observer.observe(container, {
+ childList: true,
+ subtree: true,
+ characterData: true,
+ attributes: true,
+ attributeFilter: ['id'],
+ });
+
+ return () => {
+ observer.disconnect();
+ };
+ }, [containerRef]);
+
+ return items;
+}
diff --git a/packages/core/src/Outline/useOutlineFromMarkdown.ts b/packages/core/src/Outline/useOutlineFromMarkdown.ts
new file mode 100644
index 0000000000..531d43fffc
--- /dev/null
+++ b/packages/core/src/Outline/useOutlineFromMarkdown.ts
@@ -0,0 +1,23 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useOutlineFromMarkdown.ts
+ * @input Uses React, parseOutlineFromMarkdown
+ * @output Exports useOutlineFromMarkdown hook
+ * @position Hook utility; consumed by applications and Outline examples
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Outline/Outline.doc.mjs
+ * - /packages/core/src/Outline/index.ts
+ */
+
+import {useMemo} from 'react';
+import {parseOutlineFromMarkdown} from './parseOutlineFromMarkdown';
+import type {OutlineItem} from './types';
+
+/** Extract a stable outline from a Markdown string. */
+export function useOutlineFromMarkdown(markdown: string): OutlineItem[] {
+ return useMemo(() => parseOutlineFromMarkdown(markdown), [markdown]);
+}
diff --git a/packages/core/src/Outline/useScrollSpy.ts b/packages/core/src/Outline/useScrollSpy.ts
new file mode 100644
index 0000000000..0864d2fc55
--- /dev/null
+++ b/packages/core/src/Outline/useScrollSpy.ts
@@ -0,0 +1,142 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useScrollSpy.ts
+ * @input Uses React, IntersectionObserver, OutlineItem type
+ * @output Exports internal useScrollSpy hook
+ * @position Internal behavior hook; consumed by XDSOutline.tsx
+ *
+ * SYNC: When modified, update /packages/core/src/Outline/XDSOutline.tsx
+ */
+
+import {useEffect, useRef, useState} from 'react';
+import type {OutlineItem} from './types';
+
+function getScrollableAncestor(element: HTMLElement | null): Element | null {
+ let current = element?.parentElement ?? null;
+
+ while (current != null) {
+ const computedStyle = window.getComputedStyle(current);
+ const overflowY = computedStyle.overflowY;
+ const isScrollable =
+ (overflowY === 'auto' ||
+ overflowY === 'scroll' ||
+ overflowY === 'overlay') &&
+ current.scrollHeight > current.clientHeight;
+
+ if (isScrollable) {
+ return current;
+ }
+
+ current = current.parentElement;
+ }
+
+ return null;
+}
+
+interface UseScrollSpyOptions {
+ activeId?: string;
+ items: OutlineItem[];
+ onActiveIdChange?: (id: string) => void;
+ rootRef: React.RefObject<HTMLElement | null>;
+}
+
+export function useScrollSpy({
+ activeId,
+ items,
+ onActiveIdChange,
+ rootRef,
+}: UseScrollSpyOptions): [string | undefined, (id: string) => void] {
+ const isControlled = activeId !== undefined;
+ const [uncontrolledActiveId, setUncontrolledActiveId] = useState<
+ string | undefined
+ >(items[0]?.id);
+ const visibleHeadingIdsRef = useRef<Set<string>>(new Set());
+ const headingTopRef = useRef<Map<string, number>>(new Map());
+ const activeIdRef = useRef<string | undefined>(activeId);
+ const itemIds = items.map(item => item.id).join('\n');
+ activeIdRef.current = isControlled ? activeId : uncontrolledActiveId;
+
+ useEffect(() => {
+ if (isControlled || typeof IntersectionObserver === 'undefined') {
+ return;
+ }
+
+ const headingElements = items
+ .map(item => document.getElementById(item.id))
+ .filter((element): element is HTMLElement => element != null);
+
+ if (headingElements.length === 0) {
+ return;
+ }
+
+ const visibleHeadingIds = visibleHeadingIdsRef.current;
+ const headingTop = headingTopRef.current;
+
+ const setNextActiveId = (nextActiveId: string) => {
+ if (activeIdRef.current === nextActiveId) {
+ return;
+ }
+ activeIdRef.current = nextActiveId;
+ setUncontrolledActiveId(nextActiveId);
+ onActiveIdChange?.(nextActiveId);
+ };
+
+ const chooseActiveHeading = () => {
+ let nextActiveId: string | undefined;
+ let nextTop = Number.POSITIVE_INFINITY;
+
+ for (const id of visibleHeadingIds) {
+ const top = headingTop.get(id) ?? Number.POSITIVE_INFINITY;
+ if (top < nextTop) {
+ nextTop = top;
+ nextActiveId = id;
+ }
+ }
+
+ if (nextActiveId != null) {
+ setNextActiveId(nextActiveId);
+ }
+ };
+
+ const observer = new IntersectionObserver(
+ entries => {
+ for (const entry of entries) {
+ const id = entry.target.id;
+ headingTop.set(id, entry.boundingClientRect.top);
+ if (entry.isIntersecting) {
+ visibleHeadingIds.add(id);
+ } else {
+ visibleHeadingIds.delete(id);
+ }
+ }
+ chooseActiveHeading();
+ },
+ {
+ root: getScrollableAncestor(rootRef.current),
+ threshold: 0,
+ },
+ );
+
+ for (const headingElement of headingElements) {
+ observer.observe(headingElement);
+ }
+
+ return () => {
+ observer.disconnect();
+ visibleHeadingIds.clear();
+ headingTop.clear();
+ };
+ }, [isControlled, itemIds, items, onActiveIdChange, rootRef]);
+
+ const setActiveId = (nextActiveId: string) => {
+ if (!isControlled) {
+ setUncontrolledActiveId(nextActiveId);
+ }
+ onActiveIdChange?.(nextActiveId);
+ };
+
+ return [isControlled ? activeId : uncontrolledActiveId, setActiveId];
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index be19e04e0e..8bf1dcf585 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -153,6 +153,7 @@ export * from './Timestamp';
// Overlay
export * from './Overlay';
+export * from './Outline';
// Overflow list
export * from './OverflowList';