From c2aa4bbe5063e2c57a23e28de899863d3d29d27e Mon Sep 17 00:00:00 2001 From: shenxianpeng Date: Sat, 25 Apr 2026 01:30:22 +0300 Subject: [PATCH] Fix theme color mode switching when highlight.js is disabled --- docs/about/release-notes.md | 1 + mkdocs/tests/theme_tests.py | 27 +++++++++++++++++++++++++++ mkdocs/themes/mkdocs/js/darkmode.js | 14 ++++++++------ 3 files changed, 36 insertions(+), 6 deletions(-) diff --git a/docs/about/release-notes.md b/docs/about/release-notes.md index 3449100c..03c358da 100644 --- a/docs/about/release-notes.md +++ b/docs/about/release-notes.md @@ -30,6 +30,7 @@ The current members of the MkDocs-NG team. * Fix anchor link validation so `mkdocs build -v --strict` still fails when missing anchors are reported as warnings. #30 * Fix `validation.links.not_found` is always reported as INFO for excluded pages. #32 * Fix `mkdocs serve` cleanup so temporary site directories are removed when the process receives `SIGTERM`. #36 +* Fix mkdocs theme color mode switching when `highlightjs` is disabled. #39 ### Maintenance diff --git a/mkdocs/tests/theme_tests.py b/mkdocs/tests/theme_tests.py index f57f166b..8d9fe48f 100644 --- a/mkdocs/tests/theme_tests.py +++ b/mkdocs/tests/theme_tests.py @@ -1,4 +1,6 @@ import os +import shutil +import subprocess import unittest from unittest import mock @@ -125,3 +127,28 @@ def test_empty_config_file(self): "locale": parse_locale("en"), }, ) + + @unittest.skipUnless(shutil.which("node"), "node is not installed") + def test_darkmode_without_highlightjs_stylesheets(self): + darkmode_js = os.path.join(theme_dir, "mkdocs", "js", "darkmode.js") + script = f""" + global.localStorage = {{ getItem: () => null, setItem: () => {{}} }}; + global.window = {{ + matchMedia: () => ({{ + matches: false, + addEventListener: () => {{}}, + removeEventListener: () => {{}}, + }}), + }}; + global.document = {{ + documentElement: {{ + getAttribute: () => 'light', + setAttribute: () => {{}}, + }}, + getElementById: () => null, + querySelectorAll: () => [], + }}; + require({darkmode_js!r}); + """ + + subprocess.run(["node", "-e", script], check=True) diff --git a/mkdocs/themes/mkdocs/js/darkmode.js b/mkdocs/themes/mkdocs/js/darkmode.js index 30be9905..d49d7d33 100644 --- a/mkdocs/themes/mkdocs/js/darkmode.js +++ b/mkdocs/themes/mkdocs/js/darkmode.js @@ -3,12 +3,14 @@ function setColorMode(mode) { var hljs_light = document.getElementById('hljs-light'), hljs_dark = document.getElementById('hljs-dark'); document.documentElement.setAttribute('data-bs-theme', mode); - if (mode == 'dark') { - hljs_light.disabled = true; - hljs_dark.disabled = false; - } else { - hljs_dark.disabled = true; - hljs_light.disabled = false; + if (hljs_light && hljs_dark) { + if (mode == 'dark') { + hljs_light.disabled = true; + hljs_dark.disabled = false; + } else { + hljs_dark.disabled = true; + hljs_light.disabled = false; + } } }