@lobehub/ui
Version:
Lobe UI is an open-source UI component library for building AIGC web apps
52 lines (51 loc) • 2.23 kB
JavaScript
//#region src/Mermaid/SyntaxMermaid/prepareInlineSvg.ts
/**
* Root custom properties beautiful-mermaid reads; everything else in its
* stylesheet is derived from these via color-mix().
*/
const MERMAID_ROOT_VARS = [
"--bg",
"--fg",
"--line",
"--accent",
"--muted",
"--surface",
"--border"
];
const styleBlockPattern = /<style>([\s\S]*?)<\/style>/;
const scopeCssSelectors = (css, scope) => css.replaceAll(/(^|})([^{}@]+)\{/g, (_match, tail, selectors) => {
return `${tail}\n${selectors.split(",").map((selector) => selector.trim()).filter(Boolean).map((selector) => selector === "svg" ? scope : `${scope} ${selector}`).join(", ")} {`;
});
/**
* A <style> element inside inline SVG applies to the whole document, so the
* generated rules must be scoped to this diagram before being injected. The
* font @import is dropped because inline rendering would actually issue the
* Google Fonts request that an <img>-loaded SVG silently blocks, and the bare
* `text` rule is dropped so page CSS can supply the theme font instead.
*/
const prepareInlineMermaidSvg = (svg, scopeId) => {
if (!svg) return svg;
return svg.replace(/<svg\b/, `<svg id="${scopeId}"`).replace(styleBlockPattern, (_match, css) => {
const withoutFontRule = css.replaceAll(/@import[^;]*;/g, "").replaceAll(/(^|})\s*text\s*\{[^{}]*\}/g, "$1");
return `<style>${scopeCssSelectors(withoutFontRule, `#${scopeId}`)}</style>`;
});
};
/**
* Inline SVG resolves `var(--ant-*)` from the page, but a Blob-loaded copy is an
* isolated document with no access to them, so the root variables are baked in
* as literal values before serializing for preview or download.
*/
const toStandaloneSvgString = (element) => {
const clone = element.cloneNode(true);
const computed = globalThis.getComputedStyle(element);
for (const name of MERMAID_ROOT_VARS) {
const value = computed.getPropertyValue(name).trim();
if (value) clone.style.setProperty(name, value);
}
const fontFamily = computed.fontFamily;
if (fontFamily) clone.style.setProperty("font-family", fontFamily);
return new XMLSerializer().serializeToString(clone);
};
//#endregion
export { MERMAID_ROOT_VARS, prepareInlineMermaidSvg, toStandaloneSvgString };
//# sourceMappingURL=prepareInlineSvg.mjs.map