forked from facebook/docusaurus
/
index.tsx
64 lines (55 loc) · 1.58 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, {useEffect, useState} from 'react';
import useIsBrowser from '@docusaurus/useIsBrowser';
import mermaid from 'mermaid';
import type {Props} from '@theme/Mermaid';
/**
* Assign a unique ID to each mermaid svg as per requirements
* of `mermaid.render`.
*/
let id = 0;
export default function Mermaid({value}: Props): JSX.Element {
// When theme updates, rerender the SVG.
const [svg, setSvg] = useState<string>('');
const isBrowser = useIsBrowser();
useEffect(() => {
const render = () => {
mermaid.render(`mermaid-svg-${id.toString()}`, value, (renderedSvg) =>
setSvg(renderedSvg),
);
id += 1;
};
render();
if (isBrowser) {
const html: HTMLHtmlElement = document.querySelector('html')!;
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (
mutation.type !== 'attributes' ||
mutation.attributeName !== 'data-mermaid'
) {
continue;
}
render();
break;
}
});
observer.observe(html, {attributes: true});
return () => {
try {
observer.disconnect();
} catch {
// Do nothing
}
};
}
return undefined;
}, [isBrowser, value]);
// eslint-disable-next-line react/no-danger
return <div dangerouslySetInnerHTML={{__html: svg}} />;
}