Skip to content

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

TypeScript

feat(Outline): sliding indicator track, density variant, CSS anchor positioning (#2746)

Cindy Zhangd745249fb196
diff --git a/apps/storybook/stories/Outline.stories.tsx b/apps/storybook/stories/Outline.stories.tsx
index 2eb0e8fee6..0dc33cc4b5 100644
--- a/apps/storybook/stories/Outline.stories.tsx
+++ b/apps/storybook/stories/Outline.stories.tsx
@@ -25,6 +25,11 @@ const meta: Meta<typeof Outline> = {
control: 'text',
description: 'Controlled active item id',
},
+ density: {
+ control: 'radio',
+ options: ['default', 'compact'],
+ description: 'Density variant',
+ },
},
};
@@ -77,7 +82,7 @@ function storySlug(value: string): string {
value
.trim()
.toLowerCase()
- .replace(/['"]/g, '')
+ .replace(/['\u201C\u201D"]/g, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '') || 'section'
);
@@ -96,6 +101,15 @@ export const Controlled: Story = {
},
};
+/** Compact density variant — reduced spacing for dense UIs */
+export const Compact: Story = {
+ args: {
+ items: outlineItems,
+ activeId: 'installation',
+ density: 'compact',
+ },
+};
+
export const WithDocument: Story = {
render: () => (
<div
@@ -249,3 +263,24 @@ export const ExtractFromHTML: Story = {
);
},
};
+
+/** Deep nesting with multiple indent levels */
+export const DeepNesting: Story = {
+ render: () => {
+ const items: OutlineItem[] = [
+ {id: 'chapter-1', label: 'Chapter 1', level: 1},
+ {id: 'section-1-1', label: 'Section 1.1', level: 2},
+ {id: 'subsection-1-1-1', label: 'Subsection 1.1.1', level: 3},
+ {id: 'subsection-1-1-2', label: 'Subsection 1.1.2', level: 3},
+ {id: 'section-1-2', label: 'Section 1.2', level: 2},
+ {id: 'chapter-2', label: 'Chapter 2', level: 1},
+ {id: 'section-2-1', label: 'Section 2.1', level: 2},
+ ];
+
+ return (
+ <div style={{width: 240}}>
+ <Outline items={items} activeId="subsection-1-1-1" />
+ </div>
+ );
+ },
+};
diff --git a/packages/cli/templates/blocks/components/Outline/OutlineControlled.doc.mjs b/packages/cli/templates/blocks/components/Outline/OutlineControlled.doc.mjs
new file mode 100644
index 0000000000..0415a584a8
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Outline/OutlineControlled.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'Outline',
+ name: 'Outline — Controlled',
+ displayName: 'Outline — Controlled',
+ description:
+ 'Drive the active section yourself with activeId and onActiveIdChange. Providing activeId disables the built-in scroll-spy so your own logic owns the highlight.',
+ isReady: true,
+ aspectRatio: 4 / 3,
+ componentsUsed: ['Outline', 'Layout', 'Text', 'Button'],
+};
diff --git a/packages/cli/templates/blocks/components/Outline/OutlineControlled.tsx b/packages/cli/templates/blocks/components/Outline/OutlineControlled.tsx
new file mode 100644
index 0000000000..a3d6b6eee6
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Outline/OutlineControlled.tsx
@@ -0,0 +1,54 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import {Outline} from '@xds/core/Outline';
+import type {OutlineItem} from '@xds/core/Outline';
+import {VStack, HStack} from '@xds/core/Layout';
+import {Button} from '@xds/core/Button';
+import {Text} from '@xds/core/Text';
+
+const items: OutlineItem[] = [
+ {id: 'ctrl-summary', label: 'Summary', level: 2},
+ {id: 'ctrl-details', label: 'Details', level: 2},
+ {id: 'ctrl-results', label: 'Results', level: 2},
+ {id: 'ctrl-next-steps', label: 'Next steps', level: 2},
+];
+
+export default function OutlineControlled() {
+ const [activeId, setActiveId] = useState('ctrl-details');
+
+ const index = items.findIndex(item => item.id === activeId);
+ const goTo = (next: number) => {
+ const clamped = Math.max(0, Math.min(items.length - 1, next));
+ setActiveId(items[clamped].id);
+ };
+
+ return (
+ <VStack gap={4} style={{width: 240}}>
+ <Outline
+ items={items}
+ activeId={activeId}
+ onActiveIdChange={setActiveId}
+ />
+ <HStack gap={2}>
+ <Button
+ variant="secondary"
+ size="sm"
+ label="Previous"
+ onClick={() => goTo(index - 1)}
+ />
+ <Button
+ variant="secondary"
+ size="sm"
+ label="Next"
+ onClick={() => goTo(index + 1)}
+ />
+ </HStack>
+ <Text type="supporting" color="secondary">
+ Active section: {items[index]?.label}
+ </Text>
+ </VStack>
+ );
+}
diff --git a/packages/cli/templates/blocks/components/Outline/OutlineDeepNesting.doc.mjs b/packages/cli/templates/blocks/components/Outline/OutlineDeepNesting.doc.mjs
new file mode 100644
index 0000000000..5132c16818
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Outline/OutlineDeepNesting.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'Outline',
+ name: 'Outline — Deep Nesting',
+ displayName: 'Outline — Deep Nesting',
+ description:
+ 'Heading levels 1 through 4 map to progressively deeper indentation, so a long document with sub-sections stays scannable.',
+ isReady: true,
+ aspectRatio: 4 / 3,
+ componentsUsed: ['Outline'],
+};
diff --git a/packages/cli/templates/blocks/components/Outline/OutlineDeepNesting.tsx b/packages/cli/templates/blocks/components/Outline/OutlineDeepNesting.tsx
new file mode 100644
index 0000000000..0ceb482af6
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Outline/OutlineDeepNesting.tsx
@@ -0,0 +1,26 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {Outline} from '@xds/core/Outline';
+import type {OutlineItem} from '@xds/core/Outline';
+
+const items: OutlineItem[] = [
+ {id: 'deep-introduction', label: 'Introduction', level: 1},
+ {id: 'deep-concepts', label: 'Core concepts', level: 2},
+ {id: 'deep-tokens', label: 'Tokens', level: 3},
+ {id: 'deep-color', label: 'Color', level: 4},
+ {id: 'deep-spacing', label: 'Spacing', level: 4},
+ {id: 'deep-components', label: 'Components', level: 2},
+ {id: 'deep-primitives', label: 'Primitives', level: 3},
+ {id: 'deep-patterns', label: 'Patterns', level: 3},
+ {id: 'deep-resources', label: 'Resources', level: 1},
+];
+
+export default function OutlineDeepNesting() {
+ return (
+ <div style={{width: 240}}>
+ <Outline items={items} activeId="deep-color" />
+ </div>
+ );
+}
diff --git a/packages/cli/templates/blocks/components/Outline/OutlineDensity.doc.mjs b/packages/cli/templates/blocks/components/Outline/OutlineDensity.doc.mjs
new file mode 100644
index 0000000000..82b8a07073
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Outline/OutlineDensity.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'Outline',
+ name: 'Outline — Density',
+ displayName: 'Outline — Density',
+ description:
+ 'Two density variants control item padding. Use compact for dense sidebars and default for standard documentation layouts. The sliding indicator automatically matches each item height.',
+ isReady: true,
+ aspectRatio: 4 / 3,
+ componentsUsed: ['Outline', 'Layout', 'Text'],
+};
diff --git a/packages/cli/templates/blocks/components/Outline/OutlineDensity.tsx b/packages/cli/templates/blocks/components/Outline/OutlineDensity.tsx
new file mode 100644
index 0000000000..c7f0093f4d
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Outline/OutlineDensity.tsx
@@ -0,0 +1,43 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {Outline} from '@xds/core/Outline';
+import type {OutlineItem} from '@xds/core/Outline';
+import {HStack, VStack} from '@xds/core/Layout';
+import {Text} from '@xds/core/Text';
+
+const items: OutlineItem[] = [
+ {id: 'density-getting-started', label: 'Getting started', level: 2},
+ {id: 'density-configuration', label: 'Configuration', level: 2},
+ {id: 'density-api', label: 'API reference', level: 3},
+ {id: 'density-examples', label: 'Examples', level: 3},
+ {id: 'density-faq', label: 'FAQ', level: 2},
+];
+
+export default function OutlineDensity() {
+ return (
+ <HStack gap={10} vAlign="start">
+ <VStack gap={3} style={{width: 200}}>
+ <Text type="supporting" color="secondary" weight="medium">
+ Default
+ </Text>
+ <Outline
+ items={items}
+ density="default"
+ activeId="density-configuration"
+ />
+ </VStack>
+ <VStack gap={3} style={{width: 200}}>
+ <Text type="supporting" color="secondary" weight="medium">
+ Compact
+ </Text>
+ <Outline
+ items={items}
+ density="compact"
+ activeId="density-configuration"
+ />
+ </VStack>
+ </HStack>
+ );
+}
diff --git a/packages/core/src/Outline/Outline.doc.mjs b/packages/core/src/Outline/Outline.doc.mjs
index 79da7ace01..1f3d55e660 100644
--- a/packages/core/src/Outline/Outline.doc.mjs
+++ b/packages/core/src/Outline/Outline.doc.mjs
@@ -15,6 +15,7 @@ export const docs = {
'scroll spy',
'documentation',
'anchors',
+ 'sliding indicator',
],
playground: {
defaults: {
@@ -28,7 +29,7 @@ export const docs = {
},
theming: {
targets: [
- {className: 'xds-outline'},
+ {className: 'xds-outline', visualProps: ['density']},
{className: 'xds-outline-item', visualProps: ['level'], states: ['active']},
],
},
@@ -37,13 +38,13 @@ export const docs = {
name: 'Outline',
displayName: 'Outline',
description:
- 'Document outline navigation. Renders a flat heading list as anchor links and manages scroll-spy active state when uncontrolled.',
+ 'Document outline navigation with sliding indicator track. Renders a flat heading list as anchor links with a density variant and 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.',
+ 'Ordered heading items. Each item has id, label, and level (1-6). The id should match the target heading element id.',
required: true,
},
{
@@ -64,6 +65,12 @@ export const docs = {
description: 'Accessible label for the nav landmark.',
default: "'Table of contents'",
},
+ {
+ name: 'density',
+ type: "'default' | 'compact'",
+ description: "Density variant controlling item padding. 'compact' for dense UIs, 'default' for standard spacing.",
+ default: "'default'",
+ },
{
name: 'xstyle',
type: 'StyleXStyles',
@@ -71,14 +78,76 @@ export const docs = {
'StyleX styles for layout customization. Must be a stylex.create() value.',
},
],
+ examples: [
+ {
+ label: 'Basic',
+ code: `
+import {Outline} from '@xds/core/Outline';
+
+const items = [
+ {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: 'accessibility', label: 'Accessibility', level: 2},
+];
+
+// Uncontrolled: built-in scroll-spy tracks the topmost visible heading.
+<Outline items={items} />;
+`,
+ },
+ {
+ label: 'Compact (density="compact")',
+ code: `
+import {Outline} from '@xds/core/Outline';
+
+// Dense sidebars use the compact variant; the sliding indicator
+// automatically matches the shorter item height.
+<Outline items={items} density="compact" />;
+`,
+ },
+ {
+ label: 'Controlled active section',
+ code: `
+import {useState} from 'react';
+import {Outline} from '@xds/core/Outline';
+
+function ControlledOutline() {
+ const [activeId, setActiveId] = useState('overview');
+
+ // Providing activeId disables built-in scroll-spy — you own the active state.
+ return (
+ <Outline
+ items={items}
+ activeId={activeId}
+ onActiveIdChange={setActiveId}
+ />
+ );
+}
+`,
+ },
+ {
+ label: 'Generate items from markdown',
+ code: `
+import {Outline, useOutlineFromMarkdown} from '@xds/core/Outline';
+
+function MarkdownOutline({markdown}) {
+ // Derives {id, label, level} items from headings in the source.
+ const items = useOutlineFromMarkdown(markdown);
+ return <Outline items={items} />;
+}
+`,
+ },
+ ],
},
],
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.',
+ '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.',
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: 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.'},
@@ -93,7 +162,7 @@ export const docsZh = {
group: 'Outline',
theming: {
targets: [
- {className: 'xds-outline'},
+ {className: 'xds-outline', visualProps: ['density']},
{className: 'xds-outline-item', visualProps: ['level'], states: ['active']},
],
},
@@ -102,13 +171,13 @@ export const docsZh = {
name: 'Outline',
displayName: 'Outline',
description:
- '文档大纲导航。将扁平标题列表渲染为锚点链接,并在非受控模式下管理滚动监听的激活状态。',
+ '文档大纲导航,带有滑动指示器轨道。将扁平标题列表渲染为锚点链接,支持密度变体和非受控模式下的滚动监听。',
props: [
{
name: 'items',
type: 'OutlineItem[]',
description:
- '有序标题项。每项包含 id、label 和 level。id 应匹配目标标题元素的 id。',
+ '有序标题项。每项包含 id、label 和 level (1-6)。id 应匹配目标标题元素的 id。',
required: true,
},
{
@@ -128,6 +197,12 @@ export const docsZh = {
description: 'nav 地标的无障碍标签。',
default: "'Table of contents'",
},
+ {
+ name: 'density',
+ type: "'default' | 'compact'",
+ description: "控制项目内边距的密度变体。'compact' 用于紧凑界面,'default' 为标准间距。",
+ default: "'default'",
+ },
{
name: 'xstyle',
type: 'StyleXStyles',
@@ -142,6 +217,7 @@ export const docsZh = {
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: 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.'},
@@ -152,13 +228,14 @@ export const docsZh = {
/** @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.',
+ '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 via IntersectionObserver topmost-visible-heading; controlled with activeId; smooth-scroll on click.',
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 density="compact" in dense sidebars where vertical space is tight.'},
{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.'},
@@ -169,6 +246,7 @@ export const docsDense = {
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' (standard) or 'compact'. Default: 'default'.",
xstyle: 'StyleX styles for layout. Must be stylex.create() value.',
},
components: [
@@ -176,12 +254,13 @@ export const docsDense = {
name: 'Outline',
displayName: 'Outline',
description:
- 'Document outline nav. Renders heading anchors and manages scroll-spy active state when uncontrolled.',
+ 'Document outline nav with sliding indicator. Renders heading anchors with a density variant 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'.",
+ density: "Density variant: 'default' | 'compact'. Default: 'default'.",
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.tsx
index 5cb35a21be..61b3d69caa 100644
--- a/packages/core/src/Outline/Outline.test.tsx
+++ b/packages/core/src/Outline/Outline.test.tsx
@@ -9,9 +9,9 @@
* SYNC: When modified, update this header
*/
-import {useRef, useState} from 'react';
+import {useRef} from 'react';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-import {act, render, screen, waitFor} from '@testing-library/react';
+import {act, render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {Outline} from './Outline';
import {parseOutlineFromMarkdown} from './parseOutlineFromMarkdown';
@@ -102,6 +102,8 @@ describe('Outline', () => {
block: 'start',
});
expect(onActiveIdChange).toHaveBeenCalledWith('install');
+
+ document.body.removeChild(target);
});
it('applies stable root and item class names', () => {
@@ -118,6 +120,87 @@ describe('Outline', () => {
);
});
+ it('renders with density="compact"', () => {
+ render(
+ <Outline
+ items={items}
+ density="compact"
+ data-testid="outline-compact"
+ />,
+ );
+ expect(screen.getByTestId('outline-compact').className).toContain(
+ 'compact',
+ );
+ });
+
+ it('renders with density="default" by default', () => {
+ render(<Outline items={items} data-testid="outline-default" />);
+ expect(screen.getByTestId('outline-default').className).toContain(
+ 'default',
+ );
+ });
+
+ it('renders the sliding indicator track', () => {
+ const {container} = render(<Outline items={items} activeId="intro" />);
+ // Track is present as an aria-hidden div
+ const track = container.querySelector('[aria-hidden="true"]');
+ expect(track).toBeInTheDocument();
+ });
+
+ it('renders the indicator unconditionally (CSS anchor positioning handles visibility)', () => {
+ const {container} = render(<Outline items={items} activeId="intro" />);
+ const indicator = container.querySelector('.xds-outline-indicator');
+ expect(indicator).toBeInTheDocument();
+ // No inline top/height styles — positioning is CSS-driven
+ expect((indicator as HTMLElement).style.top).toBe('');
+ expect((indicator as HTMLElement).style.height).toBe('');
+ });
+
+ it('renders the active anchor before the indicator for CSS anchor positioning', () => {
+ const {container} = render(<Outline items={items} activeId="intro" />);
+ const activeLink = screen.getByRole('link', {name: 'Introduction'});
+ const indicator = container.querySelector('.xds-outline-indicator');
+
+ expect(indicator).toBeInTheDocument();
+ expect(
+ activeLink.compareDocumentPosition(indicator as Element) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
+ it('preserves the legacy controlled API (items + activeId + onActiveIdChange)', () => {
+ // Regression guard: the pre-refresh public API must keep working unchanged.
+ const onActiveIdChange = vi.fn();
+ const {rerender} = render(
+ <Outline
+ items={items}
+ activeId="intro"
+ onActiveIdChange={onActiveIdChange}
+ />,
+ );
+
+ expect(screen.getByRole('link', {name: 'Introduction'})).toHaveAttribute(
+ 'aria-current',
+ 'true',
+ );
+
+ // Controlled active id is driven entirely by the prop.
+ rerender(
+ <Outline
+ items={items}
+ activeId="api"
+ onActiveIdChange={onActiveIdChange}
+ />,
+ );
+ expect(screen.getByRole('link', {name: 'API'})).toHaveAttribute(
+ 'aria-current',
+ 'true',
+ );
+ expect(
+ screen.getByRole('link', {name: 'Introduction'}),
+ ).not.toHaveAttribute('aria-current');
+ });
+
it('updates uncontrolled active id from IntersectionObserver', () => {
let observerCallback: IntersectionObserverCallback | undefined;
@@ -160,26 +243,23 @@ describe('Outline', () => {
'true',
);
expect(onActiveIdChange).toHaveBeenCalledWith('api');
+
+ document.body.removeChild(intro);
+ document.body.removeChild(api);
});
});
describe('useOutlineFromDOM', () => {
- it('collects headings and updates after mutations', async () => {
- const user = userEvent.setup();
-
+ it('collects headings from DOM container', () => {
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}
+ <h3 id="details">Details</h3>
</article>
<output>
{outlineItems
@@ -191,15 +271,8 @@ describe('useOutlineFromDOM', () => {
}
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();
- });
+ expect(
+ screen.getByText('2:intro:Intro|3:details:Details'),
+ ).toBeInTheDocument();
});
});
diff --git a/packages/core/src/Outline/Outline.tsx b/packages/core/src/Outline/Outline.tsx
index 8f63016bf8..fc4dcb60f3 100644
--- a/packages/core/src/Outline/Outline.tsx
+++ b/packages/core/src/Outline/Outline.tsx
@@ -8,10 +8,16 @@
* @output Exports Outline component and OutlineProps type
* @position Core implementation; consumed by index.ts
*
+ * A table-of-contents navigation component with:
+ * - Sliding indicator track (vertical divider + animated active bar)
+ * - Density variant (default/compact)
+ * - Scroll-spy active state when uncontrolled
+ *
* 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
+ * - /packages/cli/templates/blocks/components/Outline/ (showcase blocks)
*/
import {useRef} from 'react';
@@ -50,21 +56,73 @@ export interface OutlineProps extends BaseProps<HTMLElement> {
/** Accessible label for the nav landmark. @default 'Table of contents' */
label?: string;
+ /**
+ * Density variant controlling item padding.
+ * - 'default': Standard spacing (default)
+ * - 'compact': Reduced spacing for dense UIs
+ * @default 'default'
+ */
+ density?: 'default' | 'compact';
+
/** Test ID for testing frameworks. */
'data-testid'?: string;
}
+// =============================================================================
+// Styles
+// =============================================================================
+
const styles = stylex.create({
root: {
- color: colorVars['--color-text-secondary'],
- fontSize: typeScaleVars['--text-supporting-size'],
- lineHeight: typeScaleVars['--text-supporting-leading'],
+ display: 'flex',
+ flexDirection: 'row',
+ position: 'relative',
+ gap: spacingVars['--spacing-0-5'],
width: '100%',
},
+ track: {
+ position: 'relative',
+ width: '2px',
+ flexShrink: 0,
+ order: -1,
+ },
+ dividerLine: {
+ position: 'absolute',
+ insetBlockStart: 0,
+ insetBlockEnd: 0,
+ insetInlineStart: 0,
+ width: '2px',
+ backgroundColor: colorVars['--color-border'],
+ borderRadius: radiusVars['--radius-full'],
+ pointerEvents: 'none',
+ },
+ indicator: {
+ position: 'absolute',
+ insetInlineStart: 0,
+ width: '2px',
+ backgroundColor: colorVars['--color-icon-primary'],
+ borderRadius: radiusVars['--radius-full'],
+ pointerEvents: 'none',
+ zIndex: 1,
+ positionAnchor: '--outline-active',
+ top: 'anchor(--outline-active top, 0px)',
+ height: 'anchor-size(--outline-active height, 0px)',
+ transitionProperty: 'top, height',
+ transitionDuration: durationVars['--duration-fast-min'],
+ transitionTimingFunction: easeVars['--ease-standard'],
+ },
+ activeAnchor: {
+ anchorName: '--outline-active',
+ },
list: {
- listStyleType: 'none',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-0-5'],
margin: 0,
padding: 0,
+ listStyle: 'none',
+ flex: 1,
+ minWidth: 0,
},
item: {
listStyleType: 'none',
@@ -73,15 +131,13 @@ const styles = stylex.create({
},
link: {
alignItems: 'center',
- borderRadius: radiusVars['--radius-inner'],
+ borderRadius: radiusVars['--radius-element'],
boxSizing: 'border-box',
- color: 'inherit',
+ color: colorVars['--color-text-secondary'],
cursor: 'pointer',
display: 'flex',
- minHeight: spacingVars['--spacing-7'],
+ fontWeight: fontWeightVars['--font-weight-normal'],
outline: 'none',
- paddingBlock: spacingVars['--spacing-1'],
- paddingInlineEnd: spacingVars['--spacing-2'],
position: 'relative',
textAlign: 'start',
textDecoration: 'none',
@@ -89,6 +145,8 @@ const styles = stylex.create({
transitionProperty: 'background-color, color',
transitionTimingFunction: easeVars['--ease-standard'],
width: '100%',
+ fontSize: typeScaleVars['--text-body-size'],
+ lineHeight: typeScaleVars['--text-body-leading'],
':hover': {
'@media (hover: hover)': {
backgroundColor: colorVars['--color-overlay-hover'],
@@ -104,20 +162,8 @@ const styles = stylex.create({
},
},
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,
- },
+ color: colorVars['--color-text-primary'],
+ fontWeight: fontWeightVars['--font-weight-semibold'],
},
label: {
overflow: 'hidden',
@@ -126,24 +172,71 @@ const styles = stylex.create({
},
});
-const dynamicStyles = stylex.create({
- levelIndent: (level: number) => ({
- paddingInlineStart: `calc(${Math.max(0, Math.min(5, level - 1))} * ${spacingVars['--spacing-4']} + ${spacingVars['--spacing-2']})`,
- }),
+const densityStyles = stylex.create({
+ compact: {
+ paddingBlock: spacingVars['--spacing-1'],
+ paddingInlineEnd: spacingVars['--spacing-2'],
+ },
+ default: {
+ paddingBlock: spacingVars['--spacing-2'],
+ paddingInlineEnd: spacingVars['--spacing-2'],
+ },
+});
+
+const indentStyles = stylex.create({
+ level1: {paddingInlineStart: spacingVars['--spacing-3']},
+ level2: {paddingInlineStart: spacingVars['--spacing-7']},
+ level3: {paddingInlineStart: spacingVars['--spacing-11']},
+ level4: {paddingInlineStart: spacingVars['--spacing-12']},
});
+function getIndentStyle(level: number) {
+ // Map heading levels 1-6 to visual indent levels 1-4
+ // Level 1 (h1) = indent 1, Level 2 (h2) = indent 1, Level 3 (h3) = indent 2, etc.
+ const indentLevel = Math.max(1, Math.min(4, level - 1 || 1));
+ switch (indentLevel) {
+ case 1:
+ return indentStyles.level1;
+ case 2:
+ return indentStyles.level2;
+ case 3:
+ return indentStyles.level3;
+ default:
+ return indentStyles.level4;
+ }
+}
+
+// =============================================================================
+// Component
+// =============================================================================
+
/**
* A table-of-contents navigation component for document headings.
*
* Outline 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.
+ * indentation based on each heading level. Features a sliding indicator
+ * track that animates to the active item.
+ *
+ * When `activeId` is omitted, it observes heading elements by id and marks
+ * the topmost visible heading active.
+ *
+ * @example
+ * ```
+ * <Outline
+ * items={[
+ * {id: 'intro', label: 'Introduction', level: 1},
+ * {id: 'features', label: 'Features', level: 2},
+ * {id: 'api', label: 'API Reference', level: 1},
+ * ]}
+ * />
+ * ```
*/
export function Outline({
items,
activeId,
onActiveIdChange,
label = 'Table of contents',
+ density = 'default',
xstyle,
className,
style,
@@ -188,16 +281,17 @@ export function Outline({
aria-label={label}
data-testid={testId}
{...mergeProps(
- xdsThemeProps('outline'),
+ xdsThemeProps('outline', {density}),
stylex.props(styles.root, xstyle),
className,
style,
)}>
- <ul {...stylex.props(styles.list)}>
+ <ul {...stylex.props(styles.list)} role="list">
{items.map(item => {
const isActive = item.id === resolvedActiveId;
+
return (
- <li key={item.id} {...stylex.props(styles.item)}>
+ <li key={item.id} {...stylex.props(styles.item)} role="listitem">
<LinkComponent
href={`#${item.id}`}
aria-current={isActive ? 'true' : undefined}
@@ -209,9 +303,10 @@ export function Outline({
}),
stylex.props(
styles.link,
- dynamicStyles.levelIndent(item.level),
+ densityStyles[density],
+ getIndentStyle(item.level),
isActive && styles.activeLink,
- isActive && styles.activeIndicator,
+ isActive && styles.activeAnchor,
),
)}>
<span {...stylex.props(styles.label)}>{item.label}</span>
@@ -220,6 +315,19 @@ export function Outline({
);
})}
</ul>
+
+ {/* Track divider. Rendered after the list so the active anchor appears
+ earlier in DOM order; `order: -1` keeps the track visually before it. */}
+ <div {...stylex.props(styles.track)} aria-hidden="true">
+ <span {...stylex.props(styles.dividerLine)} />
+ </div>
+ <span
+ {...mergeProps(
+ xdsThemeProps('outline-indicator'),
+ stylex.props(styles.indicator),
+ )}
+ aria-hidden="true"
+ />
</nav>
);
}