|
| 1 | +<script setup lang="ts"> |
| 2 | +import { onMounted, onUnmounted, ref } from "vue"; |
| 3 | +import type { MermaidConfig } from "mermaid"; |
| 4 | +import mermaid from "mermaid"; |
| 5 | +
|
| 6 | +const props = defineProps({ |
| 7 | + graph: { |
| 8 | + type: String, |
| 9 | + required: true, |
| 10 | + }, |
| 11 | + id: { |
| 12 | + type: String, |
| 13 | + required: true, |
| 14 | + }, |
| 15 | +}); |
| 16 | +
|
| 17 | +const svg = ref(""); |
| 18 | +const code = ref(decodeURIComponent(props.graph)); |
| 19 | +
|
| 20 | +let mut: MutationObserver | null = null; |
| 21 | +
|
| 22 | +onMounted(async () => { |
| 23 | + mut = new MutationObserver(() => { |
| 24 | + renderChart(); |
| 25 | + }); |
| 26 | + mut.observe(document.documentElement, { attributes: true }); |
| 27 | +
|
| 28 | + await renderChart(); |
| 29 | +
|
| 30 | + //refresh images on first render |
| 31 | + const hasImages = (/<img([\w\W]+?)>/.exec(code.value)?.length ?? 0) > 0; |
| 32 | + if (hasImages) |
| 33 | + setTimeout(() => { |
| 34 | + let imgElements = document.getElementsByTagName("img"); |
| 35 | + let imgs = Array.from(imgElements); |
| 36 | + if (imgs.length) { |
| 37 | + Promise.all( |
| 38 | + imgs |
| 39 | + .filter((img) => !img.complete) |
| 40 | + .map( |
| 41 | + (img) => |
| 42 | + new Promise((resolve) => { |
| 43 | + img.onload = img.onerror = resolve; |
| 44 | + }), |
| 45 | + ), |
| 46 | + ).then(() => { |
| 47 | + renderChart(); |
| 48 | + }); |
| 49 | + } |
| 50 | + }, 100); |
| 51 | +}); |
| 52 | +
|
| 53 | +onUnmounted(() => mut?.disconnect()); |
| 54 | +
|
| 55 | +const renderChart = async () => { |
| 56 | + const mermaidConfig: MermaidConfig = { |
| 57 | + securityLevel: "loose", |
| 58 | + startOnLoad: false, |
| 59 | + theme: "dark", |
| 60 | + }; |
| 61 | + mermaid.initialize(mermaidConfig); |
| 62 | + const render = await mermaid.render(props.id, code.value); |
| 63 | + // This is a hack to force v-html to re-render, otherwise the diagram disappears |
| 64 | + // when **switching themes** or **reloading the page**. |
| 65 | + // The cause is that the diagram is deleted during rendering (out of Vue's knowledge). |
| 66 | + // Because svgCode does NOT change, v-html does not re-render. |
| 67 | + // This is not required for all diagrams, but it is required for c4c, mindmap and zenuml. |
| 68 | + const salt = Math.random().toString(36).substring(7); |
| 69 | + svg.value = `${render.svg} <span style="display: none">${salt}</span>`; |
| 70 | +}; |
| 71 | +</script> |
| 72 | + |
| 73 | +<template> |
| 74 | + <!-- eslint-disable-next-line vue/no-v-html --> |
| 75 | + <div v-html="svg" /> |
| 76 | +</template> |
0 commit comments