@celestia-island/hikari 0.55.485 → 0.55.486

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -85,6 +85,27 @@ export interface CustomThemePreset {
85
85
  light: ThemeSchemeTokens;
86
86
  groups?: ThemeTokenGroupModes;
87
87
  }
88
+ /** The runtime's own memo of a CUSTOM theme's computed cssvars, keyed by
89
+ * theme id then mode, so the PRE-PAINT boot asset can replay the colors
90
+ * without re-implementing (or duplicating) the color math (hikari#1546
91
+ * point 2). Written by applyTheme for non-stock themes only — the stock
92
+ * preset already ships as the static sheet.
93
+ *
94
+ * VERSION DISCIPLINE: the memo bakes THREE inputs, and any of them
95
+ * changing makes a stored payload wrong —
96
+ * 1. `tokensToCSSVars` / its OKLCH-contrast helpers (this repo),
97
+ * 2. the token GROUPS a host registers (their resolved defaults feed the
98
+ * memo through `groupTokensToCSSVars`),
99
+ * 3. a host's own preset table (`window.__celestiaThemes` / in-place
100
+ * preset overrides), whose values are memoized like any custom theme.
101
+ * (1) is ours to police in review; (2) and (3) live in consumers, so the
102
+ * version is also the hatch for a HOST-driven refresh — a host that changes
103
+ * a group default or a preset's colors bumps nothing here, and its users
104
+ * keep one load of the previous palette. That is accepted (the memo is a
105
+ * first-paint hint, `applyTheme` overwrites it immediately) but it is why
106
+ * this is a hint and not a cache of record. */
107
+ export declare const THEME_VARS_MEMO_KEY = "hikari-theme-vars";
108
+ export declare const THEME_VARS_MEMO_VERSION = 1;
88
109
  export declare function loadCustomThemes(): CustomThemePreset[];
89
110
  export declare function saveCustomThemes(list: CustomThemePreset[]): void;
90
111
  export declare function addCustomTheme(theme: CustomThemePreset): void;
@@ -1,3 +1,46 @@
1
+ /**
2
+ * The PRE-PAINT theme resolver and its shipped boot asset (hikari#1546
3
+ * Phase 1.5, user direction 2026-11-25: 一整套统一 — one resolution
4
+ * executed on BOTH sides of hydration).
5
+ *
6
+ * `resolveSystemModeAt` runs the solar chain's SYNC path exactly as the
7
+ * reactive runtime resolves mode "system": manual config (when the stored
8
+ * strategy selects it and the payload validates) → the timezone estimate
9
+ * (stock default latitude + UTC-offset longitude) → solar altitude →
10
+ * day → light, else dark. Dependency-free by design (safeStorage only —
11
+ * no vue, no cronBus) so it can ride the pre-paint asset.
12
+ *
13
+ * Two documented divergences from the reactive runtime, both narrow:
14
+ * - strategy "ip": the runtime may improve the coords via a
15
+ * granted-browser-geolocation / IP cascade (async, networked). The boot
16
+ * asset cannot — it uses the timezone estimate. The runtime's answer
17
+ * lands with the bundle and self-heals.
18
+ * - stale stored values: the runtime's readers also REMOVE bad payloads;
19
+ * the boot asset is read-only (pre-paint storage writes would be a
20
+ * surprise) and falls back instead. Removal happens at initTheme.
21
+ *
22
+ * It also REPLAYS the runtime's memo for a user's custom theme (see the
23
+ * CUSTOM THEME FIRST PAINT block in the emitted wrapper): the boot never
24
+ * composes a palette itself, so there is no second implementation of the
25
+ * color math to drift. `applyTheme` retires the replayed block on its first
26
+ * run, so a memo can never outlive the paint it was written for.
27
+ *
28
+ * `buildThemeBootJs()` ships the chain as a dependency-free IIFE for
29
+ * consumers to inline in `<head>` (lagrange interpolates it with a `?raw`
30
+ * import). CONSUMERS MUST INLINE IT AFTER THEIR STYLESHEET LINKS AND BEFORE
31
+ * `</head>`: every var-bearing block (the static `html[data-mode]` sheet,
32
+ * this asset's `html:root` replay, the runtime's own `html:root` block) has
33
+ * the same specificity, so HEAD ORDER is the only thing deciding who wins,
34
+ * and the intended chain is sheet -> replay -> runtime. The math is
35
+ * serialized via `Function.prototype.toString` from
36
+ * useSolarTime's OWN definitions — the asset cannot drift from the
37
+ * runtime's solar chain by construction; `themeBoot.contract.test.ts`
38
+ * executes the emitted asset against `resolveSystemModeAt` across a date
39
+ * grid to pin the wrapper (storage reads + attribute writes) instead.
40
+ */
41
+ /** Marks the boot-injected vars block so the runtime (and tests) can tell
42
+ * it apart from useTheme's own `data-hikari-theme-vars` block. */
43
+ export declare const THEME_BOOT_STYLE_ATTR = "data-hikari-boot-vars";
1
44
  /** A read-only storage surface — the seam that lets the contract test feed
2
45
  * the resolver the SAME values the emitted asset reads (a test runner may
3
46
  * have no `localStorage` at all, and comparing against the environment's
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celestia-island/hikari",
3
- "version": "0.55.485",
3
+ "version": "0.55.486",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Hikari UI library, Vue 3 runtime — one design system for Vue 3 and Rust/WASM applications",
@@ -99,7 +99,54 @@ try {
99
99
  if (!(m === "light" || m === "dark")) {
100
100
  m = alt > 6 ? "light" : "dark";
101
101
  }
102
- d.setAttribute("data-theme", t || (typeof window !== "undefined" && window.__celestiaDefaultTheme) || "default");
102
+ var themeId = t || (typeof window !== "undefined" && window.__celestiaDefaultTheme) || "default";
103
+ d.setAttribute("data-theme", themeId);
103
104
  d.setAttribute("data-mode", m);
105
+
106
+ /* CUSTOM THEME FIRST PAINT (hikari#1546 point 2). The static sheet only
107
+ * carries the stock preset, so a user's own theme used to paint stock
108
+ * colors and snap. applyTheme() now memoizes its computed vars
109
+ * (hikari-theme-vars, versioned); this block REPLAYS that memo — no
110
+ * color math is duplicated here, the runtime stays the single source.
111
+ * The block is injected as the LAST <head> child that exists at this
112
+ * point and uses html:root, so it ties with the runtime's own block
113
+ * (which is appended later and therefore wins once the bundle lands)
114
+ * and outranks the static html[data-mode] sheet by document order. */
115
+ try {
116
+ /* A crafted/edited memo could otherwise smuggle a brace or semicolon into a key
117
+ * and escape the html:root block into arbitrary selectors. localStorage
118
+ * is same-origin (writing it already needs live JS), so this is
119
+ * hardening rather than a trust boundary — but the boot runs before ANY
120
+ * app code, which is the one place we cannot afford to trust it. */
121
+ var SAFE_KEY = /^--[A-Za-z0-9_-]+$/;
122
+ var SAFE_VALUE = /^[A-Za-z0-9 .,%()/#-]*$/;
123
+ {
124
+ var memo = JSON.parse(read("hikari-theme-vars") || "null");
125
+ var memoV = 1;
126
+ if (memo && memo.v === memoV) {
127
+ var entry = memo[themeId];
128
+ /* EXACT mode only: replaying the other mode's palette onto this
129
+ * one's background is worse than the stock colors the static sheet
130
+ * already paints, so a missing entry simply falls through. */
131
+ var vars = entry && entry[m];
132
+ if (vars && typeof vars === "object") {
133
+ var css = "";
134
+ for (var k in vars) {
135
+ if (!Object.prototype.hasOwnProperty.call(vars, k)) continue;
136
+ if (!SAFE_KEY.test(k)) continue;
137
+ var value = "" + vars[k];
138
+ if (!SAFE_VALUE.test(value)) continue;
139
+ css += k + ":" + value + ";";
140
+ }
141
+ if (css) {
142
+ var styleEl = document.createElement("style");
143
+ styleEl.setAttribute("data-hikari-boot-vars", "");
144
+ styleEl.textContent = "html:root{" + css + "}";
145
+ (document.head || d).appendChild(styleEl);
146
+ }
147
+ }
148
+ }
149
+ }
150
+ } catch (e) {}
104
151
  } catch (e) {}
105
152
  })();
@@ -98,6 +98,28 @@ export interface CustomThemePreset {
98
98
 
99
99
  const CUSTOM_STORAGE_KEY = "hikari-custom-themes";
100
100
 
101
+ /** The runtime's own memo of a CUSTOM theme's computed cssvars, keyed by
102
+ * theme id then mode, so the PRE-PAINT boot asset can replay the colors
103
+ * without re-implementing (or duplicating) the color math (hikari#1546
104
+ * point 2). Written by applyTheme for non-stock themes only — the stock
105
+ * preset already ships as the static sheet.
106
+ *
107
+ * VERSION DISCIPLINE: the memo bakes THREE inputs, and any of them
108
+ * changing makes a stored payload wrong —
109
+ * 1. `tokensToCSSVars` / its OKLCH-contrast helpers (this repo),
110
+ * 2. the token GROUPS a host registers (their resolved defaults feed the
111
+ * memo through `groupTokensToCSSVars`),
112
+ * 3. a host's own preset table (`window.__celestiaThemes` / in-place
113
+ * preset overrides), whose values are memoized like any custom theme.
114
+ * (1) is ours to police in review; (2) and (3) live in consumers, so the
115
+ * version is also the hatch for a HOST-driven refresh — a host that changes
116
+ * a group default or a preset's colors bumps nothing here, and its users
117
+ * keep one load of the previous palette. That is accepted (the memo is a
118
+ * first-paint hint, `applyTheme` overwrites it immediately) but it is why
119
+ * this is a hint and not a cache of record. */
120
+ export const THEME_VARS_MEMO_KEY = "hikari-theme-vars";
121
+ export const THEME_VARS_MEMO_VERSION = 1;
122
+
101
123
  export function loadCustomThemes(): CustomThemePreset[] {
102
124
  try {
103
125
  const raw = readStorageItem(CUSTOM_STORAGE_KEY);
@@ -4,6 +4,7 @@ import { fileURLToPath } from "node:url";
4
4
  import { describe, expect, it } from "vitest";
5
5
 
6
6
  import { buildThemeBootJs, resolveSystemModeAt } from "./themeBoot";
7
+ import { THEME_VARS_MEMO_VERSION } from "./presets";
7
8
 
8
9
  /**
9
10
  * Drift contract for the SHIPPED BOOT ASSET (hikari#1546 Phase 1.5): the
@@ -30,9 +31,40 @@ const jsPath = join(here, "..", "styles", "theme-boot.js");
30
31
  function runBoot(
31
32
  js: string,
32
33
  opts: { now: Date; storage?: Record<string, string> },
33
- ): { theme: string | null; mode: string | null } {
34
+ ): {
35
+ theme: string | null;
36
+ mode: string | null;
37
+ styles: Array<{ tag: string; attr: Record<string, string>; text: string }>;
38
+ } {
34
39
  const attrs: Record<string, string> = {};
40
+ const appended: Array<{ tag: string; attr: Record<string, string>; text: string }> = [];
41
+ const fakeHead = {
42
+ appendChild(el: { tag: string; attr: Record<string, string>; text: string }) {
43
+ appended.push(el);
44
+ },
45
+ };
35
46
  const fakeDoc = {
47
+ head: fakeHead,
48
+ createElement(tag: string) {
49
+ const el = {
50
+ tag,
51
+ attr: {} as Record<string, string>,
52
+ text: "",
53
+ setAttribute(k: string, v: string) {
54
+ el.attr[k] = v;
55
+ },
56
+ // The emitted code assigns `textContent` (real DOM semantics); the
57
+ // fake mirrors it onto `text` so assertions read what a browser
58
+ // would apply.
59
+ get textContent() {
60
+ return el.text;
61
+ },
62
+ set textContent(v: string) {
63
+ el.text = v;
64
+ },
65
+ };
66
+ return el;
67
+ },
36
68
  documentElement: {
37
69
  setAttribute(k: string, v: string) {
38
70
  attrs[k] = v;
@@ -48,12 +80,19 @@ function runBoot(
48
80
  // `Date` is SHADOWED in the asset's scope with a subclass pinned to the
49
81
  // grid instant — the wrapper's bare `new Date()` must observe the grid
50
82
  // date, not the wall clock, or the compare is meaningless.
83
+ const pinned = opts.now.getTime();
51
84
  const PinnedDate = class extends Date {
52
- constructor(...args: unknown[]) {
53
- super(...(args.length ? (args as ConstructorParameters<typeof Date>) : [opts.now.getTime()]));
85
+ // Zero-arg construction is the only call the asset makes; anything else
86
+ // forwards the same arguments (a typed overload avoids the spread-args
87
+ // error a variadic `unknown[]` would raise under vue-tsc).
88
+ constructor();
89
+ constructor(value: number);
90
+ constructor(year: number, month: number, day?: number);
91
+ constructor(a?: number, b?: number, c?: number) {
92
+ super(a === undefined ? pinned : b === undefined ? a : new Date(a, b, c ?? 1).getTime());
54
93
  }
55
94
  static now() {
56
- return opts.now.getTime();
95
+ return pinned;
57
96
  }
58
97
  };
59
98
  // eslint-disable-next-line no-new-func -- executing the emitted asset is the point
@@ -63,7 +102,11 @@ function runBoot(
63
102
  fakeDoc,
64
103
  fakeStorage,
65
104
  );
66
- return { theme: attrs["data-theme"] ?? null, mode: attrs["data-mode"] ?? null };
105
+ return {
106
+ theme: attrs["data-theme"] ?? null,
107
+ mode: attrs["data-mode"] ?? null,
108
+ styles: appended,
109
+ };
67
110
  }
68
111
 
69
112
  describe("shipped theme boot asset (hikari#1546 Phase 1.5)", () => {
@@ -106,6 +149,73 @@ describe("shipped theme boot asset (hikari#1546 Phase 1.5)", () => {
106
149
  expect(explicitDark.mode).toBe("dark");
107
150
  });
108
151
 
152
+ it("replays the runtime's memoized custom-theme vars, and only for a live version", () => {
153
+ // hikari#1546 point 2: the static sheet carries the STOCK preset, so a
154
+ // user's own theme used to paint stock colors and snap. applyTheme()
155
+ // memoizes what it computed; the asset REPLAYS it — no color math is
156
+ // duplicated in the boot path.
157
+ const at = new Date(Date.UTC(2026, 6, 1, 12, 0, 0));
158
+ const memo = (version: number) =>
159
+ JSON.stringify({
160
+ v: version,
161
+ "my-theme": {
162
+ light: { "--color-primary": "1 2 3", "--color-text": "4 5 6" },
163
+ },
164
+ });
165
+ const storage = (version: number) => ({
166
+ "hikari-theme": "my-theme",
167
+ "hikari-theme-mode": "light",
168
+ "hikari-theme-vars": memo(version),
169
+ });
170
+
171
+ const live = runBoot(js, { now: at, storage: storage(THEME_VARS_MEMO_VERSION) });
172
+ expect(live.theme, "the stored custom id is honored").toBe("my-theme");
173
+ expect(live.styles, "one vars block is injected").toHaveLength(1);
174
+ expect(live.styles[0]!.attr["data-hikari-boot-vars"]).toBe("");
175
+ expect(live.styles[0]!.text, "the memo's vars land in the block").toContain(
176
+ "--color-primary:1 2 3;",
177
+ );
178
+ expect(live.styles[0]!.text, "and its second slot too").toContain("--color-text:4 5 6;");
179
+
180
+ // A memo from an older math version must be IGNORED: replaying stale
181
+ // vars would paint a palette the runtime no longer agrees with.
182
+ const stale = runBoot(js, { now: at, storage: storage(THEME_VARS_MEMO_VERSION - 1) });
183
+ expect(stale.styles, "a stale memo is not replayed").toHaveLength(0);
184
+
185
+ // A hostile/garbled memo must not escape the html:root block: keys and
186
+ // values that are not plain cssvar shapes are dropped, the rest survive.
187
+ const hostile = runBoot(js, {
188
+ now: at,
189
+ storage: {
190
+ "hikari-theme": "my-theme",
191
+ "hikari-theme-mode": "light",
192
+ "hikari-theme-vars": JSON.stringify({
193
+ v: THEME_VARS_MEMO_VERSION,
194
+ "my-theme": {
195
+ light: {
196
+ "--color-primary": "1 2 3",
197
+ "} body { display: none } .x{": "red",
198
+ "--color-text": "4 5 6 } .y{z:1",
199
+ },
200
+ },
201
+ }),
202
+ },
203
+ });
204
+ expect(hostile.styles, "the block still injects the safe key").toHaveLength(1);
205
+ expect(hostile.styles[0]!.text, "safe pairs survive").toContain("--color-primary:1 2 3;");
206
+ expect(hostile.styles[0]!.text, "a selector-shaped key is refused").not.toContain("display");
207
+ expect(hostile.styles[0]!.text, "a value carrying a brace is refused").not.toContain(".y{");
208
+
209
+ // A stock theme never has a memo and must not inject anything.
210
+ // MUT:mut-memo-replay — disabling the replay branch REDS the live case
211
+ // above (verified); this one pins the stock exemption.
212
+ const stock = runBoot(js, {
213
+ now: at,
214
+ storage: { "hikari-theme": "default", "hikari-theme-mode": "light", "hikari-theme-vars": memo(THEME_VARS_MEMO_VERSION) },
215
+ });
216
+ expect(stock.styles, "the stock preset rides the static sheet, not a memo").toHaveLength(0);
217
+ });
218
+
109
219
  it("routes a stored manual config through the zone meridian, machine-independently", () => {
110
220
  // Round-2 review (S1): the first version compared the wrapper (fake
111
221
  // storage, manual config) against the MODULE (real localStorage, empty
@@ -1,3 +1,7 @@
1
+ import {
2
+ THEME_VARS_MEMO_KEY,
3
+ THEME_VARS_MEMO_VERSION,
4
+ } from "./presets";
1
5
  import { readStorageItem } from "./safeStorage";
2
6
  import {
3
7
  DEFAULT_GEO_LOCATION,
@@ -35,15 +39,30 @@ import {
35
39
  * the boot asset is read-only (pre-paint storage writes would be a
36
40
  * surprise) and falls back instead. Removal happens at initTheme.
37
41
  *
42
+ * It also REPLAYS the runtime's memo for a user's custom theme (see the
43
+ * CUSTOM THEME FIRST PAINT block in the emitted wrapper): the boot never
44
+ * composes a palette itself, so there is no second implementation of the
45
+ * color math to drift. `applyTheme` retires the replayed block on its first
46
+ * run, so a memo can never outlive the paint it was written for.
47
+ *
38
48
  * `buildThemeBootJs()` ships the chain as a dependency-free IIFE for
39
49
  * consumers to inline in `<head>` (lagrange interpolates it with a `?raw`
40
- * import). The math is serialized via `Function.prototype.toString` from
50
+ * import). CONSUMERS MUST INLINE IT AFTER THEIR STYLESHEET LINKS AND BEFORE
51
+ * `</head>`: every var-bearing block (the static `html[data-mode]` sheet,
52
+ * this asset's `html:root` replay, the runtime's own `html:root` block) has
53
+ * the same specificity, so HEAD ORDER is the only thing deciding who wins,
54
+ * and the intended chain is sheet -> replay -> runtime. The math is
55
+ * serialized via `Function.prototype.toString` from
41
56
  * useSolarTime's OWN definitions — the asset cannot drift from the
42
57
  * runtime's solar chain by construction; `themeBoot.contract.test.ts`
43
58
  * executes the emitted asset against `resolveSystemModeAt` across a date
44
59
  * grid to pin the wrapper (storage reads + attribute writes) instead.
45
60
  */
46
61
 
62
+ /** Marks the boot-injected vars block so the runtime (and tests) can tell
63
+ * it apart from useTheme's own `data-hikari-theme-vars` block. */
64
+ export const THEME_BOOT_STYLE_ATTR = "data-hikari-boot-vars";
65
+
47
66
  const DEG = Math.PI / 180;
48
67
  const RAD = 180 / Math.PI;
49
68
 
@@ -162,8 +181,55 @@ export function buildThemeBootJs(): string {
162
181
  if (!(m === "light" || m === "dark")) {
163
182
  m = alt > 6 ? "light" : "dark";
164
183
  }
165
- d.setAttribute("data-theme", t || (typeof window !== "undefined" && window.__celestiaDefaultTheme) || "default");
184
+ var themeId = t || (typeof window !== "undefined" && window.__celestiaDefaultTheme) || "default";
185
+ d.setAttribute("data-theme", themeId);
166
186
  d.setAttribute("data-mode", m);
187
+
188
+ /* CUSTOM THEME FIRST PAINT (hikari#1546 point 2). The static sheet only
189
+ * carries the stock preset, so a user's own theme used to paint stock
190
+ * colors and snap. applyTheme() now memoizes its computed vars
191
+ * (hikari-theme-vars, versioned); this block REPLAYS that memo — no
192
+ * color math is duplicated here, the runtime stays the single source.
193
+ * The block is injected as the LAST <head> child that exists at this
194
+ * point and uses html:root, so it ties with the runtime's own block
195
+ * (which is appended later and therefore wins once the bundle lands)
196
+ * and outranks the static html[data-mode] sheet by document order. */
197
+ try {
198
+ /* A crafted/edited memo could otherwise smuggle a brace or semicolon into a key
199
+ * and escape the html:root block into arbitrary selectors. localStorage
200
+ * is same-origin (writing it already needs live JS), so this is
201
+ * hardening rather than a trust boundary — but the boot runs before ANY
202
+ * app code, which is the one place we cannot afford to trust it. */
203
+ var SAFE_KEY = /^--[A-Za-z0-9_-]+$/;
204
+ var SAFE_VALUE = /^[A-Za-z0-9 .,%()\/#-]*$/;
205
+ {
206
+ var memo = JSON.parse(read("${THEME_VARS_MEMO_KEY}") || "null");
207
+ var memoV = ${THEME_VARS_MEMO_VERSION};
208
+ if (memo && memo.v === memoV) {
209
+ var entry = memo[themeId];
210
+ /* EXACT mode only: replaying the other mode's palette onto this
211
+ * one's background is worse than the stock colors the static sheet
212
+ * already paints, so a missing entry simply falls through. */
213
+ var vars = entry && entry[m];
214
+ if (vars && typeof vars === "object") {
215
+ var css = "";
216
+ for (var k in vars) {
217
+ if (!Object.prototype.hasOwnProperty.call(vars, k)) continue;
218
+ if (!SAFE_KEY.test(k)) continue;
219
+ var value = "" + vars[k];
220
+ if (!SAFE_VALUE.test(value)) continue;
221
+ css += k + ":" + value + ";";
222
+ }
223
+ if (css) {
224
+ var styleEl = document.createElement("style");
225
+ styleEl.setAttribute("${THEME_BOOT_STYLE_ATTR}", "");
226
+ styleEl.textContent = "html:root{" + css + "}";
227
+ (document.head || d).appendChild(styleEl);
228
+ }
229
+ }
230
+ }
231
+ }
232
+ } catch (e) {}
167
233
  } catch (e) {}`;
168
234
  return `/* GENERATED by packages/vue/src/theme/themeBoot.ts (buildThemeBootJs) —
169
235
  * do not edit by hand. The math functions are serialized from useSolarTime's
@@ -5,6 +5,53 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
5
  type ThemeModule = typeof import("./useTheme");
6
6
  type SolarModule = typeof import("./useSolarTime");
7
7
 
8
+ describe("custom-theme first-paint memo (hikari#1546 point 2)", () => {
9
+ it("memoizes a custom theme's vars for the boot asset and skips the stock preset", async () => {
10
+ const { THEME_VARS_MEMO_KEY, THEME_VARS_MEMO_VERSION, stockDefaultPreset } =
11
+ await import("./presets");
12
+ const theme = await import("./useTheme");
13
+ const api = theme.useTheme();
14
+ const { nextTick } = await import("vue");
15
+ // The API's own adder updates the live `customThemes` ref (calling the
16
+ // presets-layer helper would only write storage, which the ref read at
17
+ // import time).
18
+ api.addCustomTheme({
19
+ id: "brand-x",
20
+ name: "Brand X",
21
+ light: { ...stockDefaultPreset.light, primary: { r: 1, g: 2, b: 3 } },
22
+ dark: { ...stockDefaultPreset.dark, primary: { r: 4, g: 5, b: 6 } },
23
+ } as never);
24
+ theme.initTheme();
25
+ api.setTheme("brand-x");
26
+ await nextTick();
27
+ // `setTheme` persists the id; applyTheme ran synchronously on the watch
28
+ // flush, so the memo must already be there.
29
+ await Promise.resolve();
30
+ const raw = localStorage.getItem(THEME_VARS_MEMO_KEY);
31
+ expect(raw, "a custom theme writes a memo").toBeTruthy();
32
+ const memo = JSON.parse(raw!) as Record<string, unknown>;
33
+ expect(memo.v).toBe(THEME_VARS_MEMO_VERSION);
34
+ const entry = memo["brand-x"] as Record<string, Record<string, string>>;
35
+ expect(entry, "keyed by theme id then mode").toBeTruthy();
36
+ // Both modes are memoized, and the value is the REAL composition of
37
+ // that mode's tokens (the boot asset replays it verbatim).
38
+ expect(Object.keys(entry).sort()).toEqual(["dark", "light"]);
39
+ expect(entry.light!["--color-primary"]).toContain("1 2 3");
40
+ expect(entry.dark!["--color-primary"]).toContain("4 5 6");
41
+
42
+ // The stock preset never memoizes: it already ships as the static sheet
43
+ // MUT:mut-memo-stock-skip — dropping the stock guard adds a "default"
44
+ // entry and REDS the assertion below (verified).
45
+ api.setTheme("default");
46
+ await nextTick();
47
+ const after = JSON.parse(localStorage.getItem(THEME_VARS_MEMO_KEY)!) as Record<string, unknown>;
48
+ expect(after["default"], "no memo for a stock theme").toBeUndefined();
49
+ // Both modes are composed here (8 × the 400-step OKLCH search), which is
50
+ // slow under the suite's parallel load even though a browser does it in
51
+ // tens of milliseconds — this is a timeout, not a hang.
52
+ }, 30_000);
53
+ });
54
+
8
55
  describe("useTheme theme clock", () => {
9
56
  let theme: ThemeModule;
10
57
  let solar: SolarModule;
@@ -2,12 +2,13 @@ import { computed, ref, watch } from "vue";
2
2
 
3
3
  import { scheduleCronAfter, type CronHandle } from "../runtime/cronBus";
4
4
  import { scheduleInterval, type IntervalHandle } from "../runtime/intervalBus";
5
- import { addCustomTheme as addCustomThemeToStorage, loadCustomThemes, removeCustomTheme as removeCustomThemeFromStorage, themePresets, tokensToCSSVars, type CustomThemePreset, type ThemeId, type ThemeMode, type ThemePreset } from "./presets";
5
+ import { addCustomTheme as addCustomThemeToStorage, loadCustomThemes, removeCustomTheme as removeCustomThemeFromStorage, themePresets, tokensToCSSVars, THEME_VARS_MEMO_KEY, THEME_VARS_MEMO_VERSION, type CustomThemePreset, type ThemeId, type ThemeMode, type ThemePreset } from "./presets";
6
6
  import { readStorageItem, removeStorageItem, writeStorageItem } from "./safeStorage";
7
7
  import { groupTokensToCSSVars, resolveGroupTokens, setTokenGroupsReapply } from "./tokenGroups";
8
8
  import { registerStandardThemeDecor } from "./standardDecor";
9
9
  import { registerStandardThemeGroups } from "./standardGroups";
10
10
  import { invalidateLuminanceCache } from "./useBackgroundLuminance";
11
+ import { THEME_BOOT_STYLE_ATTR } from "./themeBoot";
11
12
  import { getGeolocation, getTimePeriod, hydrateSolarLocationState, timezoneFallback, type GeoLocation, type TimePeriod } from "./useSolarTime";
12
13
 
13
14
  const DEFAULT_THEME = "default";
@@ -210,6 +211,42 @@ export function pickThemeVarDeltas(
210
211
  return deltas;
211
212
  }
212
213
 
214
+ /** Memoize a CUSTOM theme's computed vars so the pre-paint boot asset can
215
+ * replay them on the next load (hikari#1546 point 2). The STOCK preset is
216
+ * skipped: it already ships as the static sheet, and rewriting it would
217
+ * duplicate ~50 vars into localStorage for no gain.
218
+ *
219
+ * Failure is silent on purpose — a full/unavailable localStorage must
220
+ * never break theming; it only costs the next load its exact first paint. */
221
+ function rememberVarsForFirstPaint(preset: ThemePreset): void {
222
+ if (preset.id in themePresets) return;
223
+ try {
224
+ const raw = readStorageItem(THEME_VARS_MEMO_KEY);
225
+ const memo: Record<string, unknown> =
226
+ raw ? (JSON.parse(raw) as Record<string, unknown>) : {};
227
+ if (memo.v !== THEME_VARS_MEMO_VERSION) {
228
+ for (const key of Object.keys(memo)) delete memo[key];
229
+ memo.v = THEME_VARS_MEMO_VERSION;
230
+ }
231
+ // BOTH modes, every time: the boot asset resolves the mode from the
232
+ // clock, which can differ from the mode the user is looking at right
233
+ // now. Memoizing only the active one would leave the other mode
234
+ // unpainted (or, worse, tempt the boot into cross-mode fallback).
235
+ const perTheme: Record<string, Record<string, string>> = {};
236
+ for (const mode of ["dark", "light"] as const) {
237
+ const tokens = mode === "dark" ? preset.dark : preset.light;
238
+ perTheme[mode] = tokensToCSSVars(
239
+ tokens,
240
+ groupTokensToCSSVars(resolveGroupTokens(mode, preset.groups?.[mode])),
241
+ );
242
+ }
243
+ memo[preset.id] = perTheme;
244
+ writeStorageItem(THEME_VARS_MEMO_KEY, JSON.stringify(memo));
245
+ } catch {
246
+ // Storage unavailable or the payload is not ours — drop the memo.
247
+ }
248
+ }
249
+
213
250
  function themeVarsStyleElement(): HTMLStyleElement {
214
251
  let styleEl = document.head.querySelector<HTMLStyleElement>(
215
252
  `style[${THEME_VARS_STYLE_ATTR}]`,
@@ -222,7 +259,19 @@ function themeVarsStyleElement(): HTMLStyleElement {
222
259
  return styleEl;
223
260
  }
224
261
 
262
+ /** Retire the pre-paint block once the runtime owns the vars (hikari#1546
263
+ * point 2, review round 1): it exists ONLY to cover the first paint, and
264
+ * leaving it live poisons `injectThemeVars`' baseline measurement — a memo
265
+ * key that the new vars map no longer carries would never be overridden,
266
+ * so a stale first-paint value would survive every later theme switch. */
267
+ function retireBootVars(): void {
268
+ document.head
269
+ .querySelector(`style[${THEME_BOOT_STYLE_ATTR}]`)
270
+ ?.remove();
271
+ }
272
+
225
273
  function injectThemeVars(el: HTMLElement, vars: Record<string, string>): void {
274
+ retireBootVars();
226
275
  const styleEl = themeVarsStyleElement();
227
276
  // Measure the cascade WITHOUT our own previous overrides: disable the
228
277
  // managed block, read every candidate, re-enable. One recalc serves
@@ -262,6 +311,8 @@ function applyTheme() {
262
311
  );
263
312
  const vars = tokensToCSSVars(tokens, groupVars);
264
313
 
314
+ rememberVarsForFirstPaint(preset);
315
+
265
316
  invalidateLuminanceCache();
266
317
 
267
318
  injectThemeVars(el, vars);
@@ -284,6 +335,20 @@ function applyTheme() {
284
335
  // applications never call setTokenGroupsReapply themselves.
285
336
  setTokenGroupsReapply(() => applyTheme());
286
337
 
338
+ /** Drop a removed theme's memo so deleted ids cannot replay forever. */
339
+ function forgetVarsForFirstPaint(themeId: ThemeId): void {
340
+ try {
341
+ const raw = readStorageItem(THEME_VARS_MEMO_KEY);
342
+ if (!raw) return;
343
+ const memo = JSON.parse(raw) as Record<string, unknown>;
344
+ if (!(themeId in memo)) return;
345
+ delete memo[themeId];
346
+ writeStorageItem(THEME_VARS_MEMO_KEY, JSON.stringify(memo));
347
+ } catch {
348
+ // Unavailable or foreign payload — nothing to prune.
349
+ }
350
+ }
351
+
287
352
  function getAllThemePresets(): Record<string, ThemePreset> {
288
353
  const result: Record<string, ThemePreset> = { ...themePresets };
289
354
  for (const ct of customThemes.value) {
@@ -371,6 +436,7 @@ export function useTheme() {
371
436
 
372
437
  function removeCustomTheme(id: string) {
373
438
  removeCustomThemeFromStorage(id);
439
+ forgetVarsForFirstPaint(id);
374
440
  customThemes.value = loadCustomThemes();
375
441
  if (currentTheme.value === id) {
376
442
  // A deleted custom whose id still resolves as a builtin preset falls