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 );
30 changes: 30 additions & 0 deletions src/link/colorScheme.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const attNameWPDarkModePlugin = 'data-wp-dark-mode-active';

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

export const getColorScheme = () => {
if ( isWPDarkModePluginActive() ) {
hueitan marked this conversation as resolved.
Show resolved Hide resolved
return 'dark';
}
return 'detect';
};

export const observeDarkModePluginActivation = ( callback ) => {
// eslint-disable-next-line no-undef
const observer = new MutationObserver( ( mutationsList ) => {
for ( const mutation of mutationsList ) {
if ( mutation.type === 'attributes' && mutation.attributeName === attNameWPDarkModePlugin ) {
stephanebisson marked this conversation as resolved.
Show resolved Hide resolved
if ( isWPDarkModePluginActive() ) {
callback( 'dark' );
} else {
callback( 'light' );
}
break;
}
}
} );

observer.observe( document.documentElement, { attributes: true } );
hueitan marked this conversation as resolved.
Show resolved Hide resolved
};
Loading