UNPKG

fumadocs-core

Version:

The React.js library for building a documentation website

367 lines (366 loc) • 14.7 kB
// ../shared/show.ts /** the element of a branch of `<show>`, defined in the module by {@link showDeclaration} */ const showElement = "_Show"; /** the ESM code that defines {@link showElement} */ const showDeclaration = `export function ${showElement}(props) { return props.when ? props.children : null }`; /** the condition of a branch of `<show>`, code checked when rendering */ function showCondition(node) { const { name, attributes } = node; if (name !== "_Show") return; for (const attr of attributes) if (attr.type === "mdxJsxAttribute" && attr.name === "when" && typeof attr.value === "object") return attr.value?.value; } /** * Visit a tree in document order, with the conditions of the branches around each node, outermost first. Returning * `skip` skips the children of a node, a visitor can remove the node it visits from `parent`. */ function walkBranches(node, visitor, when = [], parent) { if (visitor(node, when, parent) === "skip" || !node.children) return; const condition = showCondition(node); if (condition) when = [...when, condition]; const { children } = node; for (let i = 0; i < children.length; i++) { const child = children[i]; walkBranches(child, visitor, when, node); if (children[i] !== child) i--; } } const none = []; /** * Group the lists among sibling nodes, like steps and the tabs of code blocks. A branch doesn't break a list: the nodes * inside it are nodes of the list around it, unless one of them ends the list. A list has an item outside branches, a * branch groups the lists inside it otherwise. * * @param test - read a node as an item of the list, `false` ends the list and the nodes without a result are its * content. `first` is the first item of the list * @param build - the nodes that replace the nodes of a list * @param setChildren - set the children of a branch, trees differ in how a node is edited * @returns the siblings, `undefined` without a list */ function groupLists(children, test, build, setChildren) { const out = []; /** the nodes before it are in `out` */ let done = 0; let changed = false; let branches = false; let start = -1; let items = []; let direct = false; let ends = false; const visit = (node, when) => { if (showCondition(node)) { branches = true; return; } const result = ends ? void 0 : test(node, items[0]?.node); if (result) items.push({ node, data: result, when }); else if (result === false) ends = true; return "skip"; }; /** the nodes outside lists stay, a branch groups the lists inside it */ const keep = (end) => { for (; done < end; done++) { const node = children[done]; const inner = showCondition(node) && groupLists(node.children, test, build, setChildren); if (inner) { setChildren(node, inner); changed = true; } out.push(node); } }; const close = (end) => { if (direct) { keep(start); for (const node of build(children.slice(start, end), items)) out.push(node); done = end; changed = true; } start = -1; items = []; direct = false; }; for (let i = 0; i < children.length; i++) { const count = items.length; ends = false; walkBranches(children[i], visit, none); if (ends) { items.length = count; if (start !== -1) { close(i); i--; } continue; } if (items.length === count) continue; if (start === -1) start = i; direct ||= items[count].when.length === 0; } close(children.length); if (!changed && !branches) return; keep(children.length); if (changed) return out; } /** * Whether the outputs of a document are static: values analysed from the source, which can't tell the branches that * show nor read props. A document with branches has no static outputs. * * @param isStatic - by default, unless the content source of the document renders its pages for props */ function isStaticOutput(data, isStatic = !data.unstable_runtimeOutputs) { if (isStatic && data._show) throw new Error("`<show>` is checked when rendering, but the outputs of this document are static: its content source doesn't set `unstable_runtimeOutputs` in the data of the file, or processed Markdown has `output: 'string'`."); return isStatic; } // ../shared/code-output.ts const markerRegex = /\0(\/?)(\d+)\0/g; const componentNameRegex = /^[A-Z][\w$]*$/; /** the elements that static search keeps as HTML tags by default */ const staticTagRegex = /^(File|TypeTable|Callout|Card)$/; /** * Markdown stringified from the authored source for a target, with parts that render from code. Replacements mark the * parts, so edits apply to their content like to other content (e.g. the prefixes of list items), and the code of the * output splits it on the markers. The code runs in a function of the props of the page, in the scope of its module. */ function createCodeOutput({ target, isStatic, keep, stringifier, parse, literal = JSON.stringify }) { const parts = []; const mark = (part) => `\0${parts.push(part) - 1}\0`; const wrap = (part, content) => { const i = parts.push(part) - 1; return `\0${i}\0${content}\0/${i}\0`; }; const expression = (code, fallback) => mark({ code, fallback }); const s = stringifier(expression); function chunks(text) { const root = []; const stack = [root]; /** a branch that just closed, the line break after it goes with it */ let branch; let idx = 0; const pushText = (end) => { let value = text.slice(idx, end); if (branch) { const lead = /^\s*/.exec(value)[0]; if (lead.includes("\n")) { branch.push(lead); value = value.slice(lead.length); } branch = void 0; } if (value) stack.at(-1).push(value); }; for (const match of text.matchAll(markerRegex)) { pushText(match.index); idx = match.index + match[0].length; const part = parts[Number(match[2])]; if (match[1]) { const children = stack.pop(); stack.at(-1).push({ ...part, children }); if ("when" in part) branch = children; } else if ("code" in part) stack.at(-1).push(part); else stack.push([]); } pushText(text.length); return root; } /** * See {@link componentsCode}, of the components that the parts refer to: kept elements, and the JSX in authored * code. The parts are parsed as the JSX they are in the output, where an expression of comments is valid. */ const declare = (scope, from) => componentsCode(jsxComponents(parts.length > 0 && parse(`<>${chunksToJsx(parts, literal)}</>`)), scope, from); /** the JSX element of a component, with the code of its attributes */ function component(node) { const { name } = node; if (typeof name !== "string" || !componentNameRegex.test(name)) return; let open = `<${name}`; for (const attr of node.attributes) if (attr.type === "mdxJsxExpressionAttribute") open += ` {${attr.value}}`; else if (attr.value == null) open += ` ${attr.name}`; else if (typeof attr.value === "string") open += ` ${attr.name}={${JSON.stringify(attr.value)}}`; else open += ` ${attr.name}={${attr.value.value}}`; return { open, name, inline: node.type === "mdxJsxTextElement" }; } function element(node) { const when = showCondition(node); if (when) return s.replace(node, (s) => wrap({ when }, s.inner(node))); const kept = keep ? keep(node) : !isStatic || staticTagRegex.test(String(node.name)); const part = kept && !isStatic ? component(node) : void 0; if (part) s.replace(node, (s) => { const inner = s.inner(node); return wrap(part, target === "markdown" && inner && !part.inline ? `\n${inner}\n` : inner); }); else if (target === "search") s.replace(node, (s) => { if (!kept || !(keep || isStatic)) return s.inner(node); const attributes = {}; for (const attr of node.attributes) if (attr.type === "mdxJsxAttribute") attributes[attr.name] = (typeof attr.value === "object" ? attr.value?.value : attr.value) ?? true; return toHtmlTag(node.name, attributes, s.inner(node)); }); } return { s, /** mark the code of a value */ expression, /** Edit a node for the target: authored expressions, `<show>` branches, JSX elements, links, images and ESM. */ edit(node) { const { type } = node; if (type === "mdxjsEsm") s.replace(node, ""); else if (type === "mdxJsxFlowElement" || type === "mdxJsxTextElement") element(node); else if (type === "mdxTextExpression" || type === "mdxFlowExpression") { if (isStatic) return; const position = s.range(node); s.replace(node, mark({ code: node.value, fallback: position ? s.source.slice(position.start, position.end) : "", inline: type === "mdxTextExpression" })); } else if (target === "search") { if (type === "link" || type === "linkReference") s.replace(node, (s) => s.inner(node)); else if (type === "image" || type === "imageReference") s.replace(node, ""); } }, /** the output without code: values as their fallbacks, the content of every branch and element */ toStatic(text) { return text.replace(markerRegex, (_, close, i) => { const part = parts[Number(i)]; return !close && "fallback" in part ? part.fallback : ""; }); }, /** the output as a string in code, its values are concatenated: for an output without branches or elements */ toConcat(text) { let out = ""; for (const chunk of chunks(text)) out += `${out ? " + " : ""}${typeof chunk === "string" ? literal(chunk) : `(${chunk.code})`}`; return out || "\"\""; }, /** the output as a value in code: a string without parts, a fragment otherwise */ toCode(text) { return chunksToCode(chunks(text), literal); }, componentsCode: declare, /** * The export of processed Markdown: a component, rendered with `renderToMarkdown()` of `fumadocs-core/server`. * Its elements resolve like in the content, a missing MDX component is kept as JSX syntax. */ markdownCode(as, text, scope) { const declaration = declare(scope, "_jsxComponents(props.components)"); return [ `import { asMarkdown as _asMarkdown${declaration && ", jsxComponents as _jsxComponents"} } from "fumadocs-core/server";`, `export function ${as}(props) {`, " if (!_asMarkdown()) return null;", declaration, ` return ${chunksToCode(chunks(text), literal)};`, "}" ].join("\n"); } }; } /** * An element as an HTML tag, so search dialogs render it as an element: its attributes that are text or `true`, with * values and content on one line, values truncated. */ function toHtmlTag(name, attributes, inner) { let open = `<${name}`; for (const key in attributes) { const value = attributes[key]; if (value === true) open += ` ${key}`; if (key === "children" || typeof value !== "string" && typeof value !== "number") continue; let text = String(value).replace(/\s+/g, " "); if (text.length > 100) text = `${text.slice(0, 100)}…`; open += ` ${key}="${text.replaceAll("&", "&amp;").replaceAll("\"", "&quot;")}"`; } const children = inner.replace(/\s+/g, " "); return children ? `${open}>${children}</${name}>` : `${open} />`; } /** * The declaration of the components that code refers to and the module doesn't declare. Like in the content, they * are MDX components. * * @param scope - the names that the module declares, read when there are components * @param from - the code of the MDX components * @param fallback - the code of a component that `from` doesn't have */ function componentsCode(components, scope, from, fallback) { let names = ""; if (components.size > 0) { const declared = scope(); for (const name of components) if (!declared.has(name)) names += fallback ? `${name} = ${fallback}, ` : `${name}, `; } return names && `const { ${names}} = ${from};`; } /** * The components that parsed code refers to in JSX, like MDX: the name of a tag that isn't an HTML element, or the * object of a member tag like `<a.B>`. */ function jsxComponents(node, out = /* @__PURE__ */ new Set()) { if (typeof node !== "object" || node === null) return out; let { type, name } = node; if (type === "JSXOpeningElement") { const member = name?.object !== void 0; while (name?.object) name = name.object; if (name?.type === "JSXIdentifier" && (member || !/^[a-z]/.test(name.name))) out.add(name.name); } for (const key in node) jsxComponents(node[key], out); return out; } /** the names declared by the ESM statements of a module: imports and top-level declarations */ function moduleScope(statements, scope = /* @__PURE__ */ new Set()) { for (const item of statements) { for (const { local } of item.specifiers ?? []) if (local.name) scope.add(local.name); const declaration = item.type === "ExportNamedDeclaration" ? item.declaration : item; if (declaration?.id?.name) scope.add(declaration.id.name); for (const { id } of declaration?.declarations ?? []) if (id.type === "Identifier" && id.name) scope.add(id.name); } return scope; } /** all of the conditions */ function and(conditions) { if (conditions.length > 0) return `(${conditions.join(") && (")})`; } /** * The code of a list output: a function of the props giving the items whose conditions hold, or the list when static. * The list is read in document order, so an entry with `run` can count the items that show. * * @param declaration - the code that declares the names of the items, see {@link componentsCode} */ function listCode(items, isStatic, declaration = "") { let list = "["; for (const { code, when, run } of items) { const test = and(when); const item = run ? `...((${code}), [])` : code; list += test ? `...(${test} ? [${item}] : []),` : `${item},`; } list += "]"; if (isStatic) return list; return declaration ? `(props) => {\n${declaration}\nreturn ${list};\n}` : `(props) => ${list}`; } function chunksToCode(chunks, literal) { let text = ""; for (const chunk of chunks) { if (typeof chunk !== "string") return `<>${chunksToJsx(chunks, literal)}</>`; text += chunk; } return literal(text); } function chunksToJsx(chunks, literal) { let out = ""; for (const chunk of chunks) if (typeof chunk === "string") out += `{${literal(chunk)}}`; else if ("code" in chunk) out += chunk.inline ? `<span>{${chunk.code}}</span>` : `{${chunk.code}}`; else if ("when" in chunk) out += `{(${chunk.when}) ? <>${chunksToJsx(chunk.children ?? [], literal)}</> : null}`; else { const { open, name, inline, children } = chunk; const element = children?.length ? `${open}>${chunksToJsx(children, literal)}</${name}>` : `${open} />`; out += inline ? `<span>${element}</span>` : element; } return out; } export { listCode as a, toHtmlTag as c, showCondition as d, showDeclaration as f, jsxComponents as i, groupLists as l, walkBranches as m, componentsCode as n, moduleScope as o, showElement as p, createCodeOutput as r, staticTagRegex as s, and as t, isStaticOutput as u };