fumadocs-core
Version:
The React.js library for building a documentation website
246 lines (245 loc) • 8.13 kB
JavaScript
// src/mdx-plugins/stringifier.ts
const documents = /* @__PURE__ */ new WeakMap();
function getDocument(file) {
let doc = documents.get(file);
if (!doc) documents.set(file, doc = {
embedded: "",
embeds: [],
ranges: /* @__PURE__ */ new WeakMap(),
replacements: []
});
return doc;
}
function getRange(node) {
const start = node.position?.start.offset;
const end = node.position?.end.offset;
if (start !== void 0 && end !== void 0) return {
start,
end
};
}
/**
* Replace the Markdown of an authored node, ignored without a position. The last edit of a node wins.
*
* @param namespace - limit the edit to the stringifiers of a namespace: `search` for search records, `markdown` for
* processed Markdown
*/
function replaceSource(file, node, text, namespace) {
getDocument(file).replacements.push({
node,
text,
namespace
});
}
/**
* Replace an authored node with `content`, its children parsed from another source (e.g. included files). Their
* positions are kept, stringifiers place `source` after the document's own.
*/
function embedSource(file, node, source, content) {
const doc = getDocument(file);
const base = String(file).length + doc.embedded.length + 1;
doc.embedded += `\n${source}`;
const host = doc.ranges.get(node) ?? getRange(node);
if (host) doc.embeds.push({
start: base,
end: base + source.length,
host
});
let start;
let end = 0;
const visit = (nodes) => {
for (const child of nodes) {
const range = getRange(child);
if (range) {
range.start += base;
range.end += base;
doc.ranges.set(child, range);
start ??= range.start;
end = Math.max(end, range.end);
}
if ("children" in child) visit(child.children);
}
};
visit(content);
replaceSource(file, node, start === void 0 ? "" : (s) => s.slice(start, end));
}
/**
* @param namespace - also apply the edits of this namespace
* @param expression - output the expressions of replacements, their fallbacks are output without it
*/
function createStringifier(file, namespace, expression = (_, fallback) => fallback) {
const doc = documents.get(file);
const ranges = doc?.ranges;
const embeds = doc?.embeds ?? [];
const source = String(file) + (doc?.embedded ?? "");
const replaced = /* @__PURE__ */ new Map();
for (const edit of doc?.replacements ?? []) if (edit.namespace === void 0 || edit.namespace === namespace) replaced.set(edit.node, edit.text);
const own = [];
const active = /* @__PURE__ */ new Set();
let edits;
function getEdits() {
if (edits) return edits;
edits = own.slice();
for (const [node, text] of replaced) {
const range = s.range(node);
if (range && range.end > range.start) edits.push({
start: range.start,
end: range.end,
text,
node,
owner: void 0
});
}
return edits.sort((a, b) => a.start - b.start || b.end - a.end);
}
/** the index of the first edit starting at or after `offset` */
function search(list, offset) {
let lo = 0;
let hi = list.length;
while (lo < hi) {
const mid = lo + hi >> 1;
if (list[mid].start < offset) lo = mid + 1;
else hi = mid;
}
return lo;
}
function render(start, end) {
const list = getEdits();
let out = "";
let cursor = start;
let appliedStart = start;
let appliedEnd = start;
for (let i = search(list, start); i < list.length; i++) {
const edit = list[i];
if (edit.start > end) break;
if (edit.start < appliedEnd || edit.end > end) continue;
if (edit.node && active.has(edit.node)) continue;
const owner = edit.owner;
if (owner && (owner.start < start || owner.end > end || owner.start >= appliedStart && owner.end <= appliedEnd)) continue;
let text = edit.text;
if (typeof text !== "string") {
active.add(edit.node);
text = text(s);
active.delete(edit.node);
}
out += source.slice(cursor, edit.start);
if (edit.start === edit.end) out += text;
else {
out += indent(source, edit.start, text);
appliedStart = edit.start;
appliedEnd = edit.end;
}
cursor = edit.end;
if (text === "" && /^[ \t]*$/.test(source.slice(source.lastIndexOf("\n", edit.start - 1) + 1, edit.start))) {
blankLines.lastIndex = cursor;
if (blankLines.test(source)) cursor = Math.min(blankLines.lastIndex, end);
if (cursor === end) out = out.trimEnd();
}
}
return out + source.slice(cursor, end);
}
const s = {
source,
range: (node) => ranges?.get(node) ?? getRange(node),
replace(node, text) {
replaced.set(node, text);
edits = void 0;
},
edit(start, end, text, node) {
own.push({
start,
end,
text,
node: void 0,
owner: node && s.range(node)
});
edits = void 0;
},
slice(start, end) {
return dedent(source, start, render(start, end));
},
stringify(node) {
const range = s.range(node);
return range ? s.slice(range.start, range.end) : "";
},
inner(node) {
const range = s.range(node);
if (!range || !("children" in node)) return "";
const first = edge(node.children, false);
const last = edge(node.children, true);
let start = (first && lift(first, range)?.start) ?? range.end;
let end = (last && lift(last, range)?.end) ?? range.start;
const list = getEdits();
for (let i = search(list, range.start + 1); i < list.length; i++) {
const edit = list[i];
if (edit.start >= range.end) break;
if (edit.end > range.end) continue;
start = Math.min(start, edit.start);
end = Math.max(end, edit.end);
}
return end > start ? s.slice(start, end) : "";
},
within: (range, outer) => lift(range, outer) !== void 0,
expression
};
/** `range` as output inside `outer`, embedded sources are output in place of the node they replace */
function lift(range, outer) {
while (range.start < outer.start || range.end > outer.end) {
const embed = embeds.find((item) => range.start >= item.start && range.end <= item.end);
if (!embed) return;
range = embed.host;
}
return range;
}
/** the first or last node with a position, looking into the children of nodes without one */
function edge(nodes, last) {
for (let i = 0; i < nodes.length; i++) {
const node = nodes[last ? nodes.length - 1 - i : i];
const range = s.range(node) ?? ("children" in node ? edge(node.children, last) : void 0);
if (range) return range;
}
}
return s;
}
/**
* A Markdown table with aligned columns, its first row is the header.
*
* @param rows - the cells of each row, as inline Markdown
*/
function markdownTable(rows) {
const widths = [];
const table = rows.map((row) => row.map((cell, i) => {
let text = cell.trim();
if (/[\n|]/.test(text)) text = text.replace(/\s*\n\s*|(?<!\\)\|/g, (s) => s === "|" ? "\\|" : " ");
widths[i] = Math.max(widths[i] ?? 3, text.length);
return text;
}));
const line = (row) => `| ${widths.map((w, i) => (row[i] ?? "").padEnd(w)).join(" | ")} |`;
return [
table[0],
widths.map((w) => "-".repeat(w)),
...table.slice(1)
].map(line).join("\n");
}
const blankLines = /(?:[ \t\r]*\n)+/y;
const containerPrefixRegex = /^(?:[ \t]*(?:>|[-*+](?=[ \t])|\d{1,9}[.)](?=[ \t])))*[ \t]*/;
/** the prefix of the containers (e.g. lists & blockquotes) at `start`, on the lines after the first */
function containerPrefix(source, start) {
const line = source.slice(source.lastIndexOf("\n", start - 1) + 1, start);
return containerPrefixRegex.exec(line)[0].replace(/[^\t>]/g, " ");
}
/** Markdown placed at `start`, continuing its containers, blank lines only carry their markers (e.g. `>`) */
function indent(source, start, text) {
if (!text.includes("\n")) return text;
const prefix = containerPrefix(source, start);
if (!prefix) return text;
return text.replace(/\n(?=(.?))/g, (_, next) => `\n${next ? prefix : prefix.trimEnd()}`);
}
/** Markdown sliced from `start`, without the prefixes of its containers */
function dedent(source, start, text) {
if (!text.includes("\n")) return text;
const prefix = containerPrefix(source, start);
if (!prefix) return text;
return text.replace(new RegExp(`\\n(?:${prefix}|${prefix.trimEnd()}(?=\\r?\\n|$))`, "g"), "\n");
}
export { createStringifier, embedSource, markdownTable, replaceSource };