/* eslint-disable no-console */ import { join } from 'path' import { readFile } from 'fs/promises' import { getCollection } from 'astro:content' import type { CollectionKey } from 'astro:content' import { content } from '../../content' import { kebabCase, addDemosOrDeprecated } from '../index' import { getDefaultTabForApi } from '../packageUtils' import { getOutputDir } from '../getOutputDir' import { addSubsection } from '../case' import { extractReactTokens } from '../extractReactTokens' const SOURCE_ORDER: Record = { react: 1, 'react-next': 1.1, 'react-demos': 2, 'react-deprecated': 2.1, html: 3, 'html-demos': 4, 'design-guidelines': 99, accessibility: 100, 'upgrade-guide': 101, 'release-notes': 102, } const sortSources = (s1: string, s2: string) => { const s1Index = SOURCE_ORDER[s1] || 50 const s2Index = SOURCE_ORDER[s2] || 50 if (s1Index === 50 && s2Index === 50) { return s1.localeCompare(s2) } return s1Index > s2Index ? 1 : -1 } /** * Section item is always a string (subsections are kebab-cased and flattened into page names) */ export type SectionItem = string /** * Structure of the API index used for routing and navigation * Keys in sections/pages/tabs use '::' separator (e.g., 'v6::components::alert') * Subsections are kebab-cased and flattened into page names with underscores (e.g., 'forms_checkbox') */ export interface ApiIndex { /** Available documentation versions (e.g., ['v5', 'v6']) */ versions: string[] /** Sections by version - flat array of section names * (e.g., { 'v6': ['components', 'layouts', 'extensions'] }) */ sections: Record /** Pages by version::section with subsections kebab-cased and flattened using underscores * (e.g., { 'v6::components': ['alert', 'button', 'forms_checkbox', 'menus_select'] }) */ pages: Record /** Tabs by version::section::page where page may contain underscore-separated subsection * (e.g., { 'v6::components::alert': ['react'], 'v6::components::forms_checkbox': ['react'] }) */ tabs: Record /** Documented React props members by version::section::page, in frontmatter order. */ propComponents?: Record /** Examples by version::section::page::tab with titles * (e.g., { 'v6::components::alert::react': [{exampleName: 'AlertDefault', title: 'Default alert'}] }) */ examples: Record /** CSS token objects by version::section::page (e.g., { 'v6::components::accordion': [{name: '--pf-v6-c-accordion--...', value: '...', var: '...'}] }) */ css: Record } /** * Extracts examples with titles from markdown/MDX content * Looks for patterns and finds associated H3 titles * * @param body - The raw markdown/MDX text content * @returns Array of unique examples with titles in document order */ function extractExamplesWithTitles( body: string ): { exampleName: string; title: string | null }[] { if (!body) { return [] } // Match tags with src attribute containing an example name // Supports various attribute orders and spacing patterns const exampleRegex = /]*\ssrc=\{\s*(\w+)\s*\}[^>]*\/?>/g const examples: { exampleName: string; title: string | null }[] = [] const seen = new Set() let match // Find all examples and their positions while ((match = exampleRegex.exec(body)) !== null) { const exampleName = match[1] if (exampleName && !seen.has(exampleName)) { seen.add(exampleName) // Find the most recent h3 before this example const textBeforeExample = body.substring(0, match.index) const h3Matches = [...textBeforeExample.matchAll(/^### (.+)$/gm)] const title = h3Matches.length > 0 ? h3Matches[h3Matches.length - 1][1].trim() : null examples.push({ exampleName, title }) } } return examples } type PrecomputedExamplesByPath = Record< string, { exampleName: string; title: string | null }[] > async function readPrecomputedExamplesByPath( outputDir: string, ): Promise { const cachePath = join(outputDir, '.precomputed-examples.json') return JSON.parse(await readFile(cachePath, 'utf8')) as PrecomputedExamplesByPath } /** * Builds API index by analyzing all content collections. */ export async function generateApiIndex(): Promise { console.log('Generating API index from content collections...') const precomputedExamplesByPath = process.env.PF_DOCS_REQUIRE_PRECOMPUTED_EXAMPLES === 'true' ? await readPrecomputedExamplesByPath(await getOutputDir()) : null const index: ApiIndex = { versions: [], sections: {}, pages: {}, tabs: {}, propComponents: {}, examples: {}, css: {}, } // Get all versions const versionSet = new Set() content.forEach((entry: any) => { if (entry.version) { versionSet.add(entry.version) } }) index.versions = Array.from(versionSet).sort() // For each version, collect index data for (const version of versionSet) { const collectionsToFetch = content .filter((entry: any) => entry.version === version) .map((entry: any) => entry.name as CollectionKey) const collections = await Promise.all(collectionsToFetch.map((name) => getCollection(name))) const flatEntries = collections.flat() flatEntries.sort((a, b) => String(a.filePath).localeCompare(String(b.filePath))) // Collect sections, pages, and tabs in a single pass const sections = new Set() const sectionPages: Record> = {} const pageTabs: Record> = {} const tabExamples: Record = {} const pageCss: Record = {} const pageCssPrefixes: Record = {} const deprecatedPropComponents: Record = {} flatEntries.forEach((entry: any) => { const { section, subsection, id } = entry.data if (!section) { return } // Flatten subsections into page name using underscores // e.g., subsection="forms", id="checkbox" becomes page="forms_checkbox" const basePage = kebabCase(id) const page = addSubsection(basePage, subsection) // All pages are keyed by version::section (no subsection in key) const pageKey = `${version}::${section}` const tabKey = `${version}::${section}::${page}` // Collect section sections.add(section) // Collect page under section key if (!sectionPages[pageKey]) { sectionPages[pageKey] = new Set() } sectionPages[pageKey].add(page) // Collect tab const entryTab = entry.data.tab || entry.data.source || getDefaultTabForApi(entry.filePath) const tab = addDemosOrDeprecated(entryTab, entry.filePath) if (!pageTabs[tabKey]) { pageTabs[tabKey] = new Set() } pageTabs[tabKey].add(tab) // Prefer active React members, but retain deprecated-only pages such as Chip. if (tab === 'react' && entry.data.propComponents?.length) { index.propComponents![tabKey] = [...new Set(entry.data.propComponents)] } else if (tab === 'react-deprecated' && entry.data.propComponents?.length) { deprecatedPropComponents[tabKey] = [...new Set(entry.data.propComponents)] } const exampleKey = `${tabKey}::${tab}` const examplesWithTitles = precomputedExamplesByPath ? precomputedExamplesByPath[entry.filePath || ''] || [] : extractExamplesWithTitles(entry.body || '') if (examplesWithTitles.length > 0) { tabExamples[exampleKey] = examplesWithTitles } // Collect CSS prefixes for pages - we'll extract tokens later // Key by version::section::page (tabKey) so each page gets its own tokens if (entry.data.cssPrefix && !pageCssPrefixes[tabKey]) { pageCssPrefixes[tabKey] = entry.data.cssPrefix } }) Object.entries(deprecatedPropComponents).forEach(([key, propComponents]) => { if (!index.propComponents![key]) { index.propComponents![key] = propComponents } }) // Extract CSS tokens for pages that have cssPrefix for (const [pageKey, cssPrefix] of Object.entries(pageCssPrefixes)) { try { const tokens = await extractReactTokens(cssPrefix) if (tokens.length > 0) { pageCss[pageKey] = tokens } } catch (error) { console.warn(`Failed to extract CSS tokens for ${pageKey}:`, error) } } // Convert sets to sorted arrays // Sections are now always flat strings (subsections are in page names) // Add hardcoded API endpoints (icons, tokens) to the sections list const allSections = new Set([...sections, 'icons', 'tokens']) index.sections[version] = Array.from(allSections).sort() Object.entries(sectionPages).forEach(([key, pages]) => { index.pages[key] = Array.from(pages).sort() }) Object.entries(pageTabs).forEach(([key, tabs]) => { index.tabs[key] = Array.from(tabs).sort(sortSources) }) Object.entries(tabExamples) .sort(([a], [b]) => a.localeCompare(b)) .forEach(([key, examples]) => { index.examples[key] = examples }) // Add CSS token objects to index Object.entries(pageCss).forEach(([key, tokens]) => { index.css[key] = tokens }) } return index }