From ee009ebec8be9721e379e7b483f4fe70d86ad1e2 Mon Sep 17 00:00:00 2001 From: Mykhailo <43426404+mykh-hailo@users.noreply.github.com> Date: Sat, 21 Mar 2026 13:44:33 +0100 Subject: [PATCH] Support dark/light theme images in markdown (#36922) This PR matches GitHub's behavior more closely on how to render Markdown images in light/dark mode. Images with source suffix `#gh-dark-mode-only` / `#gh-light-mode-only` will only show when the correct theme is requested. Closes: #35545 --------- Co-authored-by: wxiaoguang --- web_src/css/markup/content.css | 10 ++++++++++ web_src/js/webcomponents/index.ts | 11 +++++++++++ 2 files changed, 21 insertions(+) diff --git a/web_src/css/markup/content.css b/web_src/css/markup/content.css index 34e7de8c47..047b03fa19 100644 --- a/web_src/css/markup/content.css +++ b/web_src/css/markup/content.css @@ -316,6 +316,16 @@ In markup content, we always use bottom margin for all elements */ box-sizing: initial; } +/* GitHub-style dark/light image switching. + These fragments are kept in the rendered HTML as part of the `src` attribute. + We decide which to show via `data-gitea-theme-dark` on ``, which is + mirrored from `--is-dark-theme` in JS (so it also works with auto/custom themes). +*/ +html[data-gitea-theme-dark="true"] .markup img[src*="#gh-light-mode-only"], +html[data-gitea-theme-dark="false"] .markup img[src*="#gh-dark-mode-only"] { + display: none; +} + .file-view.markup { padding: 1em 2em; font-size: 16px; diff --git a/web_src/js/webcomponents/index.ts b/web_src/js/webcomponents/index.ts index f2d725814d..2493f56ac9 100644 --- a/web_src/js/webcomponents/index.ts +++ b/web_src/js/webcomponents/index.ts @@ -2,3 +2,14 @@ import './polyfills.ts'; import './relative-time.ts'; import './origin-url.ts'; import './overflow-menu.ts'; +import {isDarkTheme} from '../utils.ts'; + +function initPageThemeDarkLight() { + // Set page's theme color preference as early as possible, to avoid flicker of wrong theme color during page load. + const sync = () => document.documentElement.setAttribute('data-gitea-theme-dark', String(isDarkTheme())); + sync(); + // Track system theme changes in case Gitea is using "auto" theme. + window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', sync); +} + +initPageThemeDarkLight();