UNPKG

@markslides/markdown-it-mermaid

Version:
167 lines (165 loc) 5.92 kB
var __defProp = Object.defineProperty; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; // src/index.ts import mermaid from "mermaid"; var renderCache = /* @__PURE__ */ new Map(); var hashCode = (str) => { let hash = 0; for (let i = 0; i < str.length; i++) { const char = str.charCodeAt(i); hash = (hash << 5) - hash + char; hash = hash & hash; } return hash.toString(36); }; var mermaidChart = (code) => { const codeHash = hashCode(code); const cachedResult = renderCache.get(codeHash); if (cachedResult) { return cachedResult; } const id = `mermaid-${codeHash}`; const containerId = `${id}-container`; try { const placeholder = `<div id="${containerId}" class="mermaid-container"> <div class="mermaid-loading">Rendering diagram...</div> </div>`; setTimeout(() => __async(void 0, null, function* () { var _a; const containerElem = document.getElementById(containerId); if (!containerElem) return; try { yield mermaid.parse(code, { suppressErrors: false }); const { svg, bindFunctions } = yield mermaid.render( `${id}-${Date.now()}`, code ); const currentContainer = document.getElementById(containerId); if (currentContainer) { const svgWrapper = document.createElement("div"); svgWrapper.className = "mermaid-svg-wrapper"; svgWrapper.style.cssText = "width: 100%; height: auto; display: flex; justify-content: center; align-items: center;"; const parser = new DOMParser(); const svgDoc = parser.parseFromString(svg, "image/svg+xml"); const svgElement = svgDoc.querySelector("svg"); if (svgElement) { svgElement.setAttribute( "preserveAspectRatio", "xMidYMid meet" ); if (!svgElement.hasAttribute("viewBox")) { const width = svgElement.getAttribute("width") || "100%"; const height = svgElement.getAttribute("height") || "100%"; if (width !== "100%" && height !== "100%") { svgElement.setAttribute( "viewBox", `0 0 ${width} ${height}` ); } } svgElement.removeAttribute("width"); svgElement.removeAttribute("height"); svgWrapper.appendChild(svgElement); } else { svgWrapper.innerHTML = svg; } currentContainer.innerHTML = ""; currentContainer.appendChild(svgWrapper); if (bindFunctions) { bindFunctions(currentContainer); } const finalResult = currentContainer.outerHTML; renderCache.set(codeHash, finalResult); } } catch (error) { console.error("Mermaid error:", error); const errorResult = `<pre class="mermaid-error">${((_a = error.message) == null ? void 0 : _a.includes("Syntax error")) ? `Syntax error: ${error.message}` : error.message || "Failed to render diagram"}</pre>`; const currentContainer = document.getElementById(containerId); if (currentContainer) { currentContainer.innerHTML = errorResult; } renderCache.set(codeHash, errorResult); } }), 0); return placeholder; } catch (error) { console.error("Mermaid chart error:", error); const errorResult = `<pre class="mermaid-error">${error.message || "Unknown error"}</pre>`; renderCache.set(codeHash, errorResult); return errorResult; } }; var isDarkMode = false; var markdownItMermaid = (md, config) => { mermaid.initialize(__spreadValues({ theme: isDarkMode ? "dark" : "default", darkMode: isDarkMode, fontFamily: "Inconsolata, monospace !important", // fontFamily: 'ui-monospace', // altFontFamily: 'monospace', startOnLoad: false, // Set to false to prevent auto-initialization conflicts securityLevel: "loose", // Allow more flexible parsing logLevel: "error" }, config)); mermaid.registerIconPacks([ { name: "logos", loader: () => fetch( "https://unpkg.com/@iconify-json/logos@1/icons.json" ).then((res) => res.json()) } ]); md.mermaid = mermaid; const original = md.renderer.rules.fence || function(tokens, idx, options, env, self) { return self.renderToken(tokens, idx, options); }; md.renderer.rules.fence = (tokens, idx, options, env, self) => { const token = tokens[idx]; const code = token.content.trim(); if (token.info === "mermaid") { return mermaidChart(code); } return original(tokens, idx, options, env, self); }; }; var src_default = markdownItMermaid; export { src_default as default };