Fix race condition when looking up current auto/light/dark theme

Related feedback:
- e2dd008388 (commitcomment-104105757)
This commit is contained in:
Raymond Hill 2023-03-12 11:20:54 -04:00
parent 3da9fe08e1
commit caeb848c56
No known key found for this signature in database
GPG Key ID: 25E1490B761470C2
2 changed files with 18 additions and 6 deletions

View File

@ -26,6 +26,7 @@
/******************************************************************************/
import { dom, qs$ } from './dom.js';
import { getActualTheme } from './theme.js';
/******************************************************************************/
@ -45,10 +46,14 @@ const cmEditor = new CodeMirror(qs$('#content'), {
});
uBlockDashboard.patchCodeMirrorEditor(cmEditor);
if ( dom.cl.has(dom.html, 'dark') ) {
dom.cl.add('#content .cm-s-default', 'cm-s-night');
dom.cl.remove('#content .cm-s-default', 'cm-s-default');
}
vAPI.messaging.send('dom', { what: 'uiStyles' }).then(response => {
if ( typeof response !== 'object' || response === null ) { return; }
if ( getActualTheme(response.uiTheme) === 'dark' ) {
dom.cl.add('#content .cm-s-default', 'cm-s-night');
dom.cl.remove('#content .cm-s-default', 'cm-s-default');
}
});
// Convert resource URLs into clickable links to code viewer
cmEditor.addOverlay({

View File

@ -21,8 +21,9 @@
'use strict';
function setTheme(theme, propagate = false) {
if ( theme === 'auto' ) {
function getActualTheme(nominalTheme) {
let theme = nominalTheme || 'light';
if ( nominalTheme === 'auto' ) {
if ( typeof self.matchMedia === 'function' ) {
const mql = self.matchMedia('(prefers-color-scheme: dark)');
theme = mql instanceof Object && mql.matches === true
@ -32,6 +33,11 @@ function setTheme(theme, propagate = false) {
theme = 'light';
}
}
return theme;
}
function setTheme(theme, propagate = false) {
theme = getActualTheme(theme);
let w = self;
for (;;) {
const rootcl = w.document.documentElement.classList;
@ -139,6 +145,7 @@ function setAccentColor(
}
export {
getActualTheme,
setTheme,
setAccentColor,
};