Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

T345056: dark mode support #110

Merged
merged 16 commits into from
Apr 5, 2024
21 changes: 16 additions & 5 deletions src/init.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
/* global wikipediapreview_init_options */
wikipediaPreview.init( {
root: document,
/* eslint-disable-next-line camelcase */
detectLinks: !! wikipediapreview_init_options.detectLinks,
} );
import { getColorScheme, observeDarkModePluginActivation } from './link/colorScheme';

const init = ( scheme ) => {
wikipediaPreview.init( {
root: document,
/* eslint-disable-next-line camelcase */
detectLinks: !! wikipediapreview_init_options.detectLinks,
prefersColorScheme: scheme,
} );
};

// Initial init on first page load
init( getColorScheme() );

// Re-init as needed as the color scheme changes
observeDarkModePluginActivation( init );
31 changes: 31 additions & 0 deletions src/link/colorScheme.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const attNameWPDarkModePluginActive = 'data-wp-dark-mode-active';
const attNameWPDarkModePluginInstalled = 'data-wp-dark-mode-preset';

const isWPDarkModePluginActive = () => {
return document.documentElement.hasAttribute( attNameWPDarkModePluginActive );
};

const isWPDarkModePluginInstalled = () => {
return document.documentElement.hasAttribute( attNameWPDarkModePluginInstalled );
};

export const getColorScheme = () => {
if ( isWPDarkModePluginInstalled() && isWPDarkModePluginActive() ) {
return 'dark';
} else if ( isWPDarkModePluginInstalled() && ! isWPDarkModePluginActive() ) {
return 'light';
}
return 'detect';
};

export const observeDarkModePluginActivation = ( callback ) => {
// eslint-disable-next-line no-undef
const observer = new MutationObserver( () => {
if ( isWPDarkModePluginActive() ) {
callback( 'dark' );
} else {
callback( 'light' );
}
} );
observer.observe( document.documentElement, { attributeFilter: [ attNameWPDarkModePluginActive ] } );
};
Loading