Skip to content

Follow the system appearance with a light and a dark theme - #32

Merged
Masakai merged 8 commits into
Masakai:mainfrom
harasuke:feat/follow-system-theme
Nov 7, 2026
Merged

Masakai merged 8 commits into
Masakai:mainfrom
harasuke:feat/follow-system-theme

Conversation

@harasuke

@harasuke harasuke commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

Hi @Masakai, this lets Settings > Appearance pick one theme for light mode and one for dark mode, and the preview follows the Mac's appearance in every window.

Problem

Only GitHub Light and GitHub Dark followed the system, and only when the appearance changed while a window was open. RenderViewModel read selectedThemeId once in init, and MarkdownRenderView reacted to onChange(of: colorScheme), which does not fire for the initial value. With GitHub Light saved and the Mac already dark, every window opened light: the ones restored at launch and the ones opened later alike. The Help window never followed at all. In practice the preview colours depended on how each window had been opened, and the other four themes could not follow the appearance in any way.

Opening a document with a dark theme also flashed white: the WKWebView paints its own white background until the page arrives, and renderer.html starts with github-light.css until rendererDidLoad() sends the real theme.

What changes

  • 1a70c1f: each MarkdownTheme carries the hex of its --bg-color and a light or dark slot. ThemePreference reads the four keys in one place: followSystemAppearance, lightThemeId, darkThemeId, plus the existing selectedThemeId as the fixed theme. A test checks every hex against the theme's CSS.
  • 8caf79b: RenderViewModel decides the theme in init, from NSApp.effectiveAppearance and the preference, and observes effectiveAppearance itself, so restored windows, windows opened later, the welcome window and Help all behave the same. The view no longer watches colorScheme.
  • 2194e42: no more white flash. RendererWebView no longer draws a background, and SwiftUI paints the theme's background behind it. A WKUserScript injected at document start tells the page the theme, and mdviewer.js, which runs in <head> right after the theme's <link>, swaps the stylesheet before the first paint. The script is replaced whenever the theme changes, so a reload after a WebContent crash comes back in the right theme too.
  • 6c4dc10: Settings > Appearance gets a "Follow System Appearance" switch. When it is on, it shows "Light Theme" and "Dark Theme" menus, each listing only the themes for that slot. When it is off, it shows the single "Theme" menu as before. The toolbar theme menu gains "Use Settings Theme". English and Japanese strings.
  • 66a739c: README and help, in English and Japanese. I left the CHANGELOG to you for the release.
  • bc61e97: tests that check the initial theme and the diagram redraw by their outcome.
  • 8b756f2: Mermaid bakes its colours into the SVG, so diagrams are drawn again on a light/dark switch. They are redrawn only when one is actually on screen: the page reports it in renderComplete (hasDiagrams, from the .mermaid elements in #content), instead of guessing from the word "mermaid" in the source.

Design choices

  • Existing users keep what they had. When the new keys are missing, their defaults come from selectedThemeId. With GitHub Light, GitHub Dark or no choice at all, the switch starts on. With Solarized, Dracula or Nord, it starts off and the chosen theme stays fixed. load() never writes. save() writes all four keys, so once something is changed in Settings, the derived defaults cannot shift later.
  • One visible change, probably worth a line in the release notes: with GitHub Dark chosen and the Mac in light mode, windows now open in GitHub Light. To keep GitHub Dark, turn "Follow System Appearance" off.
  • A theme chosen from the toolbar stays on that window. When the system appearance or Settings change, the window keeps it until "Use Settings Theme" is chosen. As before, it is not saved. The menu items are toggles, so macOS draws its own checkmarks.
  • No inline background on <html>. It would outlive the next setTheme and stop the body's background from reaching the canvas, leaving a short document in two colours.
  • Small layout change: the Settings window is 40pt taller (340 → 380) to fit the extra row.
  • No project file changes: nothing in project.yml / project.pbxproj changed.

Testing

  • Full MDViewerTests suite green (xcodebuild test): 358 tests. The new tests are in MarkdownThemeTests (migration defaults, slots, save/load round trip), RenderViewModelTests (appearance flips, pinning, Use Settings Theme, diagram redraw) and WebRendererViewTests (initial theme already applied while <body> is parsed, hasDiagrams in renderComplete). The appearance is injected, so the tests do not depend on the Mac running them.
  • On a real build, with the Mac in dark mode, I checked:
    • restored windows and a newly opened one start in the dark theme;
    • switching the Mac to light changes every window live;
    • a theme pinned from the toolbar survives switches in both directions, with correct checkmarks, and "Use Settings Theme" releases it;
    • a screen recording (~20 fps) of opening a document shows no bright frame;
    • PDF export with a light theme still gives a white page.

Settings is about to choose a light theme and a dark theme instead of a
single one, and a window needs the theme's background before its
stylesheet has loaded. MarkdownTheme now carries the hex of its
--bg-color, and lightThemes / darkThemes list the themes for each slot.

ThemePreference reads the four keys in one place: followSystemAppearance,
lightThemeId and darkThemeId, plus the existing selectedThemeId as the
fixed theme. When the new keys are missing, their defaults come from
selectedThemeId, so nobody sees a change after updating: GitHub Light,
GitHub Dark or no choice at all follows the system, any other theme stays
fixed and fills its own slot. An unknown id, or a theme in the wrong
slot, falls back to that slot's default.

load() never writes. save() writes all four keys, so once the user
changes something in Settings the derived defaults cannot shift under
them (a Nord user picking GitHub Dark as fixed theme would otherwise
start following the system).

A test checks every hex against the --bg-color in the theme's CSS.
Only GitHub Light and GitHub Dark followed the system, and only when the
appearance changed: RenderViewModel read selectedThemeId once in init, and
MarkdownRenderView reacted to onChange(of: colorScheme), which does not
fire for the initial value. With GitHub Light saved and the Mac already
dark, every window opened light. The Help window never followed at all.

RenderViewModel now decides the theme in init, from
NSApp.effectiveAppearance and ThemePreference, and observes
effectiveAppearance itself. Windows restored at launch, windows opened
later, a welcome window that later opens a document and the Help window
all get the same treatment, and the view no longer watches colorScheme.
Both inputs are injectable, so the tests no longer depend on the
appearance of the Mac running them.

Choosing a theme from the toolbar now pins it on that window, even when
it is the theme already shown: system and Settings changes leave the
window alone until useSettingsTheme() clears the pin. As before, the
choice is never written to the settings. .previewThemeChanged no longer
carries a theme id; each window reloads the preference instead.
Opening a document with a dark theme flashed white: the WKWebView paints
its own white background until the page arrives, and renderer.html starts
with github-light.css until rendererDidLoad() sends the real theme.

RendererWebView no longer draws a background, and SwiftUI paints the
theme's background behind it, in the document window and in Help. A
WKUserScript injected at document start tells the page the theme, and
mdviewer.js, which runs in <head> right after the theme's <link>, swaps
the stylesheet and sets Mermaid up for light or dark before the first
paint. The script is replaced whenever the window's theme changes, so a
reload after a WebContent crash comes back in the right theme too.

No inline background is set on <html>: it would outlive the next
setTheme and stop the body's background from reaching the canvas, leaving
a short document in two colours.

setTheme only re-initialises Mermaid, so diagrams already drawn kept their
old colours. When the theme switches between light and dark and the
document contains a Mermaid block, it is rendered again, the same way the
math delimiter setting re-renders.
Settings > Appearance gets a "Follow System Appearance" switch. When it
is on, it shows "Light Theme" and "Dark Theme" menus, each listing only
the themes for that slot; when it is off, the single "Theme" menu as
before. The view keeps a ThemePreference instead of @AppStorage, because
the defaults of the new keys depend on selectedThemeId, and saves all
four keys on every change. The Settings window is 40pt taller to fit the
extra row.

The toolbar theme menu starts with "Use Settings Theme", checked while
the window follows Settings, and checks the pinned theme otherwise. The
items are toggles, so macOS draws its own checkmarks in the menu.

The new strings are added in English and Japanese.
The help entry for the toolbar theme menu also mentions Use Settings
Theme, and points to Settings > Appearance for following the system.
The initial-theme test asserted only once the page had loaded, so it
stayed green if the stylesheet swap moved into a DOMContentLoaded listener
or mdviewer.js got defer, either of which brings the flash back. It now
records the stylesheet while <body> is being parsed.

The Mermaid redraw was only tested through needsRerenderForThemeChange.
Two tests now flip the appearance on a view model with a recording web
view, and check that the content is rendered again after the theme when
it has a diagram, and not when it has none.
Whether a theme switch had to render the document again was decided by
looking for the word "mermaid" in the Markdown, so a document that only
mentions Mermaid, in prose or in a code block of another language, was
rendered again for nothing.

The page now says it itself: renderComplete carries hasDiagrams, read
from the .mermaid elements in #content. It describes what is shown, so
when a render that produced nothing keeps the previous content, the
answer is still right. RenderViewModel keeps the last value, and while
a render it sent has not completed yet it redraws anyway, since the
page has not answered for the new content. A reloaded page starts with
no diagram.
@Masakai

Masakai commented Nov 1, 2026

Copy link
Copy Markdown
Owner

Thanks for this. The full MDViewerTests suite passes here too (358 tests at 8b756f2).

I found one thing while testing: a light/dark switch can move the reading position in documents with many Mermaid diagrams.

What I measured

I scrolled so that a heading sat at the top of the viewport, then called MDViewer.setTheme followed by MDViewer.setContent, the same order apply() uses:

Document Viewport height scrollY before scrollY after Heading position
12 diagrams 400px 7178 9986 0 → -2808px
1 diagram, at the top 700px 4168 4168 unchanged

In the first case, the document is about 6000px tall right after innerHTML is replaced, because the diagrams are not drawn yet. scrollY is pushed back to 5617, and it ends at 9986 once the diagrams are in. I did not work out why it ends there.

So this seems to happen when the reading position is further down than the height of the document without its diagrams, though I only measured these two cases.

I measured this with a WKWebView running the real renderer in a test window, not in the full app.

Why it matters here

The render path itself is not new in this PR, and I would expect a live reload to behave the same way on main, though I have not measured that. What this PR adds is a new trigger: with an automatic appearance, the switch happens without the user doing anything, in every open window showing such a document.

A possible fix

Remember the position before contentEl.innerHTML = html in renderContent, and restore it after mermaid.run finishes. I have not tried this.

Would you be able to look at this in this PR?

Replacing #content turns drawn diagrams back into source text, so the
page gets shorter and the reading position moves. Hold the position and
the page height until the latest render's diagrams are drawn.

A navigation during that time (sidebar heading, search, in-page link)
wins over the restore. A render waits for the theme stylesheet, because
a diagram drawn before it has loaded can come out taller. Pages without
drawn diagrams are not held, so edits to them cost the same as before.
@harasuke

harasuke commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

@Masakai Sorry for the slow reply, I have been busy and could not get to this sooner. Thanks for measuring this. I reproduced it and pushed a fix in ab7b994.

What was happening

There were two separate causes:

  1. Replacing #content turns the drawn diagrams back into source text, so the page gets much shorter and scrollY is pulled back, as you measured. With 12 diagrams and a 400px viewport, a heading moved by -1011px in my test. Like you, I did not work out exactly why it ends where it does; the fix does not depend on that.
  2. If the first diagram was drawn before the new theme's stylesheet had loaded, it could come out taller (576px instead of 416px), which moved everything below it by 160px. Applying the theme 300ms earlier made this go away.

The fix

It follows your suggestion, with a few additions:

  • The position is saved when setContent starts, and #content keeps its old height until the latest render's diagrams are drawn. The position is restored then.
  • If the reader navigates during that time (sidebar heading, search, in-page link), the page ends on that target instead, as laid out after the diagrams are drawn. Without this, the restore would have undone the navigation.
  • A render waits for the theme stylesheet to load, for at most 2s. setTheme no longer reassigns the href when the theme is unchanged.
  • This only applies when the page shows drawn diagrams, so edits to documents without diagrams are not affected (26-27ms per render on a 400-section document, same as before).

Live edits are covered too

You expected a live reload to behave the same way, and it does: re-rendering the document with one extra word, as an edit does, moved a heading by -1449px on this branch before the fix, and by 0 after it. I did not run this on main, but this PR does not change that render path. The fix goes beyond what you reported, so tell me if you would rather have that part in a separate PR.

Testing

  • 18 new tests in RendererScriptTests, each run 10 times in a row, all passing. The full suite passes (376 tests).
  • They cover each kind of navigation during a redraw, two redraws in a row, an invalid diagram and a render that throws.
  • I also checked it by hand in the app with the editor open: the preview stays in place after an edit.
  • The tests use a private WebKit preference (hiddenPageDOMTimerThrottlingEnabled), because timers in a hidden window are too slow for Mermaid to finish. They skip themselves if that preference goes away.

One behaviour to check with you

If the reader scrolls with the wheel while diagrams are being redrawn, that scroll is undone when the position is restored. A theme switch redraws quickly, but during a burst of edits this window lasts until the last render's diagrams are drawn. I see this as the expected behaviour and it feels right to me, since the reader stays where they were. Does that work for you, or would you prefer it to behave differently?

@Masakai
Masakai merged commit cf531de into Masakai:main Nov 7, 2026
3 checks passed
@Masakai

Masakai commented Nov 7, 2026

Copy link
Copy Markdown
Owner

Thanks for the fix, and for the careful write-up. No worries about the timing.

I ran the full MDViewerTests suite at ab7b994: 376 tests, 0 failures, 0 skipped, so the 18 new tests ran here too rather than skipping themselves. I merged it in cf531de, and it is released in v1.13.0 (build 40).

On your two questions:

Wheel scrolling during a redraw. That works for me. Staying where the reader was is the point of the change, and a theme switch redraws quickly. If the window during a burst of edits turns out to be noticeable in practice, we can look at it separately.

Live edits in this PR. Keeping it here is fine. It is the same render path and the same cause, so I would rather have them together than split.

Thanks again for the light and dark themes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants