microsoft/qdk
Publicmirrored from https://github.com/microsoft/qdkAvailable
source/vscode/src/webview/theme.ts
54lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | const themeAttribute = "data-vscode-theme-kind"; |
| 5 | |
| 6 | function updateGitHubTheme() { |
| 7 | let isDark = true; |
| 8 | |
| 9 | const themeType = document.body.getAttribute(themeAttribute); |
| 10 | |
| 11 | switch (themeType) { |
| 12 | case "vscode-light": |
| 13 | case "vscode-high-contrast-light": |
| 14 | isDark = false; |
| 15 | break; |
| 16 | default: |
| 17 | isDark = true; |
| 18 | } |
| 19 | |
| 20 | // Update the stylesheet href |
| 21 | document.head.querySelectorAll("link").forEach((el) => { |
| 22 | const ref = el.getAttribute("href"); |
| 23 | if (ref && ref.includes("github-markdown")) { |
| 24 | const newVal = ref.replace( |
| 25 | /(dark\.css)|(light\.css)/, |
| 26 | isDark ? "dark.css" : "light.css", |
| 27 | ); |
| 28 | el.setAttribute("href", newVal); |
| 29 | } |
| 30 | }); |
| 31 | } |
| 32 | |
| 33 | export function setThemeStylesheet() { |
| 34 | // We need to add the right Markdown style-sheet for the theme. |
| 35 | |
| 36 | // For VS Code, there will be an attribute on the body called |
| 37 | // "data-vscode-theme-kind" that is "vscode-light" or "vscode-high-contrast-light" |
| 38 | // for light themes, else assume dark (will be "vscode-dark" or "vscode-high-contrast"). |
| 39 | |
| 40 | // Use a [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) |
| 41 | // to detect changes to the theme attribute. |
| 42 | const callback = (mutations: MutationRecord[]) => { |
| 43 | for (const mutation of mutations) { |
| 44 | if (mutation.attributeName === themeAttribute) { |
| 45 | updateGitHubTheme(); |
| 46 | } |
| 47 | } |
| 48 | }; |
| 49 | const observer = new MutationObserver(callback); |
| 50 | observer.observe(document.body, { attributeFilter: [themeAttribute] }); |
| 51 | |
| 52 | // Run it once for initial value |
| 53 | updateGitHubTheme(); |
| 54 | } |
| 55 | |