ReviewOS

stacks/stx

Two independent pre-paint theme injectors: site-builder's FOUC guard ignores app.colorMode, applies the wrong class pre-paint, and pushes <meta charset> past 1024 bytes

#1812
Closed glennmichael123 opened this 22 days ago · 2 comments
22 days ago

Found while verifying the #1803 fix against a real app (bughq). The #1803 fix works — the color-mode boot script is now ahead of the stores bundle. But there is a second, independent pre-paint theme system that is emitted before it, does not know it exists, and disagrees with it about both the storage key and the mechanism.

Two injectors, no shared contract

site-builder/theme.tscolor-mode-boot.ts
markerdata-stx-theme-guarddata-stx-color-mode-boot
config sourcesite.themeapp.colorMode
storage keyopts.storageKey ?? 'theme'configured (bughq_theme)
mechanismclassList.add/remove('dark')setAttribute('data-theme', …)
defaultopts.default ?? 'dark'initialMode
also emitsa document-level click handler for #theme-toggle—

injectThemeBootstrap (packages/stx/src/site-builder/theme.ts:120) is guarded only by "is it already in the HTML":

if (!html.includes('__stxThemeGuard') && /<head\b[^>]*>/i.test(html)) {
  const guard = `<script data-stx-theme-guard="1">${FOUC_SCRIPT(defaultTheme, storageKey, lightColor, darkColor)};window.__stxThemeGuard=1;</script>`
  html = html.replace(/<head\b([^>]*)>/i, `<head$1>\n  ${guard}`)
}

So an app that configures app.colorMode and never configures site.theme still gets the legacy guard, running on defaults it never chose. That is the bughq case: config/ui.ts sets app.colorMode to { storageKey: 'bughq_theme', attribute: 'data-theme', darkClass: null } and sets no site.theme at all. Both scripts ship on every page.

The FOUC guard causes the FOUC

Because the guard reads localStorage['theme'] — a key nothing in the app ever writes — read() always takes the t === null branch and resolves to the 'dark' default. It then puts class="dark" on the root element at the very top of <head>, before anything else runs.

Measured on /login with a stored preference of light (bughq_theme=light), recording every attribute mutation on the root element from a script installed before any page script:

class="dark"          ← legacy guard, byte 63. Wrong.
data-theme="light"    ← color-mode boot. Correct.
data-theme="light"
data-theme="light"    ← applied 3× total
class=""              ← wrong class removed only after hydration

The root element carries the wrong theme class from first paint until hydration completes. bughq happens not to render differently for it (0 dark: utilities, no .dark selector), so there is no visible flash here — but .dark on the root element is the default dark-mode strategy for Crosswind/Tailwind-style utilities, and for any app using it this is a dark flash on every load for every light-preference user. Which is the exact thing the guard exists to prevent.

Worth noting data-theme is written three times where once would do.

It also pushes <meta charset> out of the spec budget

The #1803 commit deliberately hoisted <meta charset> because "moving the ~800-byte boot script above it would have pushed the encoding declaration out of the spec's first-1024-bytes budget". That hoist works against the color-mode boot script — but the theme guard is injected at head-open too, is ~1.75KB, and lands ahead of it.

Measured byte offsets in the served /login document:

data-stx-theme-guard      →   63
<meta charset>            → 1819   ← past the 1024-byte limit
data-stx-color-mode-boot  → 1852

<meta charset> at byte 1819 violates the HTML spec requirement that the character encoding declaration appear entirely within the first 1024 bytes. So #1803's hoist is currently defeated by an injector that runs earlier than the one it was written against.

Repro

Any app that configures app.colorMode and not site.theme:

  1. app.colorMode = { storageKey: 'myapp_theme', attribute: 'data-theme', darkClass: null }
  2. Load any page, localStorage.setItem('myapp_theme', 'light'), reload.
  3. Root element gets class="dark" pre-paint, then loses it after hydration.
  4. <meta charset> sits past byte 1024.

Suggested direction

Flagging rather than fixing, since the ownership question is a design call:

  • (a) Make the two systems one. app.colorMode is the configured, attribute-based, documented path; site.theme predates it. If app.colorMode is configured, skip injectThemeBootstrap entirely — that alone fixes the wrong class, the charset offset, and the dead 1.75KB.
  • (b) If both must coexist, have injectThemeBootstrap read app.colorMode for storageKey/darkClass/default so they cannot disagree, and inject after charset.
  • (c) At minimum, re-assert the charset hoist after injectThemeBootstrap the same way #1803 re-asserts the boot script position after all injectors — ordering injectors pairwise is what #1803's commit message already argues against.

(a) seems right to me: the emitted guard in bughq reads a key nothing writes, toggles a class no stylesheet uses, and registers a document click handler for #theme-toggle, which does not exist in the app. It is pure render-blocking weight on every page.

  • #1803 — the charset hoist this defeats; the color-mode boot ordering is otherwise correct now.
  • #1794 — the original pre-paint flash issue.
22 days ago

Two further findings from continuing to work on the same app.

1. The divergence is permanent, not just pre-paint — it was being masked.

My original report showed the wrong class being corrected after hydration:

class="dark"        <- guard, wrong
data-theme="light"  <- boot, correct
class=""            <- corrected on hydration

That correction was not the framework repairing itself. It came from an unrelated useDark() in a dead file the app auto-bundles. Deleting that dead file (it imported nothing and was imported by nothing) removed the correction, and the measurement became:

bughq_theme=light  ->  data-theme="light",  class="dark"
bughq_theme=dark   ->  data-theme="dark",   class="dark"
no preference      ->  data-theme="dark",   class="dark"

class="dark" in every case, permanently, including where the resolved mode is light. So the guard's wrong value survives indefinitely unless something else happens to be managing the same class. Any app that configures app.colorMode with darkClass: null — the documented way to say "my CSS selects on the attribute, don't manage a class" — gets a root element that permanently contradicts its own resolved theme.

2. There is no way to turn it off.

injectThemeBootstrap(html, options) is called unconditionally at packages/stx/src/site-builder/build.ts:123. It is not gated on site.theme being present, nor on app.colorMode being configured. An app that never opts into site.theme still gets the guard, on defaults it did not choose, and has no switch to decline it.

That leaves affected apps choosing between two wrong options: keep darkClass: null and accept a permanently wrong class, or drop it and let useColorMode manage a class no stylesheet reads purely so that it corrects the guard on hydration. I took the second in bughq and had to write a paragraph in the config explaining why the more obviously correct setting is the one not to use — which is a reasonable signal the default is wrong rather than the app.

This makes suggestion (a) from the original report stronger: if app.colorMode is configured, skip injectThemeBootstrap entirely. Failing that, even a plain site.theme: false opt-out would be enough to unblock.

22 days ago

Fixed in 83dc1d53e7.

The legacy guard now stands down entirely when the color-mode boot script is present — no class, no FOUC guard, no toggle handler.

Your framing that "the FOUC guard causes the FOUC" is the part that made the priority obvious, and it's worse than a cosmetic issue for anyone using utility CSS: dark on the root element is the default dark-mode strategy for Crosswind/Tailwind, so every light-preference user gets a dark flash on every load. bughq only escapes it by having zero dark: utilities.

I kept the browser-chrome <meta> tags. color-mode-boot doesn't manage theme-color, so those are additive rather than conflicting — and the guard's own comments explain that interaction carefully enough that dropping them would lose real behaviour.

Apps on site.theme alone are untouched, with a test pinning that, since that's the configuration the guard was actually written for.

This also relieves the byte pressure you measured: the ~1.75KB guard was landing at head-open, ahead of the charset hoist I added for #1803. 3 of 7 tests fail without the fix.

Sign in to comment on this issue.