Skip to content

Commit 2a150fb

Browse files
committed
Make auto mode behave according to system preference
1 parent b516acc commit 2a150fb

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

src/doc/common/static/jupyter-sphinx-furo.js

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Change the editor theme of all CodeMirror cells according to the furo (dark) mode
1+
// Change the editor theme according to the furo light/dark/auto mode
22
function changeTheme(editor, theme) {
33
if (theme === 'dark') {
44
editor.setOption('theme', 'monokai'); // the same with pygments dark style in conf.py
@@ -9,19 +9,42 @@ function changeTheme(editor, theme) {
99
}
1010
}
1111

12-
// Use the theme data of the document.body element set by setTheme function
12+
// Change the editor theme of all CodeMirror cells
13+
function changeThemeAll(theme) {
14+
const querySet = document.querySelectorAll('.CodeMirror');
15+
for (var i = 0; i < querySet.length; i++) {
16+
changeTheme(querySet[i].CodeMirror, theme);
17+
}
18+
}
19+
20+
// Use the theme data of the body element set by setTheme function
1321
// defined in https://github.com/pradyunsg/furo/blob/main/src/furo/assets/scripts/furo.js
1422
const body = document.body;
1523
const observer1 = new MutationObserver((mutationsList) => {
1624
for (let mutation of mutationsList) {
1725
if (mutation.type === 'attributes' && mutation.attributeName === 'data-theme') {
1826
const theme = body.dataset.theme;
19-
const querySet = document.querySelectorAll('.CodeMirror');
20-
for (var i = 0; i < querySet.length; i++) {
21-
changeTheme(querySet[i].CodeMirror, theme);
22-
}}}});
27+
changeThemeAll(theme);
28+
}
29+
}
30+
});
2331
observer1.observe(body, { attributes: true });
2432

33+
34+
// In the furo auto mode, we watch prefers-color-scheme and use the theme data
35+
// of the body element to change the CodeMirror editor theme
36+
const prefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)');
37+
38+
function handlePrefersColorSchemeChange(e) {
39+
const theme = body.dataset.theme;
40+
if (theme === 'auto') {
41+
changeThemeAll(theme);
42+
}
43+
}
44+
45+
prefersDarkMode.addEventListener('change', handlePrefersColorSchemeChange);
46+
47+
2548
// Change the editor theme of a new CodeMirror cell.
2649
const callback = function(mutationsList, observer) {
2750
for(const mutation of mutationsList) {
@@ -89,4 +112,3 @@ thebelab.on("status", function (evt, data) {
89112
kernel.requestExecute({code: "%display latex"});
90113
}
91114
});
92-

0 commit comments

Comments
 (0)