diff --git a/src/init.js b/src/init.js index 81bd888..3a2025d 100644 --- a/src/init.js +++ b/src/init.js @@ -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 ); diff --git a/src/link/colorScheme.js b/src/link/colorScheme.js new file mode 100644 index 0000000..02cbb8d --- /dev/null +++ b/src/link/colorScheme.js @@ -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 ] } ); +};