UNPKG

code-colors-react

Version:
73 lines (72 loc) 2.52 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Markup = void 0; const tslib_1 = require("tslib"); const React = require("react"); const util_1 = require("./util"); const { createElement: h } = React; const astToReact = (ast, code, pos, lang, decorate) => { if (typeof ast === "number") return [code.slice(pos, pos + ast), ast]; const [types, tokens] = ast; const children = []; const length = tokens.length; let nodeTextLength = 0; for (let i = 0; i < length; i++) { const token = tokens[i]; const offset = pos + nodeTextLength; const [node, len] = astToReact(token, code, offset, lang, decorate); nodeTextLength += len; let node2; children.push(decorate ? ((node2 = decorate(token, node, lang, code, offset)), node2 === undefined ? node : node2) : node); } const props = { className: "token " + types.join(" "), }; const firstChild = children[0]; if (children.length === 1 && typeof firstChild === "string" && children.length <= 16) { props["text"] = firstChild; return [h("span", props, firstChild), nodeTextLength]; } else { return [h("span", props, ...children), nodeTextLength]; } }; const Markup = (props) => { const { code, lang, as = "code", renderWaiting, decorate } = props, rest = tslib_1.__rest(props, ["code", "lang", "as", "renderWaiting", "decorate"]); const [node, setNode] = React.useState(null); const Tag = as; React.useEffect(() => { setNode(null); let cancelled = false; (0, util_1.tokens)(code, lang) .then((ast) => { if (!cancelled) { let realLang = lang || "clike"; if (Array.isArray(ast[0]) && typeof ast[0][0] === "string") { if (ast[0][0].startsWith("language-")) { realLang = ast[0][0].slice(9); } } const [node] = astToReact(ast, code, 0, realLang, decorate); setNode(node); } }) .catch((err) => { }); return () => { cancelled = true; }; }, [code, decorate]); rest.children = node || (renderWaiting ? renderWaiting(props) : h("span", { style: { opacity: 0.5 } }, code)); return h(Tag, rest); }; exports.Markup = Markup;