|
13 | 13 | // limitations under the License. |
14 | 14 |
|
15 | 15 | import { Controller } from '@hotwired/stimulus' |
| 16 | +import mermaid from 'mermaid' |
16 | 17 |
|
17 | 18 | export class ReadmeController extends Controller { |
| 19 | + frameLoaded() { |
| 20 | + this.navigateToAnchorFromLocation() |
| 21 | + this.renderMermaidDiagrams() |
| 22 | + } |
| 23 | + |
| 24 | + async renderMermaidDiagrams() { |
| 25 | + // Replace all Mermaid chart sources with rendered diagrams. |
| 26 | + const mermaidSectionElements = document.querySelectorAll('section[data-type="mermaid"]') |
| 27 | + for (const [index, mermaidSectionElement] of Array.from(mermaidSectionElements).entries()) { |
| 28 | + // No need to parse the JSON, the chart source is in a `data-plain` attribute. |
| 29 | + const mermaidDataElement = mermaidSectionElement.querySelector('[data-plain]') |
| 30 | + if (!mermaidDataElement) continue |
| 31 | + const chartDefinition = mermaidDataElement.getAttribute('data-plain') |
| 32 | + if (!chartDefinition) continue |
| 33 | + |
| 34 | + // Make a container with *both* light and dark charts. |
| 35 | + const chartContainer = document.createElement('div') |
| 36 | + chartContainer.classList.add('mermaid-chart') |
| 37 | + mermaidDataElement.appendChild(chartContainer) |
| 38 | + |
| 39 | + // The documentation says not to call `initialize` more than once. That said, it's |
| 40 | + // the only way to switch themes and therefore the only way to get this working. |
| 41 | + mermaid.initialize({ theme: 'default', nodeSpacing: 50, rankSpacing: 50, curve: 'basis' }) |
| 42 | + const lightRenderResult = await mermaid.render(`mermaid-chart-light-${index}`, chartDefinition) |
| 43 | + chartContainer.insertAdjacentHTML('beforeend', lightRenderResult.svg) |
| 44 | + |
| 45 | + mermaid.initialize({ theme: 'dark', nodeSpacing: 50, rankSpacing: 50, curve: 'basis' }) |
| 46 | + const darkRenderResult = await mermaid.render(`mermaid-chart-dark-${index}`, chartDefinition) |
| 47 | + chartContainer.insertAdjacentHTML('beforeend', darkRenderResult.svg) |
| 48 | + } |
| 49 | + } |
| 50 | + |
18 | 51 | navigateToAnchorFromLocation() { |
19 | 52 | // If the browser has an anchor in the URL that may be inside the README then |
20 | 53 | // we should attempt to scroll it into view once the README is loaded. |
|
0 commit comments