An open source design system that's fully customizable and agent ready
TypeScript
docs(useOutlineFromMarkdown): add hook docs and a docs article example block (#9719)
Hanbin Tan120847534aa6
diff --git a/.changeset/hook-doc-use-outline-from-markdown.md b/.changeset/hook-doc-use-outline-from-markdown.mdnew file mode 100644index 0000000000..d1c8c92db2--- /dev/null+++ b/.changeset/hook-doc-use-outline-from-markdown.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+'@astryxdesign/cli': patch+---++[docs] Hook docs for `useOutlineFromMarkdown`, so `astryx hook useOutlineFromMarkdown` and `astryx search` return it, and a `useOutlineFromMarkdown — Docs Article` example block: a Markdown article and an Outline built from the same string through the hook, with a button that adds a section and its linked entry.+@hskl18diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.jsonindex 33b2d9dc0d..3e21c9b798 100644--- a/apps/sandbox/scripts/next-export-routes.json+++ b/apps/sandbox/scripts/next-export-routes.json@@ -786,6 +786,7 @@"/templates/useGridFocusHookUsage/","/templates/useKeyboardHintHookUsage/","/templates/useListFocusHookUsage/",+ "/templates/useOutlineFromMarkdownHookUsage/","/templates/useOverflowHookUsage/","/templates/usePressFeedbackHookUsage/","/templates/useStreamingTextHookUsage/",diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 1d4aafeacb..24f1d3591d 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -3686,6 +3686,11 @@"path": "examples/use-list-focus/recent-files","aliases": []},+ {+ "name": "example-use-outline-from-markdown-docs-article",+ "path": "examples/use-outline-from-markdown/docs-article",+ "aliases": []+ },{"name": "example-use-overflow-editor-toolbar","path": "examples/use-overflow/editor-toolbar",@@ -3941,6 +3946,11 @@"path": "hooks/use-multi-combobox","aliases": []},+ {+ "name": "hook-use-outline-from-markdown",+ "path": "hooks/use-outline-from-markdown",+ "aliases": []+ },{"name": "hook-use-overflow","path": "hooks/use-overflow",diff --git a/packages/cli/api/template/use-outline-from-markdown-hook-usage.test.tsx b/packages/cli/api/template/use-outline-from-markdown-hook-usage.test.tsxnew file mode 100644index 0000000000..0248d7b481--- /dev/null+++ b/packages/cli/api/template/use-outline-from-markdown-hook-usage.test.tsx@@ -0,0 +1,94 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @vitest-environment jsdom++/**+ * The useOutlineFromMarkdown example builds its Outline and its article from+ * one Markdown string: each entry links to a rendered heading, and the button+ * adds a heading and an entry that link to each other.+ */++import {act} from 'react';+import {createRoot, type Root} from 'react-dom/client';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import UseOutlineFromMarkdownHookUsage from '../../assets/templates/blocks/components/Outline/useOutlineFromMarkdownHookUsage';++(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =+ true;++let root: Root | null = null;+let container: HTMLElement;++function outlineEntries(): Array<{label: string; target: string}> {+ return Array.from(container.querySelectorAll('nav a[href^="#"]')).map(+ link => ({+ label: link.textContent ?? '',+ target: (link.getAttribute('href') ?? '').slice(1),+ }),+ );+}++function headingIds(): string[] {+ return Array.from(+ container.querySelectorAll('h1, h2, h3, h4, h5, h6'),+ heading => heading.id,+ );+}++function addSection(): void {+ const button = Array.from(container.querySelectorAll('button')).find(+ candidate => candidate.textContent === 'Add section',+ );+ act(() => button?.click());+}++beforeEach(() => {+ vi.stubGlobal(+ 'matchMedia',+ (query: string) =>+ ({+ matches: false,+ media: query,+ addEventListener: () => {},+ removeEventListener: () => {},+ }) as unknown as MediaQueryList,+ );+ container = document.createElement('div');+ document.body.appendChild(container);+ act(() => {+ root = createRoot(container);+ root.render(<UseOutlineFromMarkdownHookUsage />);+ });+});++afterEach(() => {+ act(() => root?.unmount());+ root = null;+ container.remove();+ vi.unstubAllGlobals();+});++describe('useOutlineFromMarkdown example', () => {+ it('links each outline entry to a rendered heading, in order', () => {+ const entries = outlineEntries();+ expect(entries.map(entry => entry.label)).toEqual([+ 'Before you start',+ 'Run the upgrade',+ 'Update the packages',+ 'Rebuild the project',+ 'Check the result',+ ]);+ expect(entries.map(entry => entry.target)).toEqual(headingIds());+ });++ it('adds a linked entry each time the button adds a section', () => {+ addSection();+ addSection();+ const added = outlineEntries().slice(-2);+ expect(added.map(entry => entry.label)).toEqual([+ 'New section',+ 'New section',+ ]);+ expect(added[0].target).not.toBe(added[1].target);+ expect(outlineEntries().map(entry => entry.target)).toEqual(headingIds());+ });+});diff --git a/packages/cli/assets/templates/blocks/components/Outline/useOutlineFromMarkdownHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Outline/useOutlineFromMarkdownHookUsage.doc.mjsnew file mode 100644index 0000000000..36cea617aa--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Outline/useOutlineFromMarkdownHookUsage.doc.mjs@@ -0,0 +1,14 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'useOutlineFromMarkdown',+ name: 'useOutlineFromMarkdown — Docs Article',+ displayName: 'useOutlineFromMarkdown — Docs Article',+ description:+ 'A docs-style article with an Outline next to it, built from the same Markdown string through useOutlineFromMarkdown. "Add section" appends a heading to the string, and a new entry that links to it appears in the outline.',+ isReady: true,+ aspectRatio: 16 / 9,+ componentsUsed: ['Markdown', 'Outline', 'ScrollableArea', 'Button', 'Layout'],+};diff --git a/packages/cli/assets/templates/blocks/components/Outline/useOutlineFromMarkdownHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Outline/useOutlineFromMarkdownHookUsage.tsxnew file mode 100644index 0000000000..f8aa1202d6--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Outline/useOutlineFromMarkdownHookUsage.tsx@@ -0,0 +1,69 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useRef, useState} from 'react';+import {Button} from '@astryxdesign/core/Button';+import {HStack, VStack} from '@astryxdesign/core/Layout';+import {Markdown} from '@astryxdesign/core/Markdown';+import {Outline, useOutlineFromMarkdown} from '@astryxdesign/core/Outline';+import {ScrollableArea} from '@astryxdesign/core/ScrollableArea';++const ARTICLE = `## Before you start++Check that your project builds on the current release. Commit your work, so+that you can compare the result of the upgrade.++## Run the upgrade++Update the packages, then rebuild the project. The upgrade changes no source+files.++### Update the packages++Install the new version of every package at the same time. Mixed versions fail+the build.++### Rebuild the project++Delete the build output first. A stale cache can hide a real error.++## Check the result++Open the pages that you use most, and compare them with the earlier build.+`;++const NEW_SECTION = `+## New section++The button added this heading to the Markdown string.+`;++export default function UseOutlineFromMarkdownHookUsage() {+ const [markdown, setMarkdown] = useState(ARTICLE);+ const items = useOutlineFromMarkdown(markdown);+ const articleRef = useRef<HTMLDivElement>(null);++ return (+ <HStack gap={6} align="start" width="100%">+ <ScrollableArea+ ref={articleRef}+ label="Article"+ height={320}+ width="100%">+ <Markdown>{markdown}</Markdown>+ </ScrollableArea>+ <VStack gap={3} align="start" width={220}>+ {/* A non-zero offset moves only the article. With 0, a click also moves+ the page around the article. */}+ <Outline items={items} scrollContainerRef={articleRef} offset={8} />+ <Button+ label="Add section"+ variant="secondary"+ size="sm"+ onClick={() => setMarkdown(current => current + NEW_SECTION)}+ />+ </VStack>+ </HStack>+ );+}diff --git a/packages/core/src/Outline/useOutlineFromMarkdown.doc.mjs b/packages/core/src/Outline/useOutlineFromMarkdown.doc.mjsnew file mode 100644index 0000000000..009b3c470f--- /dev/null+++ b/packages/core/src/Outline/useOutlineFromMarkdown.doc.mjs@@ -0,0 +1,157 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').HookDoc} */+export const docs = {+ name: 'useOutlineFromMarkdown',+ displayName: 'useOutlineFromMarkdown',+ keywords: [+ 'outline',+ 'table of contents',+ 'toc',+ 'markdown',+ 'headings',+ 'heading ids',+ 'same-page navigation',+ ],+ params: [+ {+ name: 'markdown',+ type: 'string',+ description:+ 'The Markdown source. Pass the same string you render with Markdown.',+ required: true,+ },+ {+ name: 'options',+ type: 'ParseOutlineFromMarkdownOptions',+ description:+ 'Parse options. Omit them for a document that Markdown renders without plugins.',+ required: false,+ },+ {+ name: 'options.plugins',+ type: 'ReadonlyArray<MarkdownPluginEntry>',+ description:+ 'The ordered Markdown plugin list. Pass the same list to Markdown, so transforms, labels and ids agree. The outline is recomputed when the list reference changes.',+ required: false,+ },+ {+ name: 'options.isFinal',+ type: 'boolean',+ description:+ "Whether the source is complete. Pass false while Markdown's isStreaming is true, so both apply the same transforms.",+ default: 'true',+ required: false,+ },+ ],+ returns: [+ {+ name: 'items',+ type: 'OutlineItem[]',+ description:+ "One item per root heading, in document order, ready for Outline's items prop. id is the id Markdown renders on the heading in a complete document without sources, label is the heading's text, and level is its depth from 1 to 6.",+ },+ ],+ usage: {+ description:+ 'Extracts the headings of a Markdown string for an Outline next to the rendered document. It uses the parser and heading slugs that Markdown uses, so in a complete document each item links to its heading, and fenced code never counts as a heading. The result is memoized on the source and the options. Outside React, use parseOutlineFromMarkdown.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Pass the same string, plugin list and finality to Markdown and this hook, so items match the rendered headings once the content is complete.',+ },+ {+ guidance: true,+ description:+ 'Declare the plugin list outside the component or memoize it. A new array on each render recomputes the outline.',+ },+ {+ guidance: true,+ description:+ 'For several documents on one page, install one createMarkdownHeadingLinks per document with headingIdPrefix, so their ids do not collide.',+ },+ {+ guidance: false,+ description:+ 'Write the items by hand or find headings with a regular expression. They drift from the rendered ids.',+ },+ {+ guidance: false,+ description:+ 'Expect every item to have a target while content streams. Markdown reveals text gradually and trims unfinished syntax, so a heading can be absent or have another id until the content is complete.',+ },+ {+ guidance: false,+ description:+ "Expect an item to link to a heading that cites a Markdown sources entry. The hook does not receive sources, so the ids differ: for '# Intro [ref]', Markdown renders intro and the hook returns intro-ref.",+ },+ {+ guidance: false,+ description:+ 'Expect an item for a nested heading, such as one in a blockquote. Only root headings become items.',+ },+ ],+ },+ relatedComponents: ['Outline', 'Markdown'],+ importPath: '@astryxdesign/core/Outline',+ category: 'Navigation',+};++/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */+export const docsDense = {+ description:+ 'Headings of a Markdown string as OutlineItem[] for an Outline beside the rendered document. Same parser and heading slugs as Markdown; memoized on source and options.',+ paramDescriptions: {+ markdown: 'Markdown source; the same string you render with Markdown.',+ options: 'parse options; omit for a document without plugins.',+ 'options.plugins':+ 'ordered plugin list; pass the same list to Markdown. New reference recomputes.',+ 'options.isFinal':+ "whether the source is complete; false while Markdown's isStreaming is true.",+ },+ returnDescriptions: {+ items:+ 'one item per root heading in document order: id is the rendered id in a complete document without sources, label is its text, level is 1-6.',+ },+ usage: {+ description:+ 'Headings of a Markdown string for an Outline next to the rendered document. Same parser and slugs as Markdown, so items link to their headings in a complete document. Outside React, use parseOutlineFromMarkdown.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Pass the same string, plugin list and finality to Markdown and the hook; items match the headings once content is complete.',+ },+ {+ guidance: true,+ description:+ 'Keep the plugin list stable; a new array each render recomputes.',+ },+ {+ guidance: true,+ description:+ 'Several documents on one page: one createMarkdownHeadingLinks per document with headingIdPrefix.',+ },+ {+ guidance: false,+ description: 'Write items by hand or find headings with a regex.',+ },+ {+ guidance: false,+ description:+ 'Expect every item to have a target while content streams; a heading can be absent or have another id until complete.',+ },+ {+ guidance: false,+ description:+ 'Expect an item to link to a heading that cites a Markdown sources entry; the hook does not receive sources, so the ids differ.',+ },+ {+ guidance: false,+ description:+ 'Expect items for nested headings; only root headings count.',+ },+ ],+ },+};diff --git a/packages/core/src/Outline/useOutlineFromMarkdown.ts b/packages/core/src/Outline/useOutlineFromMarkdown.tsindex 0f9bfc2bd0..7d96fc2c10 100644--- a/packages/core/src/Outline/useOutlineFromMarkdown.ts+++ b/packages/core/src/Outline/useOutlineFromMarkdown.ts@@ -10,6 +10,7 @@** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Outline/Outline.doc.mjs+ * - /packages/core/src/Outline/useOutlineFromMarkdown.doc.mjs* - /packages/core/src/Outline/index.ts*/