UNPKG

@rise4fun/docusaurus-remark-plugin-code-element

Version:
83 lines 2.69 kB
"use strict"; const tslib_1 = require("tslib"); const unist_util_visit_1 = tslib_1.__importDefault(require("unist-util-visit")); const node_querystring_1 = require("node:querystring"); function parseMeta(node) { const r = (0, node_querystring_1.parse)(node.meta || '', ' '); Object.keys(r).forEach((k) => (r[k] = fromAttributeValue(r[k]))); return r; } function injectThemeImport(root, element) { if (!root.children.find((n) => n.type === 'import' && n.value && n.value?.includes(`@theme/${element}`))) { root.children.unshift({ type: 'import', value: `import ${element} from '@theme/${element}';`, }); } } function fromAttributeValue(s) { if (s === undefined) return s; if (s === '') return true; if (s === 'true') return true; if (s === 'false') return false; if (typeof s === 'string') { const i = parseInt(s); if (!isNaN(i)) return i; const f = parseFloat(s); if (!isNaN(f)) return f; const x = /^0x/.test(s) && parseInt(s.slice(2), 16); if (x !== false && !isNaN(x)) return x; } if (typeof s === 'string' && s[0] === '"') { try { return JSON.parse(s); } catch { } } return s; } function toAttributeValue(s) { if (!s) return s; try { const j = JSON.parse(s); if (typeof j === 'string') s = j; } catch { } return JSON.stringify(s); } const plugin = (options = undefined) => { const { langs = [] } = options || {}; return async (root, vfile) => { const needsImport = new Set(); const visited = new Set(); // visit called twice on async // collect all nodes (0, unist_util_visit_1.default)(root, 'code', (node, nodeIndex, parent) => { const { lang, meta, value } = node; if (!parent || !lang || visited.has(node)) return; visited.add(node); const langOptions = langs.find((o) => o.lang === lang); if (!langOptions) return; const { element } = langOptions; const parsedMeta = parseMeta(node); needsImport.add(element); parent.children.splice(nodeIndex, 1, { type: 'jsx', value: `<${element} lang={${toAttributeValue(lang)}} meta={${JSON.stringify(parsedMeta)}} value={${toAttributeValue(value)}} />`, }); }); needsImport.forEach((element) => injectThemeImport(root, element)); }; }; module.exports = plugin; //# sourceMappingURL=index.js.map