-
Notifications
You must be signed in to change notification settings - Fork 111
docs(Storybook): add docs search addon #8501
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Lukas742
wants to merge
4
commits into
main
Choose a base branch
from
docs/pagefind
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| import { SearchIcon } from '@storybook/icons'; | ||
| import * as React from 'react'; | ||
| import { IconButton } from 'storybook/internal/components'; | ||
| import { addons, types } from 'storybook/manager-api'; | ||
|
|
||
| const ADDON_ID = 'content-search'; | ||
| const TOOL_ID = `${ADDON_ID}/toolbar`; | ||
| const isMac = navigator.platform.toUpperCase().includes('MAC'); | ||
| const shortcut = isMac ? '⌘⇧F' : 'Ctrl+Shift+F'; | ||
|
|
||
| function SearchButton() { | ||
| const openSearch = React.useCallback(() => { | ||
| const dialog = document.getElementById('pagefind-search-container'); | ||
| if (dialog && dialog instanceof HTMLDialogElement && !dialog.open) { | ||
| dialog.showModal(); | ||
| setTimeout(() => dialog.querySelector<HTMLInputElement>('.pagefind-ui__search-input')?.focus(), 50); | ||
| } | ||
| }, []); | ||
|
|
||
| React.useEffect(() => { | ||
| const handleKeydown = (e: KeyboardEvent) => { | ||
| if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key === 'f') { | ||
| e.preventDefault(); | ||
| openSearch(); | ||
| } | ||
| }; | ||
| document.addEventListener('keydown', handleKeydown); | ||
| return () => document.removeEventListener('keydown', handleKeydown); | ||
| }, [openSearch]); | ||
|
|
||
| return ( | ||
| <IconButton key={TOOL_ID} title={`Search docs (${shortcut})`} style={{ order: -2 }} onClick={openSearch}> | ||
| <SearchIcon /> | ||
| Search Docs (Beta) | ||
| </IconButton> | ||
| ); | ||
| } | ||
|
|
||
| addons.register(ADDON_ID, () => { | ||
| addons.add(TOOL_ID, { | ||
| type: types.TOOLEXTRA, | ||
| title: 'Search documentation content', | ||
| render: () => <SearchButton />, | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| #pagefind-search-container { | ||
| border: none; | ||
| padding: 1rem; | ||
| max-width: 80vw; | ||
| max-height: 80vh; | ||
| width: 100%; | ||
| overflow-y: auto; | ||
| background: var(--sapBackgroundColor); | ||
| border-radius: var(--sapElement_BorderCornerRadius); | ||
| box-shadow: var(--sapContent_Shadow3); | ||
| } | ||
| #pagefind-search-container::backdrop { | ||
| background: rgba(0, 0, 0, 0.5); | ||
| } | ||
| #pagefind-search-container .pagefind-ui__result-link { | ||
| color: var(--sapLinkColor); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| /* global PagefindUI */ | ||
|
|
||
| const container = document.getElementById('pagefind-search-container'); | ||
|
|
||
| if (container) { | ||
| try { | ||
| new PagefindUI({ | ||
| element: '#pagefind-ui', | ||
| showSubResults: true, | ||
| showImages: false, | ||
| showEmptyFilters: false, | ||
| }); | ||
| } catch { | ||
| // PagefindUI may not be available in dev mode (index only exists after build) | ||
| } | ||
|
|
||
| container.addEventListener('click', (e) => { | ||
| if (e.target === container) container.close(); | ||
| }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,186 @@ | ||
| import { readFileSync, existsSync } from 'node:fs'; | ||
| import { resolve, relative } from 'node:path'; | ||
| import { parseArgs } from 'node:util'; | ||
| import { glob } from 'glob'; | ||
| import * as pagefind from 'pagefind'; | ||
| import { extractComponentJSDoc, resolveComponentSource } from './extract-comp-description.ts'; | ||
|
|
||
| interface StoryIndexEntry { | ||
| id: string; | ||
| type: string; | ||
| name: string; | ||
| title?: string; | ||
| importPath?: string; | ||
| tags?: string[]; | ||
| } | ||
|
|
||
| // --- CLI args --- | ||
|
|
||
| const { values } = parseArgs({ | ||
| options: { | ||
| directory: { type: 'string', short: 'd' }, | ||
| }, | ||
| }); | ||
|
|
||
| if (typeof values.directory !== 'string') { | ||
| throw new Error('Expected --directory to be a string (e.g. --directory .out)'); | ||
| } | ||
|
|
||
| const outDir = resolve(process.cwd(), values.directory); | ||
| const indexJsonPath = resolve(outDir, 'index.json'); | ||
|
|
||
| if (!existsSync(indexJsonPath)) { | ||
| throw new Error(`index.json not found at ${indexJsonPath}. Did you run "storybook build" first?`); | ||
| } | ||
|
|
||
| // --- Read Storybook index.json --- | ||
|
|
||
| const storiesJson = JSON.parse(readFileSync(indexJsonPath, 'utf-8')); | ||
| const entries: StoryIndexEntry[] = Object.values(storiesJson.entries); | ||
|
|
||
| const importPathToEntry = new Map<string, StoryIndexEntry>(); | ||
| for (const entry of entries) { | ||
| if (entry.type === 'docs' && entry.importPath?.endsWith('.mdx')) { | ||
| importPathToEntry.set(entry.importPath, entry); | ||
| } | ||
| } | ||
|
|
||
| console.log(`Found ${importPathToEntry.size} docs entries in index.json`); | ||
|
|
||
| const mdxFiles = await glob('**/*.mdx', { | ||
| cwd: process.cwd(), | ||
| ignore: ['node_modules/**', '.out/**', '**/node_modules/**'], | ||
| }); | ||
|
|
||
| console.log(`Found ${mdxFiles.length} MDX files on disk`); | ||
|
|
||
| function extractTextFromMdx(source: string): string { | ||
| const lines = source.split('\n'); | ||
| const textParts: string[] = []; | ||
| let inCodeBlock = false; | ||
|
|
||
| for (const line of lines) { | ||
| if (line.trimStart().startsWith('```')) { | ||
| inCodeBlock = !inCodeBlock; | ||
| continue; | ||
| } | ||
|
|
||
| if (inCodeBlock) continue; | ||
|
|
||
| if (/^\s*import\s/.test(line)) continue; | ||
| if (/^\s*export\s/.test(line)) continue; | ||
|
|
||
| // Skip JSX-only lines (tags with no text content) | ||
| if (/^\s*<[A-Z][\w.]*[\s/>]/.test(line) && !/>([^<]+)</.test(line)) continue; | ||
| if (/^\s*<\/[A-Z]/.test(line)) continue; | ||
| if (/^\s*<Meta\s/.test(line)) continue; | ||
|
|
||
| const headingMatch = line.match(/^(#{1,6})\s+(.+)/); | ||
| if (headingMatch) { | ||
| textParts.push(headingMatch[2].trim()); | ||
| continue; | ||
| } | ||
|
|
||
| const cleaned = line | ||
| .replace(/<[^>]+>/g, '') | ||
Check failureCode scanning / CodeQL Incomplete multi-character sanitization High
This string may still contain
<script Error loading related location Loading |
||
| .replace(/\{`([^`]*)`\}/g, '$1') | ||
| .replace(/\{['"]([^'"]*)['"]\}/g, '$1') | ||
| .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') | ||
| .replace(/`([^`]+)`/g, '$1') | ||
| .replace(/\*{1,3}([^*]+)\*{1,3}/g, '$1') | ||
| .replace(/[<>]/g, '') | ||
| .trim(); | ||
|
|
||
| if (cleaned.length > 0) { | ||
| textParts.push(cleaned); | ||
| } | ||
| } | ||
|
|
||
| return textParts.join(' '); | ||
| } | ||
|
|
||
| // --- Extract component descriptions from JSDoc --- | ||
|
|
||
| const componentDescriptions = new Map<string, string>(); | ||
| for (const entry of entries) { | ||
| if (entry.type !== 'docs' || !entry.importPath?.endsWith('.mdx')) continue; | ||
| if (!entry.tags?.includes('attached-mdx')) continue; | ||
|
|
||
| const sourceFile = resolveComponentSource(entry.importPath); | ||
| if (!sourceFile) continue; | ||
|
|
||
| const description = extractComponentJSDoc(sourceFile); | ||
| if (description) { | ||
| componentDescriptions.set(entry.importPath, description); | ||
| } | ||
| } | ||
|
|
||
| console.log(`Extracted ${componentDescriptions.size} component descriptions from JSDoc`); | ||
|
|
||
| // --- Build Pagefind index --- | ||
|
|
||
| const { index } = await pagefind.createIndex(); | ||
| if (!index) { | ||
| throw new Error('Failed to create Pagefind index'); | ||
| } | ||
|
|
||
| let indexed = 0; | ||
| let skipped = 0; | ||
|
|
||
| for (const mdxFile of mdxFiles) { | ||
| const importPath = './' + mdxFile; | ||
| const entry = importPathToEntry.get(importPath); | ||
|
|
||
| if (!entry) { | ||
| skipped++; | ||
| continue; | ||
| } | ||
|
|
||
| const source = readFileSync(mdxFile, 'utf-8'); | ||
| const mdxText = extractTextFromMdx(source); | ||
|
|
||
| const description = componentDescriptions.get(importPath); | ||
| const text = description ? `${description} ${mdxText}` : mdxText; | ||
|
|
||
| if (text.length < 10) { | ||
| skipped++; | ||
| continue; | ||
| } | ||
|
|
||
| const url = `?path=/docs/${entry.id}`; | ||
|
|
||
| const category = entry.title?.split(' / ')[0] || 'Docs'; | ||
| const title = entry.title?.split(' / ').pop() || entry.name; | ||
|
|
||
| const { errors } = await index.addCustomRecord({ | ||
| url, | ||
| content: text, | ||
| language: 'en', | ||
| meta: { | ||
| title: entry.title || title, | ||
| category, | ||
| }, | ||
| }); | ||
|
|
||
| if (errors?.length) { | ||
| console.warn(` Warning indexing ${mdxFile}:`, errors); | ||
| } else { | ||
| indexed++; | ||
| } | ||
| } | ||
|
|
||
| console.log(`Indexed ${indexed} docs, skipped ${skipped} files (no matching entry or too short)`); | ||
|
|
||
| // --- Write index --- | ||
|
|
||
| const pagefindDir = resolve(outDir, 'pagefind'); | ||
| const { errors: writeErrors } = await index.writeFiles({ outputPath: pagefindDir }); | ||
|
|
||
| if (writeErrors?.length) { | ||
| console.error('Errors writing Pagefind index:', writeErrors); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| console.log(`Pagefind index written to ${relative(process.cwd(), pagefindDir)}/`); | ||
|
|
||
| await pagefind.close(); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| import { readFileSync, existsSync } from 'node:fs'; | ||
| import { dirname, resolve } from 'node:path'; | ||
|
|
||
| // Finds the last `/** ... */ const Name =` in a component file and extracts | ||
| // the description text, stripping JSDoc markers, @tags, tables, and boilerplate. | ||
| export function extractComponentJSDoc(filePath: string): string | null { | ||
| if (!existsSync(filePath)) return null; | ||
|
|
||
| const source = readFileSync(filePath, 'utf-8'); | ||
|
|
||
| // Locate `*/ const Name =` then walk backwards to find the opening `/**` | ||
| const constPattern = /\*\/\s*\n\s*(?:export\s+)?const\s+\w+\s*=/g; | ||
| let constMatch: RegExpExecArray | null; | ||
| let lastJSDoc: string | null = null; | ||
|
|
||
| while ((constMatch = constPattern.exec(source)) !== null) { | ||
| const closeIndex = constMatch.index; | ||
| const before = source.substring(0, closeIndex); | ||
| const openIndex = before.lastIndexOf('/**'); | ||
| if (openIndex === -1) continue; | ||
| lastJSDoc = source.substring(openIndex + 3, closeIndex); | ||
| } | ||
| if (!lastJSDoc) return null; | ||
|
|
||
| const lines = lastJSDoc.split('\n').map((line) => line.replace(/^\s*\*\s?/, '').trim()); | ||
|
|
||
| const textParts: string[] = []; | ||
| for (const line of lines) { | ||
| if (line.startsWith('@')) continue; | ||
| if (line.startsWith('__Note:__') || line.startsWith('__Note__:')) continue; | ||
| if (line.startsWith('|') || line.startsWith('---')) continue; | ||
| if (line.includes('UI5 Web Component!') || line.includes('Repository')) continue; | ||
| if (line.startsWith('##')) continue; | ||
|
|
||
| const cleaned = line | ||
| .replace(/`([^`]+)`/g, '$1') | ||
| .replace(/\*{1,3}([^*]+)\*{1,3}/g, '$1') | ||
| .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') | ||
| .trim(); | ||
|
|
||
| if (cleaned) textParts.push(cleaned); | ||
| } | ||
|
|
||
| return textParts.length > 0 ? textParts.join(' ') : null; | ||
| } | ||
|
|
||
| // Resolves MDX importPath to the component's index.tsx. | ||
| // Handles docs/ subdirectories (e.g. components/AnalyticalTable/docs/AnalyticalTable.mdx). | ||
| export function resolveComponentSource(mdxImportPath: string): string | null { | ||
| const mdxPath = mdxImportPath.replace(/^\.\//, ''); | ||
| const mdxDir = dirname(mdxPath); | ||
|
|
||
| const componentDir = mdxDir.endsWith('/docs') ? dirname(mdxDir) : mdxDir; | ||
|
|
||
| for (const ext of ['index.tsx', 'index.ts']) { | ||
| const candidate = resolve(componentDir, ext); | ||
| if (existsSync(candidate)) return candidate; | ||
| } | ||
|
|
||
| return null; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.