An open source design system that's fully customizable and agent ready
TypeScript
fix(docsite): clarify search result destinations (#8588)
rubyycheung84e8552562af
diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjsindex cce1be2160..122e6244a5 100644--- a/apps/docsite/scripts/generate-data.mjs+++ b/apps/docsite/scripts/generate-data.mjs@@ -17,6 +17,7 @@* - templateRegistry.ts — page templates including playground source* - templateMetadataRegistry.ts — lightweight page-template metadata* - docsRegistry.ts — long-form documentation topics from CLI docs/+ * - searchLinks.json — search destinations and document presentation metadata*/import * as fs from 'node:fs';@@ -62,6 +63,7 @@ import {import {expandWorkspaceDirs} from '../../../scripts/lib/workspace-globs.mjs';import {projectThemingDoc} from './lib/theming-doc.mjs';import {searchLinkTables} from '../src/lib/searchLinks.mjs';+import {exampleAnchorId} from '../src/lib/exampleAnchor.mjs';import {collectBlogImages} from './lib/blog-images.mjs';import {buildTypeDefinitionIndex,@@ -2390,6 +2392,7 @@ function generateExampleRegistry(blocks, availableRegistryPaths) {entries.push({exampleFor: block.exampleFor,basename: base,+ anchorId: exampleAnchorId(block.dirName),registryItemPath,name: block.name || block.dirName,description: block.description || '',@@ -2405,6 +2408,7 @@ function generateExampleRegistry(blocks, availableRegistryPaths) {entries.push({exampleFor: target,basename,+ anchorId: exampleAnchorId(block.dirName),registryItemPath,name: block.name || block.dirName,description: block.description || `Example using ${target}.`,@@ -2425,7 +2429,7 @@ function generateExampleRegistry(blocks, availableRegistryPaths) {const exampleLines = orderExamplesByDoc(component, examples).map(entry =>- ` {name: ${JSON.stringify(entry.name)}, description: ${JSON.stringify(entry.description)}, registryItemPath: ${JSON.stringify(entry.registryItemPath)}, source: ${JSON.stringify(entry.source)}, load: () => import('./examples/${entry.basename}')},`,+ ` {name: ${JSON.stringify(entry.name)}, anchorId: ${JSON.stringify(entry.anchorId)}, description: ${JSON.stringify(entry.description)}, registryItemPath: ${JSON.stringify(entry.registryItemPath)}, source: ${JSON.stringify(entry.source)}, load: () => import('./examples/${entry.basename}')},`,).join('\n');return ` '${component}': [\n${exampleLines}\n ],`;@@ -2437,6 +2441,7 @@ import type {ComponentType} from 'react';export interface ExampleEntry {name: string;+ anchorId: string;description: string;registryItemPath: string | null;source: string;diff --git a/apps/docsite/src/__tests__/cli-search-presentation.test.ts b/apps/docsite/src/__tests__/cli-search-presentation.test.tsnew file mode 100644index 0000000000..429c5d16d8--- /dev/null+++ b/apps/docsite/src/__tests__/cli-search-presentation.test.ts@@ -0,0 +1,145 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {+ BookText,+ Braces,+ LayoutTemplate,+ PanelTopDashed,+ Shapes,+ SwatchBook,+ Webhook,+} from 'lucide-react';+import {searchResultPresentation} from '../lib/cliSearchPresentation';+import type {SiteSearchResult} from '../lib/cliSearchTypes';++function result(+ fields: Pick<SiteSearchResult, 'domain' | 'name'> & Partial<SiteSearchResult>,+): SiteSearchResult {+ return {+ score: 100,+ reason: 'test',+ description: '',+ command: '',+ package: '@astryxdesign/core',+ href: '/',+ ...fields,+ } as SiteSearchResult;+}++describe('site search presentation', () => {+ it.each([+ [+ result({domain: 'component', name: 'Theme'}),+ {title: 'Theme', context: 'Component', icon: Shapes},+ ],+ [+ result({domain: 'hook', name: 'useTheme'}),+ {title: 'useTheme', context: 'Hook', icon: Webhook},+ ],+ [+ result({+ domain: 'template',+ name: 'ButtonFloating',+ displayName: 'Button — Floating',+ kind: 'block',+ }),+ {+ title: 'Button — Floating',+ context: 'Component Example',+ icon: PanelTopDashed,+ },+ ],+ [+ result({+ domain: 'template',+ name: 'ButtonShowcase',+ displayName: 'Button — Variants',+ kind: 'block',+ href: '/components/Button',+ }),+ {title: 'Button', context: 'Component', icon: Shapes},+ ],+ [+ result({+ domain: 'template',+ name: 'analytics-dashboard',+ displayName: 'Analytics Dashboard',+ kind: 'page',+ }),+ {+ title: 'Analytics Dashboard',+ context: 'Page Template',+ icon: LayoutTemplate,+ },+ ],+ [+ result({domain: 'theme', name: 'neutral', displayName: 'Neutral'}),+ {title: 'Neutral', context: 'Theme', icon: SwatchBook},+ ],+ ])('presents catalog result %#', (input, expected) => {+ expect(searchResultPresentation(input)).toEqual(expected);+ });++ it.each([+ ['Theming', 'Guides › Theming', 'guide', 'Guide', BookText],+ [+ 'Dark mode',+ 'Guides › Theming › Dark mode',+ 'guide',+ 'Guide · Theming',+ BookText,+ ],+ [+ 'Themes',+ 'Authoring › Building Blocks › Themes',+ 'guide',+ 'Guide · Authoring › Building Blocks',+ BookText,+ ],+ [+ 'Component lookups',+ 'Astryx CLI › Guides › Component lookups',+ 'guide',+ 'Guide · Astryx CLI',+ BookText,+ ],+ [+ 'astryx theme',+ 'Astryx CLI › Commands › astryx theme',+ undefined,+ 'Reference · Commands',+ Braces,+ ],+ [+ 'Overview',+ 'Typography › Font Setup › Overview',+ 'foundations',+ 'Foundation · Typography › Font Setup',+ BookText,+ ],+ [+ 'All Tokens',+ 'Foundations › All Tokens',+ 'foundations',+ 'Foundation',+ BookText,+ ],+ ])(+ 'presents %s as a typed document location',+ (siteTitle, title, siteCategory, context, icon) => {+ expect(+ searchResultPresentation(+ result({+ domain: 'doc',+ name: title.toLowerCase().replaceAll(' ', '-'),+ package: '@astryxdesign/cli',+ siteTitle,+ siteCategory,+ title,+ }),+ ),+ ).toEqual({title: siteTitle, context, icon});+ },+ );+});diff --git a/apps/docsite/src/__tests__/cli-search.test.ts b/apps/docsite/src/__tests__/cli-search.test.tsindex 2599dc1c94..3f83592023 100644--- a/apps/docsite/src/__tests__/cli-search.test.ts+++ b/apps/docsite/src/__tests__/cli-search.test.ts@@ -18,6 +18,7 @@ import type {SearchResponse} from '@astryxdesign/cli/api';import {GET} from '../app/api/search/route';import {searchResultHref} from '../lib/searchLinks.mjs';import type {SearchLinkTables} from '../lib/searchLinks.mjs';+import {searchResultPresentation} from '../lib/cliSearchPresentation';import {createCliSearchSource,searchTarget,@@ -99,7 +100,12 @@ describe('site search = astryx search', () => {expect(rest, query).toEqual(cliRest);expect(results.map(- ({href: _href, siteTitle: _siteTitle, ...result}) => result,+ ({+ href: _href,+ siteTitle: _siteTitle,+ siteCategory: _siteCategory,+ ...result+ }) => result,),query,).toEqual(cliResults);@@ -197,13 +203,15 @@ describe('site search links', () => {}});- it("opens an integration's example block on its component page", () => {- const blocks = Object.entries(links.blocks).filter(([key]) =>- key.startsWith('-astryxdesign-'),+ it("opens an integration's non-showcase block at its exact component example", () => {+ const blocks = Object.entries(links.blocks).filter(+ ([key, page]) =>+ key.startsWith('-astryxdesign-') && page.includes('#example-'),);expect(blocks.length).toBeGreaterThan(0);for (const [key, page] of blocks) {const [, pkg, name] = /^-astryxdesign-([a-z]+)-(.+)$/.exec(key)!;+ expect(page, key).toContain(`#example-${key}`);expect(searchResultHref({@@ -219,6 +227,34 @@ describe('site search links', () => {}});+ it('folds a component showcase into the component destination', () => {+ expect(+ searchResultHref(+ {+ domain: 'template',+ kind: 'block',+ name: 'ButtonShowcase',+ package: '@astryxdesign/core',+ },+ links,+ ),+ ).toBe('/components/Button');+ });++ it('opens a Core non-showcase block at its exact component example', () => {+ expect(+ searchResultHref(+ {+ domain: 'template',+ kind: 'block',+ name: 'ButtonFloating',+ package: '@astryxdesign/core',+ },+ links,+ ),+ ).toBe('/components/Button#example-ButtonFloating');+ });+it('titles doc results the way the site does, never with the docs-tree path',async () => {@@ -228,15 +264,29 @@ describe('site search links', () => {'tokens spacing',]) {for (const result of (await api(query)).data.results) {- if (result.domain !== 'doc') continue;+ if (result.domain !== 'doc') {+ continue;+ }expect(result.siteTitle, `${query}: ${result.name}`).toBeTruthy();expect(result.siteTitle).not.toMatch(/Unorganized/);+ const expectedCategory = links.categories[result.href];+ if (expectedCategory) {+ expect(result.siteCategory, `${query}: ${result.name}`).toBe(+ expectedCategory,+ );+ }}}},SLOW,);+ it('carries the destination page category for search presentation', () => {+ expect(links.categories['/docs/tokens']).toBe('foundations');+ expect(links.categories['/docs/typography']).toBe('foundations');+ expect(links.categories['/docs/cli-component-lookups']).toBe('guide');+ });+it('opens a doc section at its anchor', () => {const href = searchResultHref({domain: 'doc', name: 'author-a-theme', section: 'palette'},@@ -278,9 +328,16 @@ describe('search panel order', () => {);it(- 'lists each place once, with a label no other row has',+ 'lists each place once, with rendered text no other row has',async () => {- for (const query of ['dark mode', 'authoring', 'tokens spacing']) {+ for (const query of [+ 'dark mode',+ 'authoring',+ 'tokens spacing',+ 'button variants',+ 'banner statuses',+ 'divider variants',+ ]) {const {data} = await api(query);const source = createCliSearchSource(async () => new Response(JSON.stringify({data})),@@ -288,11 +345,12 @@ describe('search panel order', () => {const items = await source.search(query);const hrefs = items.map(item => item.auxiliaryData.href);expect(new Set(hrefs).size, `${query}: ${hrefs}`).toBe(hrefs.length);- const docLabels = items- .filter(item => item.auxiliaryData.domain === 'doc')- .map(item => item.label);- expect(new Set(docLabels).size, `${query}: ${docLabels}`).toBe(- docLabels.length,+ const renderedText = items.map(item => {+ const {title, context} = searchResultPresentation(item.auxiliaryData);+ return `${title} · ${context}`;+ });+ expect(new Set(renderedText).size, `${query}: ${renderedText}`).toBe(+ renderedText.length,);}},diff --git a/apps/docsite/src/app/api/search/route.ts b/apps/docsite/src/app/api/search/route.tsindex 5041c2c4ff..eaa88eebb0 100644--- a/apps/docsite/src/app/api/search/route.ts+++ b/apps/docsite/src/app/api/search/route.ts@@ -3,7 +3,8 @@/*** @file GET /api/search?q=<query>: `astryx search <query>`, run by the site.* @input The query, as `astryx search` takes it.- * @output The CLI's search response, each result with the site path it opens.+ * @output The CLI's search response, each result with the site destination and+ * its destination page's title and registry category when available.* @position Called by the search panel (lib/cliSearchSource.ts).** The site's search is the CLI's: this calls `search()` from@@ -14,6 +15,7 @@import {search} from '@astryxdesign/cli/api';import {+ searchResultCategory,searchResultHref,searchResultTitle,} from '../../../lib/searchLinks.mjs';@@ -69,7 +71,17 @@ export async function GET(request: Request): Promise<Response> {href,links as SearchLinkTables,);- return {...result, href, ...(siteTitle ? {siteTitle} : {})};+ const siteCategory = searchResultCategory(+ result,+ href,+ links as SearchLinkTables,+ );+ return {+ ...result,+ href,+ ...(siteTitle ? {siteTitle} : {}),+ ...(siteCategory ? {siteCategory} : {}),+ };});return Response.json({...response, data: {...response.data, matchCount, results}},diff --git a/apps/docsite/src/components/SearchPalette.tsx b/apps/docsite/src/components/SearchPalette.tsxindex acb7f2686e..be46a11f3d 100644--- a/apps/docsite/src/components/SearchPalette.tsx+++ b/apps/docsite/src/components/SearchPalette.tsx@@ -2,16 +2,33 @@'use client';+/**+ * @file Renders CLI-ranked site-search results as readable destination rows.+ * @input The palette open state and results from createCliSearchSource().+ * @output Search navigation with concise titles, type/location context, and icons.+ * @position Mounted by the shared docsite top navigation.+ */+import {useMemo, useCallback} from 'react';import {useRouter} from 'next/navigation';+import * as stylex from '@stylexjs/stylex';import {CommandPalette} from '@astryxdesign/core/CommandPalette';+import {Icon} from '@astryxdesign/core/Icon';+import {HStack, VStack} from '@astryxdesign/core/Layout';import {Text} from '@astryxdesign/core/Text';import {trackSearch} from '../lib/analytics';-import {- createCliSearchSource,- resultKind,- searchTarget,-} from '../lib/cliSearchSource';+import {createCliSearchSource, searchTarget} from '../lib/cliSearchSource';+import {searchResultPresentation} from '../lib/cliSearchPresentation';++const styles = stylex.create({+ result: {+ minWidth: 0,+ },+ copy: {+ flex: 1,+ minWidth: 0,+ },+});interface SearchPaletteProps {isOpen: boolean;@@ -45,15 +62,27 @@ export function SearchPalette({isOpen, onOpenChange}: SearchPaletteProps) {isOpen={isOpen}onOpenChange={onOpenChange}searchSource={searchSource}- renderItem={item => (- <Text type="inherit">- {item.label}- <Text type="supporting" color="secondary">- {' '}- {resultKind(item.auxiliaryData)}- </Text>- </Text>- )}+ renderItem={item => {+ const result = item.auxiliaryData;+ const {+ title,+ context,+ icon: ResultIcon,+ } = searchResultPresentation(result);+ return (+ <HStack gap={3} vAlign="center" width="100%" xstyle={styles.result}>+ <Icon icon={ResultIcon} size="sm" color="secondary" />+ <VStack gap={0} xstyle={styles.copy}>+ <Text type="label" weight="semibold" maxLines={1}>+ {title}+ </Text>+ <Text type="supporting" color="secondary" maxLines={1}>+ {context}+ </Text>+ </VStack>+ </HStack>+ );+ }}label="Search docs, components, and templates"value=""onValueChange={handleValueChange}diff --git a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsxindex 12e748f64b..e929cdf4ec 100644--- a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx+++ b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx@@ -2,6 +2,13 @@'use client';+/**+ * @file Composes a generated component's overview, examples, and detail tabs.+ * @input Component metadata, package metadata, and its showcase block.+ * @output The interactive component detail article with stable example targets.+ * @position Client content for /components/[name].+ */+import * as stylex from '@stylexjs/stylex';import {Suspense} from 'react';import {useSearchParams, useRouter, usePathname} from 'next/navigation';@@ -15,6 +22,7 @@ import {typeScaleVars} from '@astryxdesign/core/theme/tokens.stylex';import {CodeExampleBlock} from '../CodeExampleBlock';import {TabList, Tab} from '@astryxdesign/core/TabList';import {ShowcasePreview} from './ShowcasePreview';+import {ExampleAnchor} from './ExampleAnchor';import {ComponentPreviewTheme} from './ComponentPreviewTheme';import {Anatomy} from './Anatomy';import {BestPractices} from './BestPractices';@@ -41,6 +49,7 @@ import {shadcnRegistryOrigin,} from '../../generated/shadcnRegistry';import {trackNavigate} from '../../lib/analytics';+import {exampleAnchorId} from '../../lib/exampleAnchor.mjs';import {shadcnComponentItemPath,shadcnInstallCommand,@@ -96,7 +105,7 @@ function OverviewContent({comp,pkg,pkgVersion,- showcase: _showcase,+ showcase,hasShowcase,}: ComponentDetailClientProps & {hasShowcase: boolean}) {const isHook = comp.params != null;@@ -106,11 +115,14 @@ function OverviewContent({return (<VStack gap={8} xstyle={styles.overviewProse}>{hasShowcase && (- <ComponentPreviewTheme>- <Card variant="muted" padding={0}>- <ShowcasePreview name={comp.name} />- </Card>- </ComponentPreviewTheme>+ <ExampleAnchor+ id={showcase ? exampleAnchorId(showcase.dirName) : undefined}>+ <ComponentPreviewTheme>+ <Card variant="muted" padding={0}>+ <ShowcasePreview name={comp.name} />+ </Card>+ </ComponentPreviewTheme>+ </ExampleAnchor>)}{comp.usage && (diff --git a/apps/docsite/src/components/component-detail/ExampleAnchor.tsx b/apps/docsite/src/components/component-detail/ExampleAnchor.tsxnew file mode 100644index 0000000000..55d0922cdd--- /dev/null+++ b/apps/docsite/src/components/component-detail/ExampleAnchor.tsx@@ -0,0 +1,58 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Renders and scrolls to a stable component-example deep-link target.+ * @input An optional generated anchor id and the rendered example content.+ * @output A header-aware target that works after lazy client rendering.+ * @position Wraps showcase and example cards on component detail pages.+ */++'use client';++import {useEffect, useRef, type ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';++const styles = stylex.create({+ root: {+ width: '100%',+ scrollMarginTop: 'calc(var(--appshell-header-height, 0px) + 16px)',+ },+});++function hashTarget(): string {+ try {+ return decodeURIComponent(window.location.hash.slice(1));+ } catch {+ return window.location.hash.slice(1);+ }+}++/** Gives a lazily rendered example a stable deep-link target. */+export function ExampleAnchor({+ id,+ children,+}: {+ id?: string;+ children: ReactNode;+}) {+ const ref = useRef<HTMLDivElement>(null);++ useEffect(() => {+ if (!id) {return;}+ const scrollIfTarget = () => {+ if (hashTarget() !== id) {return;}+ requestAnimationFrame(() =>+ ref.current?.scrollIntoView({block: 'start'}),+ );+ };+ scrollIfTarget();+ window.addEventListener('hashchange', scrollIfTarget);+ return () => window.removeEventListener('hashchange', scrollIfTarget);+ }, [id]);++ return (+ <div ref={ref} id={id} {...stylex.props(styles.root)}>+ {children}+ </div>+ );+}diff --git a/apps/docsite/src/components/component-detail/ExampleBlock.tsx b/apps/docsite/src/components/component-detail/ExampleBlock.tsxindex 89bc5821ac..4ec7d7cb98 100644--- a/apps/docsite/src/components/component-detail/ExampleBlock.tsx+++ b/apps/docsite/src/components/component-detail/ExampleBlock.tsx@@ -2,6 +2,13 @@'use client';+/**+ * @file Renders one generated component example and its supporting content.+ * @input An ExampleEntry and owning component name.+ * @output A live, deep-linkable preview with description, code, and install tabs.+ * @position Used by ComponentDetailClient's Examples section.+ */+import {useEffect, useState, type ComponentType} from 'react';import {Card} from '@astryxdesign/core/Card';import {Section} from '@astryxdesign/core/Section';@@ -14,6 +21,7 @@ import {Button} from '@astryxdesign/core/Button';import {HStack, VStack} from '@astryxdesign/core/Layout';import type {ExampleEntry} from '../../generated/exampleRegistry';import {ComponentPreviewTheme} from './ComponentPreviewTheme';+import {ExampleAnchor} from './ExampleAnchor';import {buildPlaygroundHref} from '../playgroundLink';import {trackOpenPlayground} from '../../lib/analytics';import {MarkdownText} from '../MarkdownText';@@ -91,75 +99,77 @@ export function ExampleBlock({entry, componentName}: ExampleBlockProps) {const [tab, setTab] = useState<string>('description');return (- <ComponentPreviewTheme>- <Card padding={3}>- <Text type="body" weight="medium">- {entry.name}- </Text>+ <ExampleAnchor id={entry.anchorId}>+ <ComponentPreviewTheme>+ <Card padding={3}>+ <Text type="body" weight="medium">+ {entry.name}+ </Text>- <LivePreview entry={entry} componentName={componentName} />+ <LivePreview entry={entry} componentName={componentName} />- <Section variant="muted" padding={1} dividers={['top']}>- <HStack- gap={1}- style={{justifyContent: 'space-between', alignItems: 'center'}}>- <TabList value={tab} onChange={setTab} size="sm">- <Tab value="description" label="Description" />- <Tab value="code" label="Code" />- {entry.registryItemPath && (- <Tab value="install" label="Install" />- )}- </TabList>- {entry.source && (- <Button- label="Open in Playground"- variant="ghost"- size="sm"- // Real anchor (Button renders <a> with href) so right-click /- // Cmd-click / middle-click "open in new tab" work. onClick stays- // for analytics; the href handles navigation natively.- href={buildPlaygroundHref(entry.source)}- onClick={() => {- trackOpenPlayground({page: 'components', item: entry.name});- }}- />- )}- </HStack>- </Section>- <Section variant="muted" padding={tab === 'code' ? 0 : 4}>- {tab === 'description' ? (- <MarkdownText type="body">- {entry.description || 'No description available.'}- </MarkdownText>- ) : tab === 'code' ? (- <CodeExampleBlock- code={entry.source}- language="tsx"- hasCopyButton- container="section"- width="100%"- />- ) : entry.registryItemPath ? (- <VStack gap={2}>- {shadcnRegistryIsPreview && (- <Text type="supporting" color="secondary">- This install URL expires with the draft preview.- </Text>+ <Section variant="muted" padding={1} dividers={['top']}>+ <HStack+ gap={1}+ style={{justifyContent: 'space-between', alignItems: 'center'}}>+ <TabList value={tab} onChange={setTab} size="sm">+ <Tab value="description" label="Description" />+ <Tab value="code" label="Code" />+ {entry.registryItemPath && (+ <Tab value="install" label="Install" />+ )}+ </TabList>+ {entry.source && (+ <Button+ label="Open in Playground"+ variant="ghost"+ size="sm"+ // Real anchor (Button renders <a> with href) so right-click /+ // Cmd-click / middle-click "open in new tab" work. onClick stays+ // for analytics; the href handles navigation natively.+ href={buildPlaygroundHref(entry.source)}+ onClick={() => {+ trackOpenPlayground({page: 'components', item: entry.name});+ }}+ />)}+ </HStack>+ </Section>+ <Section variant="muted" padding={tab === 'code' ? 0 : 4}>+ {tab === 'description' ? (+ <MarkdownText type="body">+ {entry.description || 'No description available.'}+ </MarkdownText>+ ) : tab === 'code' ? (<CodeExampleBlock- code={shadcnInstallCommand(- entry.registryItemPath,- shadcnRegistryOrigin,- )}- language="bash"+ code={entry.source}+ language="tsx"hasCopyButtoncontainer="section"width="100%"/>- </VStack>- ) : null}- </Section>- </Card>- </ComponentPreviewTheme>+ ) : entry.registryItemPath ? (+ <VStack gap={2}>+ {shadcnRegistryIsPreview && (+ <Text type="supporting" color="secondary">+ This install URL expires with the draft preview.+ </Text>+ )}+ <CodeExampleBlock+ code={shadcnInstallCommand(+ entry.registryItemPath,+ shadcnRegistryOrigin,+ )}+ language="bash"+ hasCopyButton+ container="section"+ width="100%"+ />+ </VStack>+ ) : null}+ </Section>+ </Card>+ </ComponentPreviewTheme>+ </ExampleAnchor>);}diff --git a/apps/docsite/src/lib/cliSearchPresentation.ts b/apps/docsite/src/lib/cliSearchPresentation.tsnew file mode 100644index 0000000000..859f546c08--- /dev/null+++ b/apps/docsite/src/lib/cliSearchPresentation.ts@@ -0,0 +1,148 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Converts canonical CLI search results into concise docsite rows.+ * @input A SiteSearchResult from the search API.+ * @output Display-only title, context, and icon; ranking and result data stay unchanged.+ * @position Consumed by SearchPalette.tsx.+ */++import type {ComponentType} from 'react';+import {+ BookText,+ Braces,+ LayoutTemplate,+ PanelTopDashed,+ Shapes,+ SwatchBook,+ Webhook,+ type LucideProps,+} from 'lucide-react';+import type {SiteSearchResult} from './cliSearchTypes';++const FALLBACK_DOC_ROOT_TYPES: Readonly<Record<string, string>> = {+ 'Astryx CLI': 'Reference',+ Authoring: 'Authoring',+ Foundations: 'Foundation',+ Guides: 'Guide',+ Migration: 'Migration',+};++function splitTitle(title: string): string[] {+ return title.split(/\s+›\s+/);+}++function componentDestination(result: SiteSearchResult): string | null {+ if (result.domain !== 'template' || result.kind !== 'block') {+ return null;+ }+ return /^\/components\/([^/#]+)$/.exec(result.href)?.[1] ?? null;+}++function displayTitleParts(result: SiteSearchResult): string[] {+ const component = componentDestination(result);+ if (component) {+ return [component];+ }+ const title =+ result.domain === 'doc'+ ? (result.siteTitle ?? result.title ?? result.name)+ : (result.displayName ?? result.name);+ return splitTitle(title);+}++function canonicalDocTitleParts(result: SiteSearchResult): string[] {+ return splitTitle(result.title ?? result.siteTitle ?? result.name);+}++function categoryType(category: string): string {+ if (category === 'foundations') {+ return 'Foundation';+ }+ return `${category.charAt(0).toUpperCase()}${category.slice(1)}`;+}++function docType(result: SiteSearchResult): string {+ if (result.siteCategory) {+ return categoryType(result.siteCategory);+ }+ const root = canonicalDocTitleParts(result)[0];+ return FALLBACK_DOC_ROOT_TYPES[root] ?? 'Guide';+}++function isReferenceDoc(result: SiteSearchResult): boolean {+ return result.domain === 'doc' && docType(result) === 'Reference';+}++function contextForDoc(result: SiteSearchResult): string {+ const parts = canonicalDocTitleParts(result);+ const root = parts[0];+ const type = docType(result);+ const categoryRoot =+ result.siteCategory === 'foundations'+ ? 'Foundations'+ : result.siteCategory === 'guide'+ ? 'Guides'+ : null;+ const location = result.siteCategory+ ? parts.slice(0, -1).filter(part => part !== categoryRoot)+ : Object.hasOwn(FALLBACK_DOC_ROOT_TYPES, root)+ ? parts.slice(1, -1)+ : parts.slice(0, -1);+ const breadcrumb = location.join(' › ');+ return breadcrumb ? `${type} · ${breadcrumb}` : type;+}++function contextForCatalogResult(result: SiteSearchResult): string {+ if (componentDestination(result)) {+ return 'Component';+ }+ switch (result.domain) {+ case 'component':+ return 'Component';+ case 'hook':+ return 'Hook';+ case 'template':+ return result.kind === 'block' ? 'Component Example' : 'Page Template';+ case 'theme':+ return 'Theme';+ default:+ return result.domain;+ }+}++function iconForResult(result: SiteSearchResult): ComponentType<LucideProps> {+ if (componentDestination(result)) {+ return Shapes;+ }+ switch (result.domain) {+ case 'component':+ return Shapes;+ case 'hook':+ return Webhook;+ case 'doc':+ return isReferenceDoc(result) ? Braces : BookText;+ case 'template':+ return result.kind === 'block' ? PanelTopDashed : LayoutTemplate;+ case 'theme':+ return SwatchBook;+ default:+ return BookText;+ }+}++/** Human-facing presentation for one CLI-ranked site-search result. */+export function searchResultPresentation(result: SiteSearchResult): {+ title: string;+ context: string;+ icon: ComponentType<LucideProps>;+} {+ return {+ title: displayTitleParts(result).at(-1) ?? result.name,+ context:+ result.domain === 'doc'+ ? contextForDoc(result)+ : contextForCatalogResult(result),+ icon: iconForResult(result),+ };+}diff --git a/apps/docsite/src/lib/cliSearchTypes.ts b/apps/docsite/src/lib/cliSearchTypes.tsindex e2c42f9e74..e7c9dc3122 100644--- a/apps/docsite/src/lib/cliSearchTypes.ts+++ b/apps/docsite/src/lib/cliSearchTypes.ts@@ -2,9 +2,10 @@import type {SearchResultEntry} from '@astryxdesign/cli/api';-/** One `astryx search` result, with the site path it opens and, for a doc,- * the title the site shows for it. */+/** One `astryx search` result, with the site destination it opens and, for a+ * registered doc page, the title and category the site shows for it. */export type SiteSearchResult = SearchResultEntry & {href: string;siteTitle?: string;+ siteCategory?: string;};diff --git a/apps/docsite/src/lib/exampleAnchor.mjs b/apps/docsite/src/lib/exampleAnchor.mjsnew file mode 100644index 0000000000..4eebdf886a--- /dev/null+++ b/apps/docsite/src/lib/exampleAnchor.mjs@@ -0,0 +1,21 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Defines stable HTML ids shared by search links and rendered examples.+ * @input A block catalog directory name.+ * @output A deterministic, HTML-safe component-example anchor id.+ * @position Used by docsite generation and component-detail rendering.+ */++/**+ * Stable id for a component example rendered from a CLI block.+ * The block directory name is the catalog identifier shared by search and the+ * generated example registry; sanitizing keeps integration-owned names valid+ * as HTML ids without inventing a second identity.+ *+ * @param {string} dirName+ * @returns {string}+ */+export function exampleAnchorId(dirName) {+ return `example-${String(dirName).replace(/[^a-zA-Z0-9_-]/g, '-')}`;+}diff --git a/apps/docsite/src/lib/searchLinks.mjs b/apps/docsite/src/lib/searchLinks.mjsindex 43a14f535f..44d88254a8 100644--- a/apps/docsite/src/lib/searchLinks.mjs+++ b/apps/docsite/src/lib/searchLinks.mjs@@ -4,8 +4,8 @@* @file Where a search result opens on the site.* @input A result of the CLI's search (`search()` from `@astryxdesign/cli/api`)* and the site's link tables, built with the site by searchLinkTables().- * @output The site path the result opens: a component, template, theme, or- * doc page, with the anchor of a doc section.+ * @output The site destination each result opens, plus the title and category+ * of a registered document destination.* @position Shared by scripts/generate-data.mjs (builds the tables) and the* site's search API (reads them). Plain JS so both can import it.*@@ -16,6 +16,8 @@* building `/docs/<route>`.*/+import {exampleAnchorId} from './exampleAnchor.mjs';+/*** @typedef {object} SearchLinkTables* @property {string[]} pages - Every doc page slug.@@ -27,6 +29,8 @@* @property {Record<string, string>} blocks - Block name -> the page that shows it.* @property {Record<string, string>} titles - A doc page's path, or a* section's path with its anchor, -> the title the site shows for it.+ * @property {Record<string, string>} categories - A doc page's path, or a+ * section's path with its anchor, -> the registry category of that page.*//**@@ -39,11 +43,11 @@/*** The tables a result's link is read from.* @param {object} site- * @param {Array<{topic: string, title?: string, sections?: Array<{id?: string, title: string}>}>} site.docTopics+ * @param {Array<{topic: string, title?: string, category?: string | null, sections?: Array<{id?: string, title: string}>}>} site.docTopics* @param {Record<string, string>} site.docRedirects* @param {string[]} site.components* @param {string[]} site.templates- * @param {Array<{name: string, dirName: string, exampleFor: string | null}>} site.blocks+ * @param {Array<{name: string, dirName: string, exampleFor: string | null, isShowcase?: boolean}>} site.blocks* @param {string[]} site.packagePages - Slugs of package pages (`cli` for* @astryxdesign/cli), which /docs/<slug> also serves.* @param {SectionAnchors} site.sectionAnchors@@ -54,6 +58,8 @@ export function searchLinkTables(site) {const anchors = {};/** @type {Record<string, string>} */const titles = {};+ /** @type {Record<string, string>} */+ const categories = {};// A namespace page (and a merged page) holds the sections of several// guides, and a section key is unique only within its guide. Each guide's// slug redirects to its first section, so the redirects give each guide's@@ -78,10 +84,13 @@ export function searchLinkTables(site) {for (const page of site.docTopics) {const ids = pageAnchors.get(page.topic) ?? [];const guides = (starts.get(page.topic) ?? []).sort((a, b) => a[0] - b[0]);- titles[`/docs/${page.topic}`] = page.title ?? page.topic;+ const pageHref = `/docs/${page.topic}`;+ titles[pageHref] = page.title ?? page.topic;+ if (page.category) categories[pageHref] = page.category;(page.sections ?? []).forEach((section, i) => {- titles[`/docs/${page.topic}#${ids[i]}`] =- `${page.title ?? page.topic} › ${section.title}`;+ const sectionHref = `${pageHref}#${ids[i]}`;+ titles[sectionHref] = `${page.title ?? page.topic} › ${section.title}`;+ if (page.category) categories[sectionHref] = page.category;if (!section.id) return;// The guides whose range holds this section: the latest start at or// before it (two slugs can share a start: a namespace with no text of@@ -108,7 +117,9 @@ export function searchLinkTables(site) {const owner = block.exampleFor;const href =owner && components.has(owner)- ? `/components/${owner}`+ ? block.isShowcase+ ? `/components/${owner}`+ : `/components/${owner}#${exampleAnchorId(block.dirName)}`: owner && templates.has(owner)? `/templates/${owner}`: null;@@ -129,6 +140,7 @@ export function searchLinkTables(site) {templates: [...templates].sort(),blocks,titles,+ categories,};}@@ -234,3 +246,17 @@ export function searchResultTitle(result, href, tables) {// CLI's title, without the docs tree's placeholder level for unfiled docs.return result.title?.replace(/^Unorganized › /, '');}++/**+ * The registry category of the page a doc result opens. Results without a+ * Docsite page have no category, so presentation can use a deterministic+ * fallback without inventing taxonomy for a registered page.+ * @param {{domain: string}} result+ * @param {string} href - searchResultHref of the result.+ * @param {SearchLinkTables} tables+ * @returns {string | undefined}+ */+export function searchResultCategory(result, href, tables) {+ if (result.domain !== 'doc') return undefined;+ return tables.categories[href];+}