Path: blob/main/extensions/mermaid-chat-features/chat-webview-src/index.ts
3520 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/4import mermaid, { MermaidConfig } from 'mermaid';56function getMermaidTheme() {7return document.body.classList.contains('vscode-dark') || document.body.classList.contains('vscode-high-contrast')8? 'dark'9: 'default';10}1112type State = {13readonly diagramText: string;14readonly theme: 'dark' | 'default';15};1617let state: State | undefined = undefined;1819function init() {20const diagram = document.querySelector('.mermaid');21if (!diagram) {22return;23}2425const theme = getMermaidTheme();26state = {27diagramText: diagram.textContent ?? '',28theme29};3031const config: MermaidConfig = {32startOnLoad: true,33theme,34};35mermaid.initialize(config);36}3738function tryUpdate() {39const newTheme = getMermaidTheme();40if (state?.theme === newTheme) {41return;42}4344const diagramNode = document.querySelector('.mermaid');45if (!diagramNode || !(diagramNode instanceof HTMLElement)) {46return;47}4849state = {50diagramText: state?.diagramText ?? '',51theme: newTheme52};5354// Re-render55diagramNode.textContent = state?.diagramText ?? '';56delete diagramNode.dataset.processed;5758mermaid.initialize({59theme: newTheme,60});61mermaid.run({62nodes: [diagramNode]63});64}6566// Update when theme changes67new MutationObserver(() => {68tryUpdate();69}).observe(document.body, { attributes: true, attributeFilter: ['class'] });7071init();72737475