UNPKG

fumadocs-core

Version:

The React.js library for building a documentation website

59 lines (58 loc) • 1.86 kB
import { fromDom } from "hast-util-from-dom"; import { micromark } from "micromark"; import { gfmTable, gfmTableHtml } from "micromark-extension-gfm-table"; // src/search/parse.ts const options = { allowDangerousHtml: true, extensions: [gfmTable()], htmlExtensions: [gfmTableHtml()] }; /** * Parse the Markdown content of results with the HTML parser of browsers, and gather the rows of a table after its first row, tables are scoped to the page before them. */ function parseResults(results) { const items = []; const tables = /* @__PURE__ */ new Map(); const template = document.createElement("template"); for (const result of results) { if (result.type === "page") tables.clear(); template.innerHTML = micromark(result.content, options); const record = { ...result, hastContent: toHast(template.content) }; const table = template.content.firstElementChild; if (!(table instanceof HTMLTableElement) || table.rows.length === 0) { items.push(record); continue; } let entry = result.table ? tables.get(result.table) : void 0; if (!entry) { const columns = table.rows[0].cells.length; const body = table.tHead && table.tBodies.item(0); body?.remove(); entry = { type: "table", id: result.id, columns, header: body ? toHast(template.content) : void 0, rows: [] }; items.push(entry); if (result.table) tables.set(result.table, entry); } entry.rows.push(record); } return items; } function toHast(fragment) { return fromDom(fragment, { afterTransform }); } /** elements unknown to HTML, like the JSX elements of records, become `custom` elements with a `tagName` property */ function afterTransform(node, hast) { if (hast.type === "element" && node instanceof HTMLUnknownElement) { hast.properties.tagName = hast.tagName; hast.tagName = "custom"; } } export { parseResults };