An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): add hook documentation system with CLI command (#1849)
Cindy Zhang685d69e6d287
diff --git a/packages/cli/src/api/hook.mjs b/packages/cli/src/api/hook.mjsnew file mode 100644index 0000000000..0e8b7bc9d8--- /dev/null+++ b/packages/cli/src/api/hook.mjs@@ -0,0 +1,144 @@+/**+ * @file Programmatic API for the hook command.+ *+ * Returns the same typed envelope { type, data } that `xds --json hook` outputs.+ * The CLI command handler is a thin wrapper around this function.+ */++import {findCoreDir} from '../utils/paths.mjs';+import {discoverHooks, findHookDoc, getAllHookNames} from '../lib/hook-discovery.mjs';+import {loadDocs} from '../lib/component-loader.mjs';+import {levenshteinDistance} from '../lib/string-utils.mjs';+import {XDSError} from './error.mjs';++/**+ * @param {string} [name]+ * @param {object} [options]+ * @param {string} [options.cwd]+ * @param {boolean} [options.list]+ * @param {string} [options.category]+ * @param {boolean} [options.params]+ * @param {'full'|'compact'|'brief'} [options.detail]+ * @param {string} [options.lang]+ * @param {boolean} [options.zh]+ * @returns {Promise<{type: string, data: unknown}>}+ */+export async function hook(name, options = {}) {+ const {+ cwd = process.cwd(),+ list = false,+ category,+ params = false,+ detail = 'full',+ lang = null,+ zh = false,+ } = options;++ const coreDir = findCoreDir(cwd);+ if (!coreDir) {+ throw new XDSError('Could not find @xds/core package');+ }++ // ── List mode ──────────────────────────────────────────────────++ if (category || list || !name) {+ const hooks = discoverHooks(coreDir);++ if (category) {+ const match = Object.entries(hooks).find(+ ([key]) => key.toLowerCase() === category.toLowerCase(),+ );+ if (!match) {+ throw new XDSError(+ `Unknown category "${category}"`,+ Object.keys(hooks).map(k => ({name: k, reason: 'valid category'})),+ );+ }++ if (detail === 'brief') {+ const entries = [];+ for (const hookName of match[1]) {+ const docPath = findHookDoc(coreDir, hookName);+ if (docPath) {+ try {+ const docs = await loadDocs(docPath, {zh, lang});+ entries.push({+ name: hookName,+ description: docs.usage?.description || '',+ import: docs.importPath || '@xds/core/hooks',+ });+ } catch {+ entries.push({name: hookName, description: '', import: '@xds/core/hooks'});+ }+ } else {+ entries.push({name: hookName, description: '', import: '@xds/core/hooks'});+ }+ }+ return {type: 'hook.brief', data: {[match[0]]: entries}};+ }++ return {type: 'hook.list', data: {[match[0]]: match[1]}};+ }++ // All hooks+ if (detail === 'brief') {+ /** @type {Record<string, Array<{name: string, description: string, import: string}>>} */+ const result = {};+ for (const [cat, hookNames] of Object.entries(hooks)) {+ result[cat] = [];+ for (const hookName of hookNames) {+ const docPath = findHookDoc(coreDir, hookName);+ if (docPath) {+ try {+ const docs = await loadDocs(docPath, {zh, lang});+ result[cat].push({+ name: hookName,+ description: docs.usage?.description || '',+ import: docs.importPath || '@xds/core/hooks',+ });+ } catch {+ result[cat].push({name: hookName, description: '', import: '@xds/core/hooks'});+ }+ } else {+ result[cat].push({name: hookName, description: '', import: '@xds/core/hooks'});+ }+ }+ }+ return {type: 'hook.brief', data: result};+ }++ return {type: 'hook.list', data: hooks};+ }++ // ── Single hook ────────────────────────────────────────────────++ const docPath = findHookDoc(coreDir, name);++ if (!docPath) {+ // Fuzzy search for suggestions+ const allNames = getAllHookNames(coreDir);+ const needle = name.toLowerCase();+ const suggestions = allNames+ .map(hookName => ({+ name: hookName,+ distance: levenshteinDistance(needle, hookName.toLowerCase()),+ }))+ .filter(m => m.distance <= 5)+ .sort((a, b) => a.distance - b.distance)+ .slice(0, 5)+ .map(m => ({name: m.name, reason: `similar name (distance ${m.distance})`}));++ throw new XDSError(+ `No hook named "${name}"`,+ suggestions,+ );+ }++ const docs = await loadDocs(docPath, {zh, lang});++ if (params) {+ return {type: 'hook.detail.params', data: docs.params || []};+ }++ return {type: 'hook.detail', data: docs};+}diff --git a/packages/cli/src/commands/agent-docs.mjs b/packages/cli/src/commands/agent-docs.mjsindex 8ba185ed80..98bcca6b18 100644--- a/packages/cli/src/commands/agent-docs.mjs+++ b/packages/cli/src/commands/agent-docs.mjs@@ -20,6 +20,7 @@ import * as path from 'node:path';import {findCoreDir, CLI_ROOT} from '../utils/paths.mjs';import {getRunPrefix} from '../utils/package-manager.mjs';import {discoverComponents} from '../lib/component-discovery.mjs';+import {discoverHooks} from '../lib/hook-discovery.mjs';const AGENTS_MD = 'AGENTS.md';const CLAUDE_MD = 'CLAUDE.md';diff --git a/packages/cli/src/commands/hook/index.mjs b/packages/cli/src/commands/hook/index.mjsnew file mode 100644index 0000000000..0ff365fd79--- /dev/null+++ b/packages/cli/src/commands/hook/index.mjs@@ -0,0 +1,148 @@+/**+ * @file hook command — List hooks and print hook docs+ *+ * Global options: --detail full|compact|brief, --lang en|zh+ */++import {findCoreDir} from '../../utils/paths.mjs';+import {discoverHooks, findHookDoc} from '../../lib/hook-discovery.mjs';+import {loadDocs} from '../../lib/component-loader.mjs';+import {+ formatHookFull,+ formatHookCompact,+ formatHookBrief,+ formatHookBriefAll,+ formatHookParams,+} from '../../lib/hook-format.mjs';+import {getRunPrefix} from '../../utils/package-manager.mjs';+import {jsonOut, jsonError} from '../../lib/json.mjs';+import {hook as hookApi} from '../../api/hook.mjs';+import {findRelatedBlocks} from '../../api/template.mjs';++export function registerHook(program) {+ program+ .command('hook [name]')+ .description('List hooks or print hook docs')+ .option('--list', 'List all hooks grouped by category')+ .option('--category <category>', 'List hooks in a specific category')+ .option('--params', 'Print only the parameters table')+ .action(async (name, options) => {+ const run = getRunPrefix();+ const zh = program.opts().zh || false;+ const lang = program.opts().lang || null;+ const detail = program.opts().detail || 'full';+ const json = program.opts().json || false;++ const validDetails = ['full', 'compact', 'brief'];+ if (!validDetails.includes(detail)) {+ if (json) return jsonError(`Invalid --detail value "${detail}". Valid levels: ${validDetails.join(', ')}`);+ console.error(`Error: Invalid --detail value "${detail}".`);+ console.error(`Valid levels: ${validDetails.join(', ')}`);+ process.exit(1);+ }++ let result;+ try {+ result = await hookApi(name, {+ cwd: process.cwd(),+ list: options.list,+ category: options.category,+ params: options.params,+ detail,+ lang, zh,+ });+ } catch (e) {+ if (json) return jsonError(e.message, e.suggestions);+ console.error(`Error: ${e.message}`);+ if (e.suggestions?.length) {+ console.error('');+ for (const s of e.suggestions) {+ console.error(` ${s.name} (${s.reason})`);+ }+ }+ process.exit(1);+ }++ if (json) return jsonOut(result.type, result.data);++ // ── Text output ────────────────────────────────────────────+ const coreDir = findCoreDir(process.cwd());++ switch (result.type) {+ case 'hook.list': {+ if (options.category) {+ const [cat, hookNames] = Object.entries(result.data)[0];+ console.log(`\n${cat}:`);+ for (const h of hookNames) console.log(` ${h}`);+ console.log('');+ } else {+ console.log('');+ for (const [category, hookNames] of Object.entries(result.data)) {+ console.log(category);+ for (const h of hookNames) console.log(` ${h}`);+ }+ console.log('');+ console.log(`Usage: ${run} xds hook <name>`);+ console.log('');+ }+ break;+ }++ case 'hook.brief': {+ if (options.category || options.list || !name) {+ console.log(await formatHookBriefAll(coreDir));+ } else {+ console.log(formatHookBrief(result.data));+ }+ break;+ }++ case 'hook.detail': {+ if (detail === 'brief') {+ console.log(formatHookBrief(result.data));+ } else if (detail === 'compact') {+ const importPath = result.data.importPath || '@xds/core/hooks';+ console.log(formatHookCompact(result.data, importPath));+ } else {+ console.log(formatHookFull(result.data));+ }+ // Show related block templates from relatedComponents+ const relatedComps = result.data.relatedComponents || [];+ const allBlocks = [];+ for (const comp of relatedComps) {+ const blocks = await findRelatedBlocks(comp);+ for (const b of blocks) {+ if (!allBlocks.some(existing => existing.dirName === b.dirName)) {+ allBlocks.push(b);+ }+ }+ }+ if (allBlocks.length > 0) {+ console.log('\nRelated block templates:\n');+ for (const b of allBlocks) {+ console.log(` ${b.dirName}`);+ if (b.description) console.log(` ${b.description}`);+ }+ console.log('');+ }+ break;+ }++ case 'hook.detail.params': {+ console.log(formatHookParams({params: result.data, name: name}));+ break;+ }+ }+ });+}++// Re-export lib functions for external consumers+export {discoverHooks, findHookDoc, getAllHookNames} from '../../lib/hook-discovery.mjs';+export {loadDocs} from '../../lib/component-loader.mjs';+export {+ formatHookFull,+ formatHookCompact,+ formatHookBrief,+ formatHookBriefAll,+ formatHookParams,+} from '../../lib/hook-format.mjs';diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjsindex 538fb38b72..b834416b77 100644--- a/packages/cli/src/index.mjs+++ b/packages/cli/src/index.mjs@@ -88,6 +88,7 @@ const commands = [{name: 'gap-report', path: './commands/gap-report.mjs', register: 'registerGapReport'},{name: 'upgrade', path: './commands/upgrade.mjs', register: 'registerUpgrade'},{name: 'theme', path: './commands/build-theme.mjs', register: 'registerTheme'},+ {name: 'hook', path: './commands/hook/index.mjs', register: 'registerHook'},{name: 'discover', path: './commands/discover.mjs', register: 'registerDiscover'},];@@ -129,6 +130,7 @@ ${line('')}${line(' Or run directly:')}${line(` ${r} init Setup + AI agent docs`)}${line(` ${r} component Browse component docs`)}+${line(` ${r} hook Browse hook docs`)}${line(` ${r} docs Design system reference`)}${line(` ${r} swizzle Customize a component`)}${line(` ${r} template Add a page template`)}diff --git a/packages/cli/src/lib/hook-discovery.mjs b/packages/cli/src/lib/hook-discovery.mjsnew file mode 100644index 0000000000..f187c103ab--- /dev/null+++ b/packages/cli/src/lib/hook-discovery.mjs@@ -0,0 +1,226 @@+/**+ * @file Hook discovery — find, list, and resolve XDS hooks+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {levenshteinDistance} from './string-utils.mjs';++const SKIP_DIRS = new Set(['utils', '__tests__', 'node_modules']);++// Matches the top-level `category: 'categoryName'` field in a hook .doc.mjs file.+const CATEGORY_RE = /(?:^|\n) {0,4}category:\s*['"]([^'"]+)['"]/;++/**+ * Read the `category` field from a hook's .doc.mjs file (synchronous).+ */+function readHookMeta(docPath) {+ try {+ const content = fs.readFileSync(docPath, 'utf-8');+ const categoryMatch = CATEGORY_RE.exec(content);+ return {+ category: categoryMatch ? categoryMatch[1].charAt(0).toUpperCase() + categoryMatch[1].slice(1) : null,+ };+ } catch {+ return {category: null};+ }+}++/**+ * Extract the hook name from a doc filename.+ * e.g. 'useFocusTrap.doc.mjs' → 'useFocusTrap'+ */+function hookNameFromFile(fileName) {+ return fileName.replace('.doc.mjs', '');+}++/**+ * Discover all hooks that have .doc.mjs files.+ * Returns Record<category, hookName[]> similar to discoverComponents.+ * Categories from HookDoc.category: focus, layout, animation, interaction, data, media, streaming+ * Hooks without a category go in 'Other'.+ */+export function discoverHooks(coreDir) {+ const srcDir = path.join(coreDir, 'src');+ const hooksDir = path.join(srcDir, 'hooks');++ /** @type {Map<string, string>} hookName → category */+ const hookCategories = new Map();++ // 1. Scan src/hooks/ for *.doc.mjs files+ if (fs.existsSync(hooksDir)) {+ const entries = fs.readdirSync(hooksDir, {withFileTypes: true});+ for (const entry of entries) {+ if (!entry.isFile()) continue;+ if (!entry.name.endsWith('.doc.mjs')) continue;+ const hookName = hookNameFromFile(entry.name);+ const docPath = path.join(hooksDir, entry.name);+ const {category} = readHookMeta(docPath);+ hookCategories.set(hookName, category || 'Other');+ }+ }++ // 2. Scan ALL component directories for files matching use*.doc.mjs+ if (fs.existsSync(srcDir)) {+ const topEntries = fs.readdirSync(srcDir, {withFileTypes: true});+ for (const entry of topEntries) {+ if (!entry.isDirectory() || SKIP_DIRS.has(entry.name) || entry.name === 'hooks') continue;+ const dirPath = path.join(srcDir, entry.name);+ scanDirForHookDocs(dirPath, hookCategories);+ }+ }++ // 3. Group by category, sorted alphabetically+ /** @type {Map<string, string[]>} */+ const groups = new Map();+ for (const [hookName, category] of hookCategories) {+ if (!groups.has(category)) groups.set(category, []);+ groups.get(category).push(hookName);+ }++ // Sort members within each group+ for (const members of groups.values()) {+ members.sort();+ }++ // Sort groups alphabetically, but 'Other' goes last+ const sortedEntries = Array.from(groups.entries()).sort((a, b) => {+ if (a[0] === 'Other') return 1;+ if (b[0] === 'Other') return -1;+ return a[0].localeCompare(b[0]);+ });++ /** @type {Record<string, string[]>} */+ const ordered = {};+ for (const [key, values] of sortedEntries) {+ ordered[key] = values;+ }++ return ordered;+}++/**+ * Recursively scan a directory for use*.doc.mjs files.+ */+function scanDirForHookDocs(dirPath, hookCategories) {+ if (!fs.existsSync(dirPath)) return;+ const entries = fs.readdirSync(dirPath, {withFileTypes: true});+ for (const entry of entries) {+ if (entry.isDirectory() && !SKIP_DIRS.has(entry.name)) {+ scanDirForHookDocs(path.join(dirPath, entry.name), hookCategories);+ } else if (+ entry.isFile() &&+ entry.name.startsWith('use') &&+ entry.name.endsWith('.doc.mjs')+ ) {+ const hookName = hookNameFromFile(entry.name);+ if (!hookCategories.has(hookName)) {+ const docPath = path.join(dirPath, entry.name);+ const {category} = readHookMeta(docPath);+ hookCategories.set(hookName, category || 'Other');+ }+ }+ }+}++/**+ * Find the .doc.mjs file for a hook by name.+ * Searches hooks/ directory and component directories.+ * Matches both exact name and with 'use' prefix stripped.+ *+ * @param {string} coreDir+ * @param {string} name - Hook name (e.g. 'useMediaQuery', 'MediaQuery', 'mediaquery')+ * @returns {string|null} Path to the .doc.mjs file, or null+ */+export function findHookDoc(coreDir, name) {+ const srcDir = path.join(coreDir, 'src');+ const hooksDir = path.join(srcDir, 'hooks');++ // Normalize: ensure we have both 'useFoo' and 'Foo' variants+ const normalized = name.replace(/^use/, '');+ const withUse = 'use' + normalized.charAt(0).toUpperCase() + normalized.slice(1);+ const candidates = [name, withUse, 'use' + normalized];++ // Deduplicate candidates+ const uniqueCandidates = [...new Set(candidates)];++ // 1. Check src/hooks/{name}.doc.mjs first+ for (const candidate of uniqueCandidates) {+ const direct = path.join(hooksDir, `${candidate}.doc.mjs`);+ if (fs.existsSync(direct)) return direct;+ }++ // 2. Case-insensitive search in hooks directory+ if (fs.existsSync(hooksDir)) {+ const entries = fs.readdirSync(hooksDir);+ for (const entry of entries) {+ if (!entry.endsWith('.doc.mjs')) continue;+ const hookName = hookNameFromFile(entry);+ if (hookName.toLowerCase() === name.toLowerCase() ||+ hookName.toLowerCase() === withUse.toLowerCase()) {+ return path.join(hooksDir, entry);+ }+ }+ }++ // 3. Check all component dirs for {name}.doc.mjs or use{Name}.doc.mjs+ if (fs.existsSync(srcDir)) {+ const topEntries = fs.readdirSync(srcDir, {withFileTypes: true});+ for (const entry of topEntries) {+ if (!entry.isDirectory() || SKIP_DIRS.has(entry.name) || entry.name === 'hooks') continue;+ const found = searchDirForHookDoc(path.join(srcDir, entry.name), uniqueCandidates);+ if (found) return found;+ }+ }++ // 4. Fuzzy fallback: levenshtein distance on discovered hooks+ const allHooks = discoverHooks(coreDir);+ const allNames = Object.values(allHooks).flat();+ const needle = name.toLowerCase();++ let bestMatch = null;+ let bestDist = Infinity;+ for (const hookName of allNames) {+ const dist = levenshteinDistance(needle, hookName.toLowerCase());+ if (dist < bestDist) {+ bestDist = dist;+ bestMatch = hookName;+ }+ }++ if (bestMatch && bestDist <= 3) {+ return findHookDoc(coreDir, bestMatch);+ }++ return null;+}++/**+ * Recursively search a directory for a hook doc matching any of the candidate names.+ */+function searchDirForHookDoc(dirPath, candidates) {+ if (!fs.existsSync(dirPath)) return null;+ const entries = fs.readdirSync(dirPath, {withFileTypes: true});+ for (const entry of entries) {+ if (entry.isDirectory() && !SKIP_DIRS.has(entry.name)) {+ const found = searchDirForHookDoc(path.join(dirPath, entry.name), candidates);+ if (found) return found;+ } else if (entry.isFile() && entry.name.endsWith('.doc.mjs')) {+ const hookName = hookNameFromFile(entry.name);+ for (const candidate of candidates) {+ if (hookName === candidate || hookName.toLowerCase() === candidate.toLowerCase()) {+ return path.join(dirPath, entry.name);+ }+ }+ }+ }+ return null;+}++/**+ * Get all discovered hook names as a flat array (for fuzzy matching).+ */+export function getAllHookNames(coreDir) {+ const hooks = discoverHooks(coreDir);+ return Object.values(hooks).flat();+}diff --git a/packages/cli/src/lib/hook-format.mjs b/packages/cli/src/lib/hook-format.mjsnew file mode 100644index 0000000000..d0ffaed0d7--- /dev/null+++ b/packages/cli/src/lib/hook-format.mjs@@ -0,0 +1,245 @@+/**+ * @file Hook doc formatting — render HookDoc objects to text+ *+ * Mirrors component-format.mjs conventions:+ * - Full: markdown with ## sections, tables, best practices+ * - Compact: markdown with import block, params table, abbreviated practices+ * - Brief: signature line with import hint, description, key params+ */++import {discoverHooks, findHookDoc} from './hook-discovery.mjs';+import {loadDocs} from './component-loader.mjs';++/**+ * Build a signature string from hook docs.+ * e.g. 'useFocusTrap(options: UseFocusTrapOptions): { containerRef, focusFirst }'+ */+function buildSignature(docs) {+ const name = docs.name;++ // Build params string — only top-level params (skip options.foo nested params)+ const topParams = (docs.params || []).filter(p => !p.name.includes('.'));+ const paramStr = topParams+ .map(p => {+ const opt = p.required ? '' : '?';+ return `${p.name}${opt}: ${p.type}`;+ })+ .join(', ');++ // Build return type+ const returns = docs.returns || [];+ let returnStr;+ if (returns.length === 0) {+ returnStr = 'void';+ } else if (returns.length === 1 && returns[0].name === 'value') {+ returnStr = returns[0].type;+ } else {+ returnStr = `{ ${returns.map(r => r.name).join(', ')} }`;+ }++ return `${name}(${paramStr}): ${returnStr}`;+}++/**+ * Format a parameters table (matches component props table style).+ */+function formatParamsTable(params) {+ if (!params || params.length === 0) return '';+ const lines = [];+ lines.push('| Param | Type | Default | Description |');+ lines.push('|-------|------|---------|-------------|');+ for (const p of params) {+ const def = p.default ? `\`${p.default}\`` : '\u2014';+ const req = p.required ? ' **(required)**' : '';+ lines.push(`| \`${p.name}\` | \`${p.type}\` | ${def} | ${p.description}${req} |`);+ }+ return lines.join('\n');+}++/**+ * Format a returns table.+ */+function formatReturnsTable(returns) {+ if (!returns || returns.length === 0) return '';+ const lines = [];+ lines.push('| Field | Type | Description |');+ lines.push('|-------|------|-------------|');+ for (const r of returns) {+ lines.push(`| \`${r.name}\` | \`${r.type}\` | ${r.description} |`);+ }+ return lines.join('\n');+}++/**+ * Format full hook docs (default mode).+ * Matches component formatFull structure:+ * # Name, description, anatomy→params, best practices, props→params+returns, theming→related+ */+export function formatHookFull(docs) {+ const sections = [];++ sections.push(`# ${docs.name}\n`);++ const desc = docs.usage?.description || '';+ if (desc) sections.push(desc + '\n');++ // Best Practices (same position as component format)+ if (docs.usage?.bestPractices?.length) {+ sections.push('## Best Practices\n');+ for (const bp of docs.usage.bestPractices) {+ const badge = bp.guidance ? '**Do:**' : "**Don\'t:**";+ sections.push(`- ${badge} ${bp.description}`);+ }+ sections.push('');+ }++ // Parameters (analogous to ## Props)+ if (docs.params?.length) {+ sections.push('## Parameters\n');+ sections.push(formatParamsTable(docs.params) + '\n');+ }++ // Returns (hook-specific, no component equivalent)+ if (docs.returns?.length) {+ sections.push('## Returns\n');+ sections.push(formatReturnsTable(docs.returns) + '\n');+ }++ return sections.join('\n');+}++/**+ * Format compact hook docs for LLM consumption.+ * Matches component formatCompact structure:+ * # Name, description, ## Import, ## Best Practices, ## Parameters, ## Returns+ */+export function formatHookCompact(docs, importPath) {+ const sections = [];++ sections.push(`# ${docs.name}\n`);++ // Description+ const desc = docs.usage?.description || '';+ if (desc) sections.push(desc + '\n');++ // Import block (matches component compact)+ const imp = importPath || docs.importPath;+ if (imp) {+ sections.push('## Import\n');+ sections.push(`\`\`\`tsx\nimport { ${docs.name} } from '${imp}';\n\`\`\`\n`);+ }++ // Best Practices (matches component compact)+ if (docs.usage?.bestPractices?.length) {+ sections.push('## Best Practices\n');+ for (const bp of docs.usage.bestPractices) {+ const badge = bp.guidance ? '**Do:**' : "**Don\'t:**";+ sections.push(`- ${badge} ${bp.description}`);+ }+ sections.push('');+ }++ // Parameters (matches ## Props in component compact)+ if (docs.params?.length) {+ sections.push('## Parameters\n');+ sections.push(formatParamsTable(docs.params) + '\n');+ }++ // Returns+ if (docs.returns?.length) {+ sections.push('## Returns\n');+ sections.push(formatReturnsTable(docs.returns) + '\n');+ }++ // Related components (compact footer)+ const relatedParts = [];+ if (docs.relatedComponents?.length) {+ relatedParts.push(`Components: ${docs.relatedComponents.join(', ')}`);+ }+ if (docs.relatedHooks?.length) {+ relatedParts.push(`Hooks: ${docs.relatedHooks.join(', ')}`);+ }+ if (relatedParts.length) {+ sections.push('## Related\n');+ for (const part of relatedParts) sections.push(part);+ sections.push('');+ }++ return sections.join('\n');+}++/**+ * Format a brief, LLM-optimized hook summary.+ * Matches component formatBrief conventions:+ * signature ← from 'import/path'+ * description+ * key params+ */+export function formatHookBrief(docs) {+ const output = [];++ // Signature line with import hint (matches component brief)+ const sig = buildSignature(docs);+ const imp = docs.importPath;+ output.push(imp ? `${sig} \u2190 from '${imp}'` : sig);++ // Description (shortened, matches component brief)+ const desc = docs.usage?.description || '';+ if (desc) {+ const shortDesc = desc.length > 80 ? desc.slice(0, 77) + '...' : desc;+ output.push(` ${shortDesc}`);+ }++ // Related components (compact)+ if (docs.relatedComponents?.length) {+ output.push(` Related: ${docs.relatedComponents.join(', ')}`);+ }++ // Key params (matches component brief 'prop · prop' line)+ const paramNames = (docs.params || [])+ .filter(p => !p.name.includes('.'))+ .map(p => p.required ? `${p.name}: ${p.type.split('|')[0].trim()}` : p.name);+ if (paramNames.length > 0) {+ output.push(` ${paramNames.join(' \u00b7 ')}`);+ }++ return output.join('\n') + '\n';+}++/**+ * Format brief summaries for ALL hooks in one output.+ * Matches component formatBriefAll: group headers with ##.+ */+export async function formatHookBriefAll(coreDir) {+ const hooks = discoverHooks(coreDir);+ const output = [];++ for (const [category, hookNames] of Object.entries(hooks)) {+ output.push(`## ${category}\n`);+ for (const hookName of hookNames) {+ const docPath = findHookDoc(coreDir, hookName);+ if (docPath) {+ try {+ const docs = await loadDocs(docPath);+ output.push(formatHookBrief(docs));+ } catch {+ output.push(`${hookName}\n (no docs)\n`);+ }+ } else {+ output.push(`${hookName}\n (no docs)\n`);+ }+ }+ }++ return output.join('\n');+}++/**+ * Format only the parameters table (matches component formatProps).+ */+export function formatHookParams(docs) {+ if (docs.params?.length) {+ return `## Parameters\n\n${formatParamsTable(docs.params)}\n`;+ }+ return `No parameters documentation found for ${docs.name}.\n`;+}diff --git a/packages/core/docs.mjs b/packages/core/docs.mjsindex bea5ce68ec..716ccf14ec 100644--- a/packages/core/docs.mjs+++ b/packages/core/docs.mjs@@ -226,12 +226,174 @@ function formatBrief(docs) {// ── Main ─────────────────────────────────────────────────────────────++// ── Hook Support ─────────────────────────────────────────────────────++const HOOK_CATEGORY_MAP = {+ useFocusTrap: 'Focus',+ useGridFocus: 'Focus',+ useListFocus: 'Focus',+ useMediaQuery: 'Media',+ useOverflow: 'Layout',+ useScrollOverflow: 'Layout',+ useScrollLock: 'Layout',+ useEntryAnimation: 'Animation',+ useXDSStreamingText: 'Streaming',+ useImageMode: 'Media',+ useClickableContainer: 'Interaction',+ useInputContainer: 'Interaction',+};+const HOOK_CATEGORY_ORDER = ['Focus', 'Layout', 'Animation', 'Interaction', 'Media', 'Streaming', 'Other'];++function discoverHookDocs() {+ const results = [];+ const hooksDir = path.join(srcDir, 'hooks');+ if (fs.existsSync(hooksDir)) {+ for (const file of fs.readdirSync(hooksDir)) {+ if (file.endsWith('.doc.mjs')) {+ results.push({name: file.replace('.doc.mjs', ''), docPath: path.join(hooksDir, file)});+ }+ }+ }+ // Also scan component directories for use*.doc.mjs+ if (fs.existsSync(srcDir)) {+ for (const entry of fs.readdirSync(srcDir, {withFileTypes: true})) {+ if (!entry.isDirectory() || SKIP.has(entry.name)) continue;+ const dir = path.join(srcDir, entry.name);+ try {+ for (const file of fs.readdirSync(dir)) {+ if (file.startsWith('use') && file.endsWith('.doc.mjs')) {+ results.push({name: file.replace('.doc.mjs', ''), docPath: path.join(dir, file)});+ }+ }+ } catch {}+ }+ }+ return results;+}++function findHookDocByName(hookName) {+ const normalized = hookName.replace(/^use/i, '');+ const hooksDir = path.join(srcDir, 'hooks');++ // Direct match in hooks/+ for (const variant of [hookName, `use${normalized}`, `useXDS${normalized}`]) {+ const p = path.join(hooksDir, `${variant}.doc.mjs`);+ if (fs.existsSync(p)) return p;+ }++ // Search component directories+ if (fs.existsSync(srcDir)) {+ for (const entry of fs.readdirSync(srcDir, {withFileTypes: true})) {+ if (!entry.isDirectory() || SKIP.has(entry.name)) continue;+ const dir = path.join(srcDir, entry.name);+ for (const variant of [hookName, `use${normalized}`, `useXDS${normalized}`]) {+ const p = path.join(dir, `${variant}.doc.mjs`);+ if (fs.existsSync(p)) return p;+ }+ }+ }+ return null;+}++function formatHookParamsTable(params) {+ if (!params?.length) return '';+ const lines = ['| Param | Type | Default | Description |', '|-------|------|---------|-------------|'];+ for (const p of params) {+ const def = p.default ? `\`${p.default}\`` : '\u2014';+ const req = p.required ? ' **(required)**' : '';+ lines.push(`| \`${p.name}\` | \`${p.type}\` | ${def} | ${p.description}${req} |`);+ }+ return lines.join('\n');+}++function formatHookReturnsTable(returns) {+ if (!returns?.length) return '';+ const lines = ['| Field | Type | Description |', '|-------|------|-------------|'];+ for (const r of returns) {+ lines.push(`| \`${r.name}\` | \`${r.type}\` | ${r.description} |`);+ }+ return lines.join('\n');+}++function formatHookFull(docs) {+ const s = [];+ s.push(`# ${docs.name}\n`);+ s.push((docs.usage?.description || '') + '\n');++ if (docs.params?.length) {+ s.push('## Parameters\n');+ s.push(formatHookParamsTable(docs.params) + '\n');+ }++ if (docs.returns?.length) {+ s.push('## Returns\n');+ s.push(formatHookReturnsTable(docs.returns) + '\n');+ }++ if (docs.usage?.bestPractices?.length) {+ s.push('## Best Practices\n');+ for (const bp of docs.usage.bestPractices)+ s.push(`- ${bp.guidance ? '**Do:**' : "**Don't:**"} ${bp.description}`);+ s.push('');+ }++ const refs = [];+ if (docs.relatedComponents?.length) refs.push(`Components: ${docs.relatedComponents.map(c => `XDS${c}`).join(', ')}`);+ if (docs.relatedHooks?.length) refs.push(`Hooks: ${docs.relatedHooks.join(', ')}`);+ if (docs.importPath) refs.push(`Import: ${docs.importPath}`);+ if (refs.length) {+ s.push('## Related\n');+ for (const r of refs) s.push(r);+ s.push('');+ }++ return s.join('\n');+}++function formatHookBrief(docs) {+ const desc = docs.usage?.description || '';+ const short = desc.length > 80 ? desc.slice(0, 77) + '...' : desc;+ const params = (docs.params || []).filter(p => p.required).map(p => `${p.name}: ${p.type}`).join(', ');+ const ret = (docs.returns || []).map(r => r.type).join(' | ');+ const sig = params ? `${docs.name}(${params})` : docs.name;+ return ret ? `${sig}: ${ret} ${short}` : `${sig} ${short}`;+}++// ── Main ─────────────────────────────────────────────────────────────+const args = process.argv.slice(2);const isList = args.includes('--list');const isBrief = args.includes('--brief');+const isHooks = args.includes('--hooks');const name = args.find(a => !a.startsWith('--'));-if (isList) {+if (isHooks) {+ // Hook listing mode+ const hookDocs = discoverHookDocs();+ const grouped = {};+ for (const {name: hookName, docPath} of hookDocs) {+ const cat = HOOK_CATEGORY_MAP[hookName] || 'Other';+ if (!grouped[cat]) grouped[cat] = [];+ grouped[cat].push({name: hookName, docPath});+ }+ for (const cat of HOOK_CATEGORY_ORDER) {+ if (!grouped[cat]) continue;+ console.log(`\n${cat}:`);+ for (const {name: hookName, docPath} of grouped[cat]) {+ if (isBrief) {+ try {+ const d = await loadDoc(docPath);+ console.log(' ' + formatHookBrief(d));+ } catch {+ console.log(` ${hookName} (error loading docs)`);+ }+ } else {+ console.log(` ${hookName}`);+ }+ }+ }+} else if (isList) {const docs = discoverDocs();const grouped = {};for (const {dir, docPath} of docs) {@@ -256,16 +418,38 @@ if (isList) {}}} else if (name) {- const docPath = findDocByComponent(name);- if (!docPath) {- console.error(`Component "${name}" not found. Run with --list to see available components.`);- process.exit(1);+ // Try hook lookup first for names starting with 'use'+ if (name.startsWith('use') || name.startsWith('Use')) {+ const hookDocPath = findHookDocByName(name);+ if (hookDocPath) {+ const docs = await loadDoc(hookDocPath);+ console.log(formatHookFull(docs));+ } else {+ // Fall through to component lookup+ const docPath = findDocByComponent(name);+ if (!docPath) {+ console.error(`Hook or component "${name}" not found.`);+ console.error('Run with --list to see components, or --hooks to see hooks.');+ process.exit(1);+ }+ const docs = await loadDoc(docPath);+ console.log(formatFull(docs, docPath));+ }+ } else {+ const docPath = findDocByComponent(name);+ if (!docPath) {+ console.error(`Component "${name}" not found. Run with --list to see available components.`);+ process.exit(1);+ }+ const docs = await loadDoc(docPath);+ console.log(formatFull(docs, docPath));}- const docs = await loadDoc(docPath);- console.log(formatFull(docs, docPath));} else {console.log('Usage:');console.log(' node docs.mjs <ComponentName> Show full component docs');+ console.log(' node docs.mjs <hookName> Show full hook docs');console.log(' node docs.mjs --list List all components');console.log(' node docs.mjs --list --brief List with brief descriptions');+ console.log(' node docs.mjs --hooks List all hooks');+ console.log(' node docs.mjs --hooks --brief List hooks with brief descriptions');}diff --git a/packages/core/src/Collapsible/Collapsible.doc.mjs b/packages/core/src/Collapsible/Collapsible.doc.mjsindex c58194434f..ece891875f 100644--- a/packages/core/src/Collapsible/Collapsible.doc.mjs+++ b/packages/core/src/Collapsible/Collapsible.doc.mjs@@ -86,7 +86,7 @@ export const docs = {},],usage: {- description: 'Collapsible hides and reveals content behind a trigger button. Use it in settings panels, FAQ pages, or detail views to keep the page scannable while letting users drill into sections they care about. Wrap multiple collapsibles in XDSCollapsibleGroup for accordion behavior.',+ description: 'Collapsible hides and reveals content behind a trigger button. Use it in settings panels, FAQ pages, or detail views to keep the page scannable while letting users drill into sections they care about. Wrap multiple collapsibles in XDSCollapsibleGroup for accordion behavior. For custom collapsible components, use the `useXDSCollapsible` hook directly (`xds hook useXDSCollapsible`).',bestPractices: [{ guidance: true, description: 'Wrap each XDSCollapsible in an XDSCard for visual separation in accordion layouts.' },{ guidance: true, description: 'Use XDSCollapsibleGroup with type="single" for settings or FAQ pages where only one section should be open at a time.' },diff --git a/packages/core/src/Collapsible/useXDSCollapsible.doc.mjs b/packages/core/src/Collapsible/useXDSCollapsible.doc.mjsnew file mode 100644index 0000000000..c3837ec8af--- /dev/null+++ b/packages/core/src/Collapsible/useXDSCollapsible.doc.mjs@@ -0,0 +1,46 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useXDSCollapsible',+ keywords: ['collapsible', 'collapse', 'expand', 'toggle', 'accordion', 'disclosure', 'fold'],+ params: [+ {+ name: 'isCollapsible',+ type: "boolean | XDSCollapsibleConfig",+ description: 'Enable collapsible behavior. true = self-managed (starts open). Pass config object for controlled mode or custom defaults.',+ },+ {+ name: 'value',+ type: 'string',+ description: 'Unique identifier within an XDSCollapsibleGroup. When present and inside a group, state is managed by the group.',+ },+ ],+ returns: [+ {+ name: 'isEnabled',+ type: 'boolean',+ description: 'Whether collapsible behavior is active.',+ },+ {+ name: 'isOpen',+ type: 'boolean',+ description: 'Whether the content is currently expanded.',+ },+ {+ name: 'toggle',+ type: '() => void',+ description: 'Toggle open/closed state. Dispatches to group, controlled callback, or internal state.',+ },+ ],+ usage: {+ description: 'Reusable hook that encapsulates the collapsible state machine. Supports three modes: group-controlled (inside XDSCollapsibleGroup), controlled (isOpen + onOpenChange), and uncontrolled (self-managed with defaultIsOpen). Used internally by XDSCard and XDSSection.',+ bestPractices: [+ {guidance: true, description: 'Use the hook directly when building custom collapsible components that need XDS collapsible behavior without XDSCollapsible wrapper.'},+ {guidance: true, description: 'For accordion behavior, wrap items in XDSCollapsibleGroup and pass unique value props.'},+ {guidance: false, description: 'Implement your own open/close state when useXDSCollapsible already provides it — the hook handles group coordination automatically.'},+ ],+ },+ relatedComponents: ['Collapsible', 'Card', 'Section'],+ relatedHooks: [],+ importPath: '@xds/core/Collapsible',+ category: 'interaction',+};diff --git a/packages/core/src/HoverCard/useXDSHoverCard.doc.mjs b/packages/core/src/HoverCard/useXDSHoverCard.doc.mjsnew file mode 100644index 0000000000..56ae4a67b4--- /dev/null+++ b/packages/core/src/HoverCard/useXDSHoverCard.doc.mjs@@ -0,0 +1,65 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useXDSHoverCard',+ keywords: ['hovercard', 'hover', 'preview', 'card', 'tooltip', 'popup', 'floating', 'anchor'],+ params: [+ {+ name: 'content',+ type: 'ReactNode | ((props: ContextRenderProps) => ReactNode)',+ description: 'Content to display in the hover card. Can be a render function receiving layer props.',+ required: true,+ },+ {+ name: 'placement',+ type: 'LayerPlacement',+ description: 'Position relative to the trigger.',+ default: "'below'",+ },+ {+ name: 'alignment',+ type: 'LayerAlignment',+ description: 'Alignment along the placement axis.',+ default: "'center'",+ },+ {+ name: 'delayMs',+ type: 'number',+ description: 'Delay before showing the hover card on hover.',+ default: '300',+ },+ {+ name: 'onShow',+ type: '() => void',+ description: 'Callback fired when the hover card becomes visible.',+ },+ {+ name: 'onHide',+ type: '() => void',+ description: 'Callback fired when the hover card is hidden.',+ },+ ],+ returns: [+ {+ name: 'triggerProps',+ type: 'object',+ description: 'Props to spread on the trigger element (ref, event handlers).',+ },+ {+ name: 'layerNode',+ type: 'ReactNode',+ description: 'The hover card layer to render (include in JSX output).',+ },+ ],+ usage: {+ description: 'Headless hook for hover-triggered floating cards. Builds on useXDSLayer with hover/focus intent detection, delay, and safe triangle hover zones. Use for rich previews on hover without building the interaction logic.',+ bestPractices: [+ {guidance: true, description: 'Use for rich content previews (user profiles, link previews) that benefit from hover interaction.'},+ {guidance: true, description: 'Prefer the XDSHoverCard component for standard cases — use the hook when you need full control over rendering.'},+ {guidance: false, description: 'Use for simple text hints — use XDSTooltip or useXDSTooltip instead.'},+ ],+ },+ relatedComponents: ['HoverCard', 'Tooltip', 'Popover'],+ relatedHooks: ['useXDSLayer', 'useXDSTooltip', 'useXDSPopover'],+ importPath: '@xds/core/HoverCard',+ category: 'interaction',+};diff --git a/packages/core/src/Popover/useXDSPopover.doc.mjs b/packages/core/src/Popover/useXDSPopover.doc.mjsnew file mode 100644index 0000000000..8a6536d023--- /dev/null+++ b/packages/core/src/Popover/useXDSPopover.doc.mjs@@ -0,0 +1,86 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useXDSPopover',+ keywords: ['popover', 'popup', 'dropdown', 'floating', 'anchor', 'dialog', 'overlay', 'flyout'],+ params: [+ {+ name: 'content',+ type: 'ReactNode | ((props: ContextRenderProps) => ReactNode)',+ description: 'Content to display in the popover. Can be a render function receiving layer props.',+ required: true,+ },+ {+ name: 'placement',+ type: 'LayerPlacement',+ description: 'Position relative to the trigger.',+ default: "'below'",+ },+ {+ name: 'alignment',+ type: 'LayerAlignment',+ description: 'Alignment along the placement axis.',+ default: "'start'",+ },+ {+ name: 'hasLightDismiss',+ type: 'boolean',+ description: 'Whether clicking outside dismisses the popover.',+ default: 'true',+ },+ {+ name: 'hasSurface',+ type: 'boolean',+ description: 'Whether to apply the default popover surface styles (background, shadow, radius).',+ default: 'true',+ },+ {+ name: 'onShow',+ type: '() => void',+ description: 'Callback fired when the popover becomes visible.',+ },+ {+ name: 'onHide',+ type: '() => void',+ description: 'Callback fired when the popover is hidden.',+ },+ ],+ returns: [+ {+ name: 'triggerProps',+ type: 'object',+ description: 'Props to spread on the trigger element (ref, aria-expanded, event handlers).',+ },+ {+ name: 'layerNode',+ type: 'ReactNode',+ description: 'The popover layer to render (include in JSX output).',+ },+ {+ name: 'isOpen',+ type: 'boolean',+ description: 'Whether the popover is currently visible.',+ },+ {+ name: 'show',+ type: '() => void',+ description: 'Imperatively show the popover.',+ },+ {+ name: 'hide',+ type: '() => void',+ description: 'Imperatively hide the popover.',+ },+ ],+ usage: {+ description: 'Headless hook for click-triggered popovers with focus trapping. Combines useXDSLayer with useFocusTrap for dialog-like popover behavior. Use for interactive floating content that needs keyboard navigation.',+ bestPractices: [+ {guidance: true, description: 'Use for interactive content (forms, menus, pickers) that needs focus trapping and light dismiss.'},+ {guidance: true, description: 'Prefer the XDSPopover component for standard trigger-content pairs — use the hook for custom trigger patterns.'},+ {guidance: false, description: 'Use for non-interactive hover previews — use useXDSHoverCard or useXDSTooltip instead.'},+ ],+ },+ relatedComponents: ['Popover', 'DropdownMenu', 'HoverCard'],+ relatedHooks: ['useXDSLayer', 'useFocusTrap', 'useXDSHoverCard', 'useXDSTooltip'],+ importPath: '@xds/core/Popover',+ category: 'interaction',+};diff --git a/packages/core/src/Resizable/useXDSResizable.doc.mjs b/packages/core/src/Resizable/useXDSResizable.doc.mjsnew file mode 100644index 0000000000..3ec4b5f09a--- /dev/null+++ b/packages/core/src/Resizable/useXDSResizable.doc.mjs@@ -0,0 +1,84 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useXDSResizable',+ keywords: ['resize', 'resizable', 'drag', 'split', 'panel', 'sidebar', 'divider', 'splitter'],+ params: [+ {+ name: 'defaultSize',+ type: "number | string",+ description: 'Initial size in pixels or percentage string (e.g. "20%").',+ },+ {+ name: 'minSizePx',+ type: 'number',+ description: 'Minimum size in pixels.',+ default: '50',+ },+ {+ name: 'maxSizePx',+ type: 'number',+ description: 'Maximum size in pixels.',+ default: 'Infinity',+ },+ {+ name: 'collapsible',+ type: 'boolean',+ description: 'Whether dragging below the collapsed threshold collapses the region to zero.',+ default: 'false',+ },+ {+ name: 'snaps',+ type: 'number[]',+ description: 'Pixel values to snap to during drag.',+ },+ {+ name: 'autoSaveId',+ type: 'string',+ description: 'Key for localStorage persistence of size across sessions.',+ },+ ],+ returns: [+ {+ name: 'size',+ type: 'number',+ description: 'Current size in pixels.',+ },+ {+ name: 'isCollapsed',+ type: 'boolean',+ description: 'Whether the region is currently collapsed.',+ },+ {+ name: 'collapse',+ type: '() => void',+ description: 'Programmatically collapse the region.',+ },+ {+ name: 'expand',+ type: '() => void',+ description: 'Expand from collapsed state.',+ },+ {+ name: 'resize',+ type: '(size: number) => void',+ description: 'Resize to a specific pixel value.',+ },+ {+ name: 'props',+ type: 'ResizableProps',+ description: 'Props to spread on the resizable component or pass to XDSResizeHandle.',+ },+ ],+ usage: {+ description: 'Hook for adding drag-to-resize behavior to layout regions. Supports single-region and multi-region configurations with snap points, collapsible panels, localStorage persistence, and cascade resize ordering.',+ bestPractices: [+ {guidance: true, description: 'Use with XDSLayout or XDSAppShell sidebar for resizable navigation panels.'},+ {guidance: true, description: 'Set autoSaveId to persist user-chosen sizes across page reloads.'},+ {guidance: false, description: 'Set minSizePx too small — content becomes unreadable. Prefer collapsible for panels that can hide entirely.'},+ ],+ },+ relatedComponents: ['Resizable', 'AppShell', 'Layout', 'SideNav'],+ relatedHooks: ['useXDSCollapsible'],+ importPath: '@xds/core/Resizable',+ category: 'layout',+};diff --git a/packages/core/src/Toast/useXDSToast.doc.mjs b/packages/core/src/Toast/useXDSToast.doc.mjsnew file mode 100644index 0000000000..a4b9814cb4--- /dev/null+++ b/packages/core/src/Toast/useXDSToast.doc.mjs@@ -0,0 +1,28 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useXDSToast',+ keywords: ['toast', 'notification', 'snackbar', 'alert', 'message', 'feedback', 'flash'],+ params: [+ // useXDSToast takes no arguments — returns a show function+ ],+ returns: [+ {+ name: 'showToast',+ type: '(options: XDSToastOptions) => () => void',+ description: 'Show a toast notification. Returns a dismiss function. Options include body (ReactNode), type ("info" | "error"), isAutoHide, autoHideDuration, endContent, uniqueID, and collisionBehavior.',+ },+ ],+ usage: {+ description: 'Hook for showing toast notifications from anywhere in your component tree. Returns a function that accepts toast options and shows the notification. Works automatically with XDSLayerProvider or self-mounts a fallback viewport.',+ bestPractices: [+ {guidance: true, description: 'Use for transient success/error feedback that does not require user action.'},+ {guidance: true, description: 'Set uniqueID to deduplicate toasts from rapid user actions.'},+ {guidance: false, description: 'Use for critical errors that require acknowledgment — use AlertDialog instead.'},+ {guidance: false, description: 'Call useXDSToast in the same component that renders XDSLayerProvider — it must be called from a child component inside the provider.'},+ ],+ },+ relatedComponents: ['Toast', 'Banner', 'AlertDialog'],+ relatedHooks: [],+ importPath: '@xds/core/Toast',+ category: 'interaction',+};diff --git a/packages/core/src/Tooltip/useXDSTooltip.doc.mjs b/packages/core/src/Tooltip/useXDSTooltip.doc.mjsnew file mode 100644index 0000000000..c361a74214--- /dev/null+++ b/packages/core/src/Tooltip/useXDSTooltip.doc.mjs@@ -0,0 +1,55 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useXDSTooltip',+ keywords: ['tooltip', 'hint', 'label', 'hover', 'info', 'title', 'floating'],+ params: [+ {+ name: 'content',+ type: 'ReactNode',+ description: 'Text or content to display in the tooltip.',+ required: true,+ },+ {+ name: 'placement',+ type: 'LayerPlacement',+ description: 'Position relative to the trigger.',+ default: "'above'",+ },+ {+ name: 'alignment',+ type: 'LayerAlignment',+ description: 'Alignment along the placement axis.',+ default: "'center'",+ },+ {+ name: 'delayMs',+ type: 'number',+ description: 'Delay before showing the tooltip on hover.',+ default: '300',+ },+ ],+ returns: [+ {+ name: 'triggerProps',+ type: 'object',+ description: 'Props to spread on the trigger element (ref, aria-describedby, event handlers).',+ },+ {+ name: 'layerNode',+ type: 'ReactNode',+ description: 'The tooltip layer to render (include in JSX output).',+ },+ ],+ usage: {+ description: 'Headless hook for hover/focus-triggered tooltips. Builds on useXDSLayer with hover intent, delay, and accessible aria-describedby linking. Use for custom trigger elements that need tooltip behavior.',+ bestPractices: [+ {guidance: true, description: 'Use for brief text labels that describe a UI element — icon buttons, truncated text, abbreviations.'},+ {guidance: true, description: 'Prefer the XDSTooltip component for standard wrapping — use the hook when the trigger is not a simple child.'},+ {guidance: false, description: 'Put interactive content (links, buttons) inside tooltips — use Popover or HoverCard instead.'},+ ],+ },+ relatedComponents: ['Tooltip', 'HoverCard', 'Popover'],+ relatedHooks: ['useXDSLayer', 'useXDSHoverCard', 'useXDSPopover'],+ importPath: '@xds/core/Tooltip',+ category: 'interaction',+};diff --git a/packages/core/src/docs-types.ts b/packages/core/src/docs-types.tsindex 5c80e47e8b..d39db54920 100644--- a/packages/core/src/docs-types.ts+++ b/packages/core/src/docs-types.ts@@ -615,3 +615,98 @@ export interface GroupDoc {* Shown in the sidebar, catalog, or group landing page. */description: string;}++// =============================================================================+// Hook Documentation Types+// =============================================================================++/**+ * Documents a hook parameter/option. Similar to PropDoc but for hook+ * arguments and options object fields.+ */+export interface HookParamDoc {+ /** Parameter or option field name. */+ name: string;+ /** TypeScript type signature as a string. */+ type: string;+ /** What this parameter does. 1-2 sentences. */+ description: string;+ /** Default value as a string, if optional with a default. */+ default?: string;+ /** True if required. Omit if optional. */+ required?: boolean;+}++/**+ * Documents a hook's return value field.+ */+export interface HookReturnDoc {+ /** Field name on the returned object, or 'value' for primitive returns. */+ name: string;+ /** TypeScript type. */+ type: string;+ /** What this return value provides. */+ description: string;+}++/**+ * Documentation for a standalone hook's .doc.mjs file.+ *+ * Hooks that are part of a component's API (e.g. useXDSImperativeDialog)+ * should be documented in the component's MultiComponentDoc.components array.+ *+ * Standalone hooks (e.g. useMediaQuery, useFocusTrap, useOverflow) get+ * their own {hookName}.doc.mjs file and use this type.+ *+ * Every hook .doc.mjs must export a single `docs` constant:+ *+ * /\*\* @type {import('../docs-types').HookDoc} \*\/+ * export const docs = { ... };+ */+export interface HookDoc {+ /** Hook name exactly as exported, e.g. 'useMediaQuery', 'useFocusTrap'. */+ name: string;+ /** Search keywords for CLI discovery. */+ keywords?: string[];+ /** Hook parameters or options object fields. */+ params: HookParamDoc[];+ /** Return value documentation. For object returns, list each field.+ * For primitive returns, use a single entry. */+ returns: HookReturnDoc[];+ /** Usage documentation — description, best practices. */+ usage: UsageDoc;+ /** Component names this hook is commonly used with.+ * Enables cross-referencing: \`xds component Toast\` can mention useXDSToast,+ * and \`xds hook useXDSToast\` can link back to Toast. */+ relatedComponents?: string[];+ /** Other hook names this hook is commonly used with. */+ relatedHooks?: string[];+ /** Import path, e.g. '@xds/core/hooks' or '@xds/core/Toast'. */+ importPath?: string;+ /** Category for grouping in listings. */+ category?:+ | 'focus'+ | 'layout'+ | 'animation'+ | 'interaction'+ | 'data'+ | 'media'+ | 'streaming';+}++/**+ * Translation overlay for hook documentation.+ */+export interface HookTranslationDoc {+ /** Compressed/translated description. */+ description?: string;+ /** Param descriptions keyed by param name. */+ paramDescriptions?: Record<string, string>;+ /** Return descriptions keyed by field name. */+ returnDescriptions?: Record<string, string>;+ /** Translated usage. */+ usage?: {+ description?: string;+ bestPractices?: BestPractice[];+ };+}diff --git a/packages/core/src/hooks/useClickableContainer.doc.mjs b/packages/core/src/hooks/useClickableContainer.doc.mjsnew file mode 100644index 0000000000..e1392c111f--- /dev/null+++ b/packages/core/src/hooks/useClickableContainer.doc.mjs@@ -0,0 +1,75 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useClickableContainer',+ keywords: ['click', 'container', 'card', 'pressable', 'interactive', 'nested', 'link', 'button', 'delegate'],+ params: [+ {+ name: 'options',+ type: 'UseClickableContainerOptions',+ description: 'Configuration object for the clickable container.',+ required: true,+ },+ {+ name: 'options.containerRef',+ type: 'RefObject<HTMLElement | null>',+ description: 'Ref to the outer container element.',+ required: true,+ },+ {+ name: 'options.interactiveRef',+ type: 'RefObject<HTMLElement | null>',+ description: 'Ref to the primary interactive element inside (link, button). If no onClick or href is provided, clicks are proxied to this element.',+ required: false,+ },+ {+ name: 'options.onClick',+ type: '(event: MouseEvent<HTMLElement>) => void',+ description: 'Click handler fired when the container surface (not a nested interactive element) is clicked.',+ required: false,+ },+ {+ name: 'options.href',+ type: 'string',+ description: 'Navigation URL. When provided, clicking the container navigates to this URL.',+ required: false,+ },+ {+ name: 'options.target',+ type: 'string',+ description: "Link target (e.g., '_blank'). Used with href for navigation behavior.",+ required: false,+ },+ {+ name: 'options.disabled',+ type: 'boolean',+ description: 'Whether the container is disabled.',+ default: 'false',+ required: false,+ },+ ],+ returns: [+ {+ name: 'onClick',+ type: '(event: MouseEvent<HTMLElement>) => void',+ description: 'Click handler to attach to the container element.',+ },+ {+ name: 'onMouseUp',+ type: '(event: MouseEvent<HTMLElement>) => void',+ description: 'Mouse up handler to attach to the container (handles middle-click navigation for href).',+ },+ ],+ usage: {+ description:+ 'Makes a container element clickable while preserving nested interactive element behavior. Solves the "nested interactive elements" problem: when a card is clickable but contains buttons/links, clicking those should NOT trigger the card\'s action. Detects interactive ancestors between the click target and the container, and ignores text selections. Supports href navigation (including middle-click and Ctrl/Cmd+click for new tabs).',+ bestPractices: [+ { guidance: true, description: 'Attach both onClick and onMouseUp to the container element for full click handling including middle-click.' },+ { guidance: true, description: 'Use inside XDSClickableCard or XDSSelectableCard for the standard card interaction pattern.' },+ { guidance: false, description: 'Use when the entire container is a single interactive element — just use a <button> or <a> directly.' },+ ],+ },+ relatedComponents: ['ClickableCard', 'SelectableCard'],+ relatedHooks: ['useInputContainer'],+ importPath: '@xds/core/hooks',+ category: 'interaction',+};diff --git a/packages/core/src/hooks/useEntryAnimation.doc.mjs b/packages/core/src/hooks/useEntryAnimation.doc.mjsnew file mode 100644index 0000000000..d944a76a14--- /dev/null+++ b/packages/core/src/hooks/useEntryAnimation.doc.mjs@@ -0,0 +1,34 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useEntryAnimation',+ keywords: ['animation', 'entry', 'mount', 'transition', 'slide', 'fade', 'scale', 'motion', 'stylex'],+ params: [+ {+ name: 'preset',+ type: "'slideDown' | 'slideUp' | 'fadeIn' | 'scaleIn'",+ description: 'Animation preset to apply on mount.',+ default: "'slideDown'",+ required: false,+ },+ ],+ returns: [+ {+ name: 'entryStyle',+ type: 'StyleXStyles | null',+ description: 'A StyleX style object for the entry animation, or null if the element was rendered on initial page load (no animation needed).',+ },+ ],+ usage: {+ description:+ 'Returns a StyleX style for animating an element on mount. Only animates when the element is dynamically inserted after the initial page paint — elements rendered on page load are not animated. Uses XDS motion tokens (duration, easing) for consistent animation timing. Requires "use client" — does not support SSR.',+ bestPractices: [+ { guidance: true, description: 'Use for conditionally rendered elements like validation messages, toasts, or expanding sections.' },+ { guidance: true, description: 'Spread the returned style into stylex.props() alongside other styles.' },+ { guidance: false, description: 'Use for elements that should be visible on initial page load — they will not animate.' },+ ],+ },+ relatedComponents: ['FieldStatus'],+ relatedHooks: [],+ importPath: '@xds/core/hooks',+ category: 'animation',+};diff --git a/packages/core/src/hooks/useFocusTrap.doc.mjs b/packages/core/src/hooks/useFocusTrap.doc.mjsnew file mode 100644index 0000000000..a0c81afd45--- /dev/null+++ b/packages/core/src/hooks/useFocusTrap.doc.mjs@@ -0,0 +1,50 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useFocusTrap',+ keywords: ['focus', 'trap', 'modal', 'dialog', 'accessibility', 'a11y', 'keyboard', 'tab', 'escape', 'wai-aria'],+ params: [+ {+ name: 'options',+ type: 'UseFocusTrapOptions',+ description: 'Configuration object for the focus trap.',+ required: true,+ },+ {+ name: 'options.isActive',+ type: 'boolean',+ description: 'Whether the focus trap is currently active.',+ required: true,+ },+ {+ name: 'options.onEscape',+ type: '() => void',+ description: 'Callback when Escape key is pressed inside the trapped container.',+ required: false,+ },+ ],+ returns: [+ {+ name: 'containerRef',+ type: 'React.RefObject<HTMLElement | null>',+ description: 'Ref to attach to the container element that should trap focus.',+ },+ {+ name: 'focusFirst',+ type: '() => void',+ description: 'Focuses the first focusable element inside the container.',+ },+ ],+ usage: {+ description:+ 'Traps focus within a container element following the WAI-ARIA dialog focus trap pattern. Listens to focus events on the document and redirects focus back into the container if it escapes via keyboard navigation. Handles both Tab and Shift+Tab wrapping. Mouse clicks outside the container are not intercepted — use a light-dismiss handler for that.',+ bestPractices: [+ { guidance: true, description: 'Call focusFirst() when opening a dialog/modal to move focus into the trapped region.' },+ { guidance: true, description: 'Provide an onEscape callback to close the dialog when Escape is pressed.' },+ { guidance: false, description: 'Use on non-modal content like tooltips or dropdowns — those need light-dismiss, not focus trapping.' },+ ],+ },+ relatedComponents: ['Dialog', 'DatePicker'],+ relatedHooks: ['useListFocus', 'useScrollLock'],+ importPath: '@xds/core/hooks',+ category: 'focus',+};diff --git a/packages/core/src/hooks/useGridFocus.doc.mjs b/packages/core/src/hooks/useGridFocus.doc.mjsnew file mode 100644index 0000000000..b26684c156--- /dev/null+++ b/packages/core/src/hooks/useGridFocus.doc.mjs@@ -0,0 +1,90 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useGridFocus',+ keywords: ['grid', 'focus', 'keyboard', 'navigation', 'arrow', 'calendar', 'a11y', 'wai-aria', 'cells'],+ params: [+ {+ name: 'options',+ type: 'UseGridFocusOptions',+ description: 'Configuration object for grid focus behavior.',+ required: true,+ },+ {+ name: 'options.columns',+ type: 'number',+ description: 'Number of columns in the grid. Used for up/down navigation (moves by this many cells).',+ required: true,+ },+ {+ name: 'options.cellSelector',+ type: 'string',+ description: 'Selector for focusable cells within the grid.',+ default: "'button:not([disabled]), [tabindex]:not([tabindex=\"-1\"])'",+ required: false,+ },+ {+ name: 'options.onNavigateBefore',+ type: '(column: number, offset: number) => void',+ description: 'Callback when navigation would go before the first cell. Receives the column index and offset (1 for horizontal, columns for vertical).',+ required: false,+ },+ {+ name: 'options.onNavigateAfter',+ type: '(column: number, offset: number) => void',+ description: 'Callback when navigation would go after the last cell. Receives the column index and offset.',+ required: false,+ },+ {+ name: 'options.onPageUp',+ type: '() => void',+ description: 'Callback for Page Up key (e.g., navigate to previous month in calendars).',+ required: false,+ },+ {+ name: 'options.onPageDown',+ type: '() => void',+ description: 'Callback for Page Down key (e.g., navigate to next month in calendars).',+ required: false,+ },+ ],+ returns: [+ {+ name: 'gridRef',+ type: 'React.RefObject<HTMLElement | null>',+ description: 'Ref to attach to the grid container element.',+ },+ {+ name: 'handleKeyDown',+ type: '(e: React.KeyboardEvent) => void',+ description: 'Key down handler to attach to the grid container.',+ },+ {+ name: 'focusCell',+ type: '(index: number) => void',+ description: 'Focus a specific cell by index (clamped to valid range).',+ },+ {+ name: 'focusFirst',+ type: '() => void',+ description: 'Focus the first focusable cell in the grid.',+ },+ {+ name: 'focusLast',+ type: '() => void',+ description: 'Focus the last focusable cell in the grid.',+ },+ ],+ usage: {+ description:+ 'Manages keyboard navigation within a 2D grid following the WAI-ARIA grid pattern. Supports arrow keys for cell-to-cell navigation, Home/End for row boundaries, Ctrl+Home/Ctrl+End for grid boundaries, and Page Up/Down for custom callbacks (e.g., month navigation in calendars). Boundary navigation callbacks allow seamless cross-grid navigation.',+ bestPractices: [+ { guidance: true, description: 'Use for calendar date grids — wire onPageUp/onPageDown to month navigation and onNavigateBefore/onNavigateAfter for cross-month arrow key navigation.' },+ { guidance: true, description: 'Attach both gridRef and handleKeyDown to the grid container element.' },+ { guidance: false, description: 'Use for simple linear lists — prefer useListFocus for 1D navigation.' },+ ],+ },+ relatedComponents: ['Calendar'],+ relatedHooks: ['useListFocus', 'useFocusTrap'],+ importPath: '@xds/core/hooks',+ category: 'focus',+};diff --git a/packages/core/src/hooks/useImageMode.doc.mjs b/packages/core/src/hooks/useImageMode.doc.mjsnew file mode 100644index 0000000000..7aabccccee--- /dev/null+++ b/packages/core/src/hooks/useImageMode.doc.mjs@@ -0,0 +1,59 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useImageMode',+ keywords: ['image', 'dark', 'light', 'mode', 'luminance', 'color', 'detect', 'theme', 'media', 'apca', 'contrast'],+ params: [+ {+ name: 'src',+ type: 'string | null | undefined',+ description: 'Image source URL to analyze. When null/undefined, returns the fallback value.',+ required: true,+ },+ {+ name: 'options',+ type: 'UseImageModeOptions',+ description: 'Optional configuration for image analysis.',+ required: false,+ },+ {+ name: 'options.region',+ type: 'ImageSampleRegion',+ description: 'Region to sample within the image using normalized 0-1 coordinates ({ x, y, width, height }). Defaults to the full image.',+ required: false,+ },+ {+ name: 'options.threshold',+ type: 'number',+ description: 'Luminance threshold for the dark/light split. Below = dark, above = light.',+ default: '0.5',+ required: false,+ },+ {+ name: 'options.fallback',+ type: "'dark' | 'light' | null",+ description: 'Fallback value while loading or on error.',+ default: 'null',+ required: false,+ },+ ],+ returns: [+ {+ name: 'mode',+ type: "'dark' | 'light' | null",+ description: "Detected luminance mode of the image. Returns null while loading or if src is null/undefined.",+ },+ ],+ usage: {+ description:+ 'Detects whether an image is predominantly dark or light by sampling pixels via OffscreenCanvas. Uses APCA perceptual lightness (sRGB linearization + power curve) for accurate detection, especially on saturated colors. Runs entirely off the paint path — no visible canvas, no layout thrash. Supports regional sampling for detecting luminance where text overlays will appear. Returns null while loading and falls back gracefully on CORS or network errors.',+ bestPractices: [+ { guidance: true, description: 'Pair with XDSMediaTheme to automatically adapt text color over dynamic background images.' },+ { guidance: true, description: 'Use the region option to sample only the area where text overlays will appear for more accurate results.' },+ { guidance: false, description: 'Use for images that change rapidly (e.g., video frames) — each src change triggers a new fetch and analysis.' },+ ],+ },+ relatedComponents: ['MediaTheme'],+ relatedHooks: ['useMediaQuery'],+ importPath: '@xds/core/hooks',+ category: 'media',+};diff --git a/packages/core/src/hooks/useInputContainer.doc.mjs b/packages/core/src/hooks/useInputContainer.doc.mjsnew file mode 100644index 0000000000..55ec34bab8--- /dev/null+++ b/packages/core/src/hooks/useInputContainer.doc.mjs@@ -0,0 +1,57 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useInputContainer',+ keywords: ['input', 'container', 'focus', 'delegate', 'wrapper', 'text', 'textarea', 'click', 'icon', 'padding'],+ params: [+ {+ name: 'options',+ type: 'UseInputContainerOptions',+ description: 'Configuration object for the input container.',+ required: true,+ },+ {+ name: 'options.containerRef',+ type: 'RefObject<HTMLElement | null>',+ description: 'Ref to the outer container/wrapper element.',+ required: true,+ },+ {+ name: 'options.inputRef',+ type: 'RefObject<HTMLInputElement | HTMLTextAreaElement | HTMLElement | null>',+ description: 'Ref to the inner input or textarea element.',+ required: true,+ },+ {+ name: 'options.disabled',+ type: 'boolean',+ description: 'Whether the input is disabled.',+ default: 'false',+ required: false,+ },+ ],+ returns: [+ {+ name: 'onClick',+ type: '(event: MouseEvent<HTMLElement>) => void',+ description: 'Click handler to attach to the container wrapper.',+ },+ {+ name: 'onMouseUp',+ type: '(event: MouseEvent<HTMLElement>) => void',+ description: 'Mouse up handler to attach to the container wrapper.',+ },+ ],+ usage: {+ description:+ 'Makes an input container wrapper clickable, delegating focus to the inner input/textarea when the user clicks non-interactive areas (icons, padding, status indicators). Built on top of useClickableContainer, so nested interactive elements (clear buttons, calendar toggles, links) are handled safely — clicking them does NOT steal focus from the input. Automatically detects input type: text-like inputs receive .focus(), while other types (checkbox, radio, file) receive .click().',+ bestPractices: [+ { guidance: true, description: 'Use inside input wrapper components (XDSTextInput, XDSNumberInput, XDSTimeInput, XDSTextArea) to make the full container area clickable.' },+ { guidance: true, description: 'Attach both onClick and onMouseUp to the wrapper div for full interaction handling.' },+ { guidance: false, description: 'Use on bare inputs without a wrapper — there is no benefit if the input already fills the full clickable area.' },+ ],+ },+ relatedComponents: ['TextInput', 'NumberInput', 'TimeInput', 'TextArea'],+ relatedHooks: ['useClickableContainer'],+ importPath: '@xds/core/hooks',+ category: 'interaction',+};diff --git a/packages/core/src/hooks/useListFocus.doc.mjs b/packages/core/src/hooks/useListFocus.doc.mjsnew file mode 100644index 0000000000..16a2f79067--- /dev/null+++ b/packages/core/src/hooks/useListFocus.doc.mjs@@ -0,0 +1,80 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useListFocus',+ keywords: ['list', 'focus', 'keyboard', 'navigation', 'menu', 'toolbar', 'roving', 'tabindex', 'a11y', 'arrow', 'wai-aria'],+ params: [+ {+ name: 'options',+ type: 'UseListFocusOptions',+ description: 'Configuration object for list focus behavior. All fields are optional.',+ required: false,+ },+ {+ name: 'options.itemSelector',+ type: 'string',+ description: 'Selector for focusable items within the list.',+ default: "'[role=\"menuitem\"]'",+ required: false,+ },+ {+ name: 'options.wrap',+ type: 'boolean',+ description: 'Whether arrow navigation wraps around at the ends.',+ default: 'true',+ required: false,+ },+ {+ name: 'options.onEscape',+ type: '() => void',+ description: 'Callback when Escape key is pressed (e.g., close menu).',+ required: false,+ },+ {+ name: 'options.orientation',+ type: "'horizontal' | 'vertical'",+ description: "Navigation orientation. 'horizontal' uses ArrowLeft/ArrowRight, 'vertical' uses ArrowUp/ArrowDown.",+ default: "'vertical'",+ required: false,+ },+ ],+ returns: [+ {+ name: 'listRef',+ type: 'React.RefObject<HTMLElement | null>',+ description: 'Ref to attach to the list container element.',+ },+ {+ name: 'handleKeyDown',+ type: '(e: React.KeyboardEvent) => void',+ description: 'Key down handler to attach to the list container.',+ },+ {+ name: 'focusItem',+ type: '(index: number) => void',+ description: 'Focus a specific item by index (clamped to valid range).',+ },+ {+ name: 'focusFirst',+ type: '() => void',+ description: 'Focus the first focusable item in the list.',+ },+ {+ name: 'focusLast',+ type: '() => void',+ description: 'Focus the last focusable item in the list.',+ },+ ],+ usage: {+ description:+ 'Manages keyboard navigation within a linear list following WAI-ARIA menu/listbox/toolbar patterns. Supports arrow key navigation (vertical or horizontal), Home/End for boundaries, optional wrap-around, and Escape to close. Suitable for dropdown menus, toolbars, and any 1D focusable list.',+ bestPractices: [+ { guidance: true, description: "Set orientation to 'horizontal' for toolbars and tab bars, 'vertical' for dropdown menus." },+ { guidance: true, description: 'Provide an onEscape callback for menus/dropdowns to return focus to the trigger.' },+ { guidance: false, description: 'Use for 2D grid navigation — prefer useGridFocus for grids and calendars.' },+ ],+ },+ relatedComponents: ['TabMenu', 'Toolbar'],+ relatedHooks: ['useGridFocus', 'useFocusTrap'],+ importPath: '@xds/core/hooks',+ category: 'focus',+};diff --git a/packages/core/src/hooks/useMediaQuery.doc.mjs b/packages/core/src/hooks/useMediaQuery.doc.mjsnew file mode 100644index 0000000000..c523cf9c89--- /dev/null+++ b/packages/core/src/hooks/useMediaQuery.doc.mjs@@ -0,0 +1,32 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useMediaQuery',+ keywords: ['responsive', 'breakpoint', 'media', 'mobile', 'desktop', 'screen', 'matchmedia'],+ params: [+ {+ name: 'query',+ type: 'string',+ description: 'CSS media query string to evaluate.',+ required: true,+ },+ ],+ returns: [+ {+ name: 'matches',+ type: 'boolean',+ description: 'Whether the media query currently matches. Always false on first render (SSR-safe).',+ },+ ],+ usage: {+ description: 'SSR-safe media query hook that subscribes to window.matchMedia changes. Returns whether the given media query matches. Always returns false on first render for SSR compatibility.',+ bestPractices: [+ { guidance: true, description: 'Use for responsive layout switching based on viewport width, color scheme, or motion preferences.' },+ { guidance: true, description: 'Prefer XDS responsive tokens and component props over manual breakpoint logic when possible.' },+ { guidance: false, description: 'Use for server-rendered content that must match on first paint — the hook always returns false initially.' },+ ],+ },+ relatedComponents: [],+ relatedHooks: ['useImageMode'],+ importPath: '@xds/core/hooks',+ category: 'media',+};diff --git a/packages/core/src/hooks/useOverflow.doc.mjs b/packages/core/src/hooks/useOverflow.doc.mjsnew file mode 100644index 0000000000..a80d0e2ee3--- /dev/null+++ b/packages/core/src/hooks/useOverflow.doc.mjs@@ -0,0 +1,82 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useOverflow',+ keywords: ['overflow', 'truncate', 'responsive', 'collapse', 'resize', 'measure', 'hidden', 'more', 'breadcrumb'],+ params: [+ {+ name: 'itemCount',+ type: 'number',+ description: 'Total number of items to measure for overflow.',+ required: true,+ },+ {+ name: 'options',+ type: 'UseOverflowOptions',+ description: 'Configuration object for overflow behavior.',+ required: false,+ },+ {+ name: 'options.gap',+ type: 'number',+ description: 'Gap between items in pixels. Used in width calculations.',+ default: '0',+ required: false,+ },+ {+ name: 'options.minVisibleItems',+ type: 'number',+ description: 'Minimum number of items to always show, even if they don\'t fit.',+ default: '0',+ required: false,+ },+ {+ name: 'options.collapseFrom',+ type: "'start' | 'end'",+ description: 'Which end to collapse items from.',+ default: "'end'",+ required: false,+ },+ {+ name: 'options.behavior',+ type: "'observeParent' | 'observeSelf'",+ description: "Which element to observe for overflow calculations. 'observeParent' uses the container's parent element width, allowing the visible container to remain content-sized.",+ default: "'observeSelf'",+ required: false,+ },+ ],+ returns: [+ {+ name: 'containerRef',+ type: 'React.RefCallback<HTMLElement>',+ description: 'Ref callback to attach to the visible container element.',+ },+ {+ name: 'measureRef',+ type: 'React.RefCallback<HTMLElement>',+ description: 'Ref callback to attach to the hidden measurement container that holds all items.',+ },+ {+ name: 'visibleCount',+ type: 'number',+ description: 'Number of items that fit in the visible container.',+ },+ {+ name: 'hasOverflow',+ type: 'boolean',+ description: 'Whether any items are overflowing (visibleCount < itemCount).',+ },+ ],+ usage: {+ description:+ 'Measures children rendered in a hidden container to determine how many fit in the available width without flickering. Uses ResizeObserver to react to container size changes. The measurement container should hold all items plus an optional overflow indicator element (identified by a data-overflow-indicator attribute).',+ bestPractices: [+ { guidance: true, description: 'Render all items into the measureRef container (hidden) and only the first visibleCount items into the containerRef container (visible).' },+ { guidance: true, description: 'Include an overflow indicator (e.g., "+N more" button) as the last child of the measurement container with a data-overflow-indicator attribute.' },+ { guidance: false, description: 'Use for vertical overflow — this hook measures horizontal width only.' },+ ],+ },+ relatedComponents: ['OverflowList', 'Breadcrumb'],+ relatedHooks: ['useScrollOverflow'],+ importPath: '@xds/core/hooks',+ category: 'layout',+};diff --git a/packages/core/src/hooks/useScrollLock.doc.mjs b/packages/core/src/hooks/useScrollLock.doc.mjsnew file mode 100644index 0000000000..d759f0c2cc--- /dev/null+++ b/packages/core/src/hooks/useScrollLock.doc.mjs@@ -0,0 +1,27 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useScrollLock',+ keywords: ['scroll', 'lock', 'modal', 'dialog', 'body', 'prevent', 'background', 'ios', 'safari', 'fixed'],+ params: [+ {+ name: 'isLocked',+ type: 'boolean',+ description: 'Whether body scroll should be locked.',+ required: true,+ },+ ],+ returns: [],+ usage: {+ description:+ 'Locks body scroll when active by pinning the body with position: fixed. This prevents background scrolling behind modals and dialogs, which is necessary for iOS Safari where overscroll-behavior: contain does not work. Restores the original scroll position when unlocked.',+ bestPractices: [+ { guidance: true, description: 'Use when opening full-screen modals or dialogs to prevent background content from scrolling.' },+ { guidance: true, description: 'Pass the same boolean that controls dialog visibility (e.g., isOpen) as the isLocked parameter.' },+ { guidance: false, description: 'Use for non-modal overlays like popovers or tooltips — users should be able to scroll away from those.' },+ ],+ },+ relatedComponents: ['Dialog'],+ relatedHooks: ['useFocusTrap'],+ importPath: '@xds/core/hooks',+ category: 'layout',+};diff --git a/packages/core/src/hooks/useScrollOverflow.doc.mjs b/packages/core/src/hooks/useScrollOverflow.doc.mjsnew file mode 100644index 0000000000..26f1dc9907--- /dev/null+++ b/packages/core/src/hooks/useScrollOverflow.doc.mjs@@ -0,0 +1,41 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useScrollOverflow',+ keywords: ['scroll', 'overflow', 'carousel', 'fade', 'edge', 'horizontal', 'scrollable', 'resize'],+ params: [],+ returns: [+ {+ name: 'scrollRef',+ type: 'React.RefCallback<HTMLElement>',+ description: 'Ref callback to attach to the horizontally scrollable container element.',+ },+ {+ name: 'overflowStart',+ type: 'boolean',+ description: 'Whether content overflows the start edge (left in LTR, right in RTL).',+ },+ {+ name: 'overflowEnd',+ type: 'boolean',+ description: 'Whether content overflows the end edge (right in LTR, left in RTL).',+ },+ {+ name: 'hasOverflow',+ type: 'boolean',+ description: 'Whether the container has any scroll overflow at all (scrollWidth > clientWidth).',+ },+ ],+ usage: {+ description:+ 'Tracks scroll overflow state for a horizontally scrollable container. Returns a ref callback and state booleans that update as the user scrolls or the container resizes. Uses scroll event listeners and ResizeObserver for reactive updates. Tolerance of 1px is applied to avoid sub-pixel false positives.',+ bestPractices: [+ { guidance: true, description: 'Use to show/hide scroll navigation buttons or fade edges on carousels and horizontal lists.' },+ { guidance: true, description: 'Apply the scrollRef to a container with overflow-x: auto or overflow-x: scroll.' },+ { guidance: false, description: 'Use for vertical scroll tracking — this hook only measures horizontal overflow.' },+ ],+ },+ relatedComponents: ['Carousel'],+ relatedHooks: ['useOverflow'],+ importPath: '@xds/core/hooks',+ category: 'layout',+};diff --git a/packages/core/src/hooks/useXDSStreamingText.doc.mjs b/packages/core/src/hooks/useXDSStreamingText.doc.mjsnew file mode 100644index 0000000000..ea0b810fc3--- /dev/null+++ b/packages/core/src/hooks/useXDSStreamingText.doc.mjs@@ -0,0 +1,53 @@+/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useXDSStreamingText',+ keywords: ['streaming', 'text', 'typewriter', 'animation', 'ai', 'chat', 'markdown', 'reveal', 'llm', 'chunked'],+ params: [+ {+ name: 'targetText',+ type: 'string',+ description: 'The full target text to reveal. As new chunks arrive, update this value with the accumulated text.',+ required: true,+ },+ {+ name: 'isStreaming',+ type: 'boolean',+ description: 'Whether text is currently being streamed. When false, the hook returns the full targetText immediately.',+ required: true,+ },+ {+ name: 'options',+ type: 'UseStreamingTextOptions',+ description: 'Optional configuration for streaming behavior.',+ required: false,+ },+ {+ name: 'options.speed',+ type: "'natural' | 'fast' | 'instant'",+ description: "Speed preset for text reveal. 'natural' is steady ~2 chars/frame, 'fast' scales with backlog ~4 chars/frame, 'instant' returns full text with no animation.",+ default: "'natural'",+ required: false,+ },+ ],+ returns: [+ {+ name: 'displayedText',+ type: 'string',+ description: 'The portion of targetText to render. Grows steadily toward the full targetText during streaming, or equals targetText when not streaming.',+ },+ ],+ usage: {+ description:+ 'Smooths bursty streamed text into a steady character-by-character reveal using requestAnimationFrame. Decouples arrival rate from display rate. Advances on word and syntax boundaries to avoid slicing mid-markdown or mid-word, preventing visual glitches with markdown renderers. Animation timing derives from XDS motion tokens via useXDSTheme when available, with sensible fallbacks outside a theme provider. Snaps to full text when isStreaming becomes false.',+ bestPractices: [+ { guidance: true, description: 'Pass the accumulated text (not individual chunks) as targetText — the hook handles incremental reveal internally.' },+ { guidance: true, description: 'Set isStreaming to false when the stream completes to snap to the final text.' },+ { guidance: true, description: "Use speed='instant' for non-animated contexts like search results or when reduced motion is preferred." },+ { guidance: false, description: 'Use for static text that does not change — the hook adds unnecessary overhead for non-streaming content.' },+ ],+ },+ relatedComponents: ['Markdown'],+ relatedHooks: [],+ importPath: '@xds/core/hooks',+ category: 'streaming',+};