Skip to content

Commit

Permalink
fix(graph): take vscode light/dark theme into account (#21208)
Browse files Browse the repository at this point in the history
  • Loading branch information
MaxKless authored Jan 18, 2024
1 parent e979109 commit e4e7f54
Showing 1 changed file with 31 additions and 4 deletions.
35 changes: 31 additions & 4 deletions graph/ui-theme/src/lib/theme-resolver.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,29 @@ export const localStorageThemeKey = 'nx-dep-graph-theme';
export type Theme = 'light' | 'dark' | 'system';
export let currentTheme: Theme;

// listen for (prefers-color-scheme: dark) changes
function mediaListener(ev: MediaQueryListEvent) {
const resolver = ev.matches ? 'dark' : 'light';
toggleHtmlClass(resolver);
currentTheme = resolver;
}

// listen for body.vscode-dark changes
const vscodeDarkOberserver = new MutationObserver((mutations) => {
for (let mutation of mutations) {
if (mutation.type === 'attributes') {
const isVSCodeDark = document.body.classList.contains('vscode-dark');
const isVSCodeLight = document.body.classList.contains('vscode-light');
if (!isVSCodeDark && !isVSCodeLight) {
return;
}
const resolver = isVSCodeDark ? 'dark' : 'light';
toggleHtmlClass(resolver);
currentTheme = resolver;
}
}
});

function toggleHtmlClass(theme: Theme) {
if (theme === 'dark') {
htmlEl.classList.add('dark');
Expand All @@ -25,9 +42,14 @@ export function themeInit() {
themeResolver(theme);
}

export function getSystemTheme() {
const darkMedia = window.matchMedia('(prefers-color-scheme: dark)');
return darkMedia.matches ? 'dark' : 'light';
export function getSystemTheme(): 'light' | 'dark' {
const isVSCodeDark = document.body.classList.contains('vscode-dark');
const isVSCodeLight = document.body.classList.contains('vscode-light');
if (isVSCodeDark || isVSCodeLight) {
return isVSCodeDark ? 'dark' : 'light';
}
const isDarkMedia = window.matchMedia('(prefers-color-scheme: dark)').matches;
return isDarkMedia || isVSCodeDark ? 'dark' : 'light';
}

export function themeResolver(theme: Theme) {
Expand All @@ -38,12 +60,17 @@ export function themeResolver(theme: Theme) {
const darkMedia = window.matchMedia('(prefers-color-scheme: dark)');
if (theme !== 'system') {
darkMedia.removeEventListener('change', mediaListener);
vscodeDarkOberserver.disconnect();
toggleHtmlClass(theme);
currentTheme = theme;
} else {
const resolver = darkMedia.matches ? 'dark' : 'light';
const resolver = getSystemTheme();

darkMedia.addEventListener('change', mediaListener);
vscodeDarkOberserver.observe(document.body, {
attributes: true,
attributeFilter: ['class'],
});
toggleHtmlClass(resolver);
currentTheme = resolver;
}
Expand Down

0 comments on commit e4e7f54

Please sign in to comment.