@celestia-island/hikari 0.55.484 → 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;
@@ -0,0 +1,58 @@
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";
44
+ /** A read-only storage surface — the seam that lets the contract test feed
45
+ * the resolver the SAME values the emitted asset reads (a test runner may
46
+ * have no `localStorage` at all, and comparing against the environment's
47
+ * storage made the parity assertion machine-dependent: review round 2). */
48
+ export interface BootStorage {
49
+ getItem(key: string): string | null;
50
+ }
51
+ /** The runtime contract, sync path: mode "system" is light only while the
52
+ * sun is genuinely up (altitude > 6°); dusk and night are dark. */
53
+ export declare function resolveSystemModeAt(date?: Date, storage?: BootStorage): "dark" | "light";
54
+ /** Serialize the boot IIFE. The math is emitted from useSolarTime's own
55
+ * function sources (toString) plus the two constants they close over —
56
+ * emitted BEFORE the functions, so the copy executes exactly what the
57
+ * runtime executes. */
58
+ export declare function buildThemeBootJs(): string;
@@ -1,4 +1,11 @@
1
1
  export type TimePeriod = "day" | "dusk" | "night";
2
+ export declare function toJulianDate(date: Date): number;
3
+ export declare function greenwichSiderealTime(jd: number): number;
4
+ export interface SunEquatorial {
5
+ decl: number;
6
+ ra: number;
7
+ }
8
+ export declare function sunEquatorialCoordinates(jd: number): SunEquatorial;
2
9
  export declare function solarAltitude(latDeg: number, lngDeg: number, date: Date): number;
3
10
  export declare function getTimePeriod(latDeg: number, lngDeg: number, date?: Date): TimePeriod;
4
11
  export declare const DEFAULT_GEO_LOCATION: {
@@ -33,6 +40,10 @@ export interface SolarManualLocation {
33
40
  }
34
41
  export declare const SOLAR_LOCATION_STRATEGY_STORAGE_KEY = "hikari-solar-strategy";
35
42
  export declare const SOLAR_MANUAL_LOCATION_STORAGE_KEY = "hikari-solar-manual";
43
+ /** Intl constructs a formatter only for ids it knows — the constructor
44
+ * throws RangeError otherwise, which is the whole validation story for
45
+ * manually chosen zones. */
46
+ export declare function isKnownTimeZone(timeZone: string): boolean;
36
47
  /** Module state starts at the offline defaults and hydrates from storage
37
48
  * LAZILY (hydrateSolarLocationState): importing this module must touch no
38
49
  * storage key at all — the wallpaper layer's SSR import contract
@@ -53,6 +64,9 @@ export declare const solarManualLocation: import("vue").Ref<{
53
64
  export declare function hydrateSolarLocationState(): void;
54
65
  export declare function setSolarLocationStrategy(s: SolarLocationStrategy): void;
55
66
  export declare function setSolarManualLocation(cfg: SolarManualLocation | null): void;
67
+ /** The zone's UTC offset in minutes at the given instant, parsed from the
68
+ * `longOffset` name ("GMT+08:00", "GMT-03:30"; plain "GMT" for UTC). */
69
+ export declare function zoneOffsetMinutes(timeZone: string, date: Date): number;
56
70
  /** Coordinates for a manual config: the hemisphere flips the default
57
71
  * latitude's sign, and the longitude is the zone's STANDARD (non-DST) UTC
58
72
  * offset divided by 4 — 15° per hour, the zone's center meridian. DST is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celestia-island/hikari",
3
- "version": "0.55.484",
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",
@@ -109,8 +109,9 @@
109
109
  // danger confirm's own red dissolves into its red card. The confirm
110
110
  // inverts to a filled white control labeled in a deepened shade of the
111
111
  // variant color — the strongest move on every variant surface — and the
112
- // cancel quiets to a translucent outline in the card's own ink (the
113
- // house grammar for quiet controls on tinted toast surfaces).
112
+ // cancel is the house ghost icon button (the ✕, 2026-11-25 product
113
+ // call: every right-side cancel on a toast surface) re-pinned to the
114
+ // band's on-tone ink below (the HkToast copy/close grammar).
114
115
  .hk-blocking-toast-info {
115
116
  --hk-blocking-toast-ink: var(--hi-color-info, #006274);
116
117
  }
@@ -152,26 +153,43 @@
152
153
  background: rgb(255 255 255 / 78%);
153
154
  }
154
155
 
155
- /* The secondary cancel stops being a heavy surface block (it rendered
156
- as a white pill competing with the confirm on the tinted card) and
157
- picks up the quiet outline in the card's currentColor — white on
158
- info/danger, near-black on warning — so it reads on every variant
159
- without its own per-variant table. */
160
- .hk-blocking-toast-actions .hk-btn-secondary {
161
- background: transparent;
162
- border-color: color-mix(in srgb, currentColor 45%, transparent);
163
- @include backdrop-filter(none);
164
- color: inherit;
165
- }
166
-
167
- .hk-blocking-toast-actions .hk-btn-secondary:hover:not(:disabled) {
168
- border-color: color-mix(in srgb, currentColor 70%, transparent);
169
- background: color-mix(in srgb, currentColor 18%, transparent);
170
- }
171
-
172
- .hk-blocking-toast-actions .hk-btn-secondary:active:not(:disabled) {
173
- filter: none;
174
- background: color-mix(in srgb, currentColor 28%, transparent);
156
+ /* The cancel is the STANDARD ghost icon button, whose ink defaults to
157
+ the page's secondary text color — wrong on any tinted band — and
158
+ ghost declares that ink ON the button element, so no inherited value
159
+ can beat it: each band re-pins the --hi-icon-button-* bridge at that
160
+ same seat, riding the band's own on-tone ink (info/danger white via
161
+ the on-info/on-danger slots, warning dark via on-warning — the
162
+ HkToast copy/close grammar). Hover/press washes ride currentColor so
163
+ their polarity follows the band's ink too; the global ghost's grey
164
+ wash would otherwise read as a dead spot on the saturated fills. */
165
+ .hk-blocking-toast-info .hk-blocking-toast-cancel {
166
+ --hi-icon-button-icon-color: var(--hi-color-text-on-info, #ffffff);
167
+ --hi-icon-button-icon-color-active: var(--hi-color-text-on-info, #ffffff);
168
+ --hi-icon-button-bg-hover: color-mix(in srgb, currentColor 14%, transparent);
169
+ --hi-icon-button-bg-active: color-mix(in srgb, currentColor 20%, transparent);
170
+ }
171
+
172
+ .hk-blocking-toast-warning .hk-blocking-toast-cancel {
173
+ --hi-icon-button-icon-color: var(--hi-color-text-on-warning, #1c1c1e);
174
+ --hi-icon-button-icon-color-active: var(--hi-color-text-on-warning, #1c1c1e);
175
+ --hi-icon-button-bg-hover: color-mix(in srgb, currentColor 14%, transparent);
176
+ --hi-icon-button-bg-active: color-mix(in srgb, currentColor 20%, transparent);
177
+ }
178
+
179
+ .hk-blocking-toast-danger .hk-blocking-toast-cancel {
180
+ --hi-icon-button-icon-color: var(--hi-color-text-on-danger, #ffffff);
181
+ --hi-icon-button-icon-color-active: var(--hi-color-text-on-danger, #ffffff);
182
+ --hi-icon-button-bg-hover: color-mix(in srgb, currentColor 14%, transparent);
183
+ --hi-icon-button-bg-active: color-mix(in srgb, currentColor 20%, transparent);
184
+ }
185
+
186
+ /* The cancel is the STANDARD icon button (HkToast's close rule); what
187
+ remains here is only a flex layout nudge — `flex-shrink: 0`, the
188
+ same value the standard layer already declares, so this flat key
189
+ carries no box/ink of its own and cannot fight the component
190
+ regardless of bundle order. */
191
+ .hk-blocking-toast-cancel {
192
+ flex-shrink: 0;
175
193
  }
176
194
 
177
195
  /* The keyboard ring follows the card ink too — the global primary ring
@@ -49,13 +49,16 @@ function actionButtons(card: HTMLElement): HTMLButtonElement[] {
49
49
  }
50
50
 
51
51
  /** Answer the gate by semantics, not by position: the row order is pinned
52
- * separately, so these helpers keep the behaviour cases readable. */
52
+ * separately, so these helpers keep the behaviour cases readable. The
53
+ * cancel stopped being a text button (no hk-btn-secondary to grep for) —
54
+ * it is the standard icon button carrying the hk-blocking-toast-cancel
55
+ * seat class, which is the stable handle. */
53
56
  function confirmButton(card: HTMLElement): HTMLButtonElement {
54
57
  return actionButtons(card).find((b) => !b.classList.contains("hk-btn-secondary"))!;
55
58
  }
56
59
 
57
60
  function cancelButton(card: HTMLElement): HTMLButtonElement {
58
- return actionButtons(card).find((b) => b.classList.contains("hk-btn-secondary"))!;
61
+ return card.querySelector<HTMLButtonElement>("button.hk-blocking-toast-cancel")!;
59
62
  }
60
63
 
61
64
  function toastRegistryTitles(): Array<{ kind: string; title?: string }> {
@@ -82,8 +85,12 @@ describe("HkBlockingToast", () => {
82
85
  const card = cards()[0];
83
86
  expect(card.querySelector(".hk-blocking-toast-title")!.textContent).toContain("Join group?");
84
87
  expect(card.querySelector(".hk-blocking-toast-message")!.textContent).toContain("Admins can view your usage.");
85
- const labels = actionButtons(card).map((b) => b.textContent?.trim());
86
- expect(labels).toEqual(["Confirm", "Cancel"]);
88
+ // Only the confirm still contributes textContent — the cancel is the
89
+ // icon button now, so its label is the accessible name (aria-label +
90
+ // title), never visible text.
91
+ expect(confirmButton(card).textContent?.trim()).toBe("Confirm");
92
+ expect(cancelButton(card).getAttribute("aria-label")).toBe("Cancel");
93
+ expect(cancelButton(card).getAttribute("title")).toBe("Cancel");
87
94
 
88
95
  confirmButton(card).click();
89
96
  await expect(gate).resolves.toBe(true);
@@ -91,6 +98,31 @@ describe("HkBlockingToast", () => {
91
98
  expect(cards().length).toBe(0);
92
99
  });
93
100
 
101
+ it("renders the cancel as the standard icon button (no visible label text)", async () => {
102
+ mountHost();
103
+ showBlockingToast("Icon cancel");
104
+ await settle();
105
+
106
+ const cancel = cancelButton(cards()[0]);
107
+ // The rendered icon-button chrome is the contract the sheet pins ink
108
+ // on (the per-band --hi-icon-button-* rules) and the Rust mirror
109
+ // emits; the seat class is what the card's own stylesheet targets.
110
+ expect(cancel.classList.contains("hk-icon-button")).toBe(true);
111
+ expect(cancel.classList.contains("hk-icon-button-24")).toBe(true);
112
+ expect(cancel.classList.contains("hk-icon-button-ghost")).toBe(true);
113
+ expect(cancel.classList.contains("hk-blocking-toast-cancel")).toBe(true);
114
+ expect(cancel.getAttribute("type")).toBe("button");
115
+ // Glyph, not a label: the ✕ renders as svg, the resolved cancel label
116
+ // rides aria-label/title only (pinned in the label cases above).
117
+ expect(cancel.querySelector("svg")).not.toBeNull();
118
+ expect(cancel.textContent?.trim()).toBe("");
119
+
120
+ // DOM order: confirm first, the cancel ✕ second (right end).
121
+ const buttons = actionButtons(cards()[0]);
122
+ expect(buttons[0]).toBe(confirmButton(cards()[0]));
123
+ expect(buttons[buttons.length - 1]).toBe(cancel);
124
+ });
125
+
94
126
  it("resolves false on cancel and removes the card", async () => {
95
127
  mountHost();
96
128
  const gate = showBlockingToast("Cancel me");
@@ -183,8 +215,10 @@ describe("HkBlockingToast", () => {
183
215
 
184
216
  const card = cards()[0];
185
217
  expect(card.classList.contains("hk-blocking-toast-danger")).toBe(true);
186
- const labels = actionButtons(card).map((b) => b.textContent?.trim());
187
- expect(labels).toEqual(["Join", "Back out"]);
218
+ expect(confirmButton(card).textContent?.trim()).toBe("Join");
219
+ // A custom cancelLabel feeds the icon button's accessible name now.
220
+ expect(cancelButton(card).getAttribute("aria-label")).toBe("Back out");
221
+ expect(cancelButton(card).getAttribute("title")).toBe("Back out");
188
222
 
189
223
  confirmButton(card).click();
190
224
  await expect(gate).resolves.toBe(true);
@@ -196,8 +230,9 @@ describe("HkBlockingToast", () => {
196
230
  const gate = showBlockingToast("本地化");
197
231
  await settle();
198
232
 
199
- const labels = actionButtons(cards()[0]).map((b) => b.textContent?.trim());
200
- expect(labels).toEqual(["确认", "取消"]);
233
+ expect(confirmButton(cards()[0]).textContent?.trim()).toBe("确认");
234
+ expect(cancelButton(cards()[0]).getAttribute("aria-label")).toBe("取消");
235
+ expect(cancelButton(cards()[0]).getAttribute("title")).toBe("取消");
201
236
 
202
237
  confirmButton(cards()[0]).click();
203
238
  await expect(gate).resolves.toBe(true);
@@ -4,7 +4,8 @@
4
4
  *
5
5
  * Toast-shaped but flow-blocking consent prompts: a compact floating
6
6
  * card in the toast stack area (not a centered modal, no scroll lock)
7
- * with explicit Confirm/Cancel buttons — e.g. "joining this group lets
7
+ * with an explicit Confirm button and a Cancel ✕ affordance — e.g.
8
+ * "joining this group lets
8
9
  * its admins view your personal workspace usage — confirm?". Unlike a
9
10
  * normal toast it never auto-dismisses; the caller's promise settles
10
11
  * only when the user answers (or an optional timeoutMs expires).
@@ -22,7 +23,7 @@
22
23
  * stacking (newer cards paint above older ones), and the explicit card
23
24
  * z keeps cards clickable under the pointer-transparent toast column.
24
25
  */
25
- import { AlertTriangle, CircleX as XCircle, Info } from "lucide-vue-next";
26
+ import { AlertTriangle, CircleX as XCircle, Info, X } from "lucide-vue-next";
26
27
  import {
27
28
  defineComponent,
28
29
  onBeforeUnmount,
@@ -45,6 +46,7 @@ import {
45
46
  } from "../runtime/useBlockingToast";
46
47
  import "./HkBlockingToast.scss";
47
48
  import HButton from "./HkButton";
49
+ import HIconButton from "./HkIconButton";
48
50
  import { ensureOverlayRoot } from "../overlay/overlayRoot";
49
51
 
50
52
  const ICON_SIZE = 18;
@@ -69,6 +71,10 @@ const HkBlockingToastCard = defineComponent({
69
71
 
70
72
  return () => {
71
73
  const item = props.item;
74
+ // The same resolved string the old text button rendered — the label
75
+ // only changed seats (visible text → the icon button's accessible
76
+ // name), never its resolution.
77
+ const cancelText = item.cancelLabel ?? t("hikari::blockingToast.cancel", "Cancel");
72
78
  return (
73
79
  <div
74
80
  class={["hk-blocking-toast-card", `hk-blocking-toast-${item.variant}`]}
@@ -92,13 +98,27 @@ const HkBlockingToastCard = defineComponent({
92
98
  >
93
99
  {item.confirmLabel ?? t("hikari::blockingToast.confirm", "Confirm")}
94
100
  </HButton>
95
- <HButton
96
- variant="secondary"
97
- size="sm"
98
- onClick={() => emit("cancel")}
101
+ {/* The cancel is the house icon button, not a text button
102
+ (2026-11-25 product call: every right-side cancel on a
103
+ toast surface is the ✕ — the blocking card included, even
104
+ though it has no progress row for the button to sit
105
+ beside). The resolved label survives as the accessible
106
+ name — aria-label + title — instead of visible text;
107
+ ghost variant + icon slot exactly like HkToast's close,
108
+ whose per-band ink re-pinning this sheet mirrors. */}
109
+ <HIconButton
110
+ class="hk-blocking-toast-cancel"
111
+ size={24}
112
+ variant="ghost"
113
+ aria-label={cancelText}
114
+ {...{ title: cancelText }}
115
+ onClick={(e) => {
116
+ e.stopPropagation();
117
+ emit("cancel");
118
+ }}
99
119
  >
100
- {item.cancelLabel ?? t("hikari::blockingToast.cancel", "Cancel")}
101
- </HButton>
120
+ {{ icon: () => <X aria-hidden="true" /> }}
121
+ </HIconButton>
102
122
  </div>
103
123
  </div>
104
124
  </div>
@@ -0,0 +1,152 @@
1
+ /* GENERATED by packages/vue/src/theme/themeBoot.ts (buildThemeBootJs) —
2
+ * do not edit by hand. The math functions are serialized from useSolarTime's
3
+ * own definitions via toString(), so this asset cannot drift from the
4
+ * runtime's solar chain by construction; the wrapper (storage reads +
5
+ * attribute writes) is pinned by themeBoot.contract.test.ts. Inline in
6
+ * <head> BEFORE the theme-vars sheet's first paint.
7
+ *
8
+ * SYNTAX FLOOR: ES2020 (const/let, arrow functions, optional chaining).
9
+ * The asset is inlined RAW — no consumer build step transpiles it — so it
10
+ * targets the same floor the family's bundles do (vite target es2020).
11
+ * A browser older than that cannot run the app it belongs to either; it
12
+ * simply keeps its unthemed first paint. Keep this file free of syntax
13
+ * NEWER than ES2020: a parse error would void the whole inline script and
14
+ * the surrounding try/catch cannot recover from a parse failure. */
15
+ (function () {
16
+ var DEG = 0.017453292519943295;
17
+ var RAD = 57.29577951308232;
18
+ var DEFAULT_GEO_LOCATION = {"lat":31.23,"lng":121.47};
19
+ var toJulianDate = function toJulianDate(date) {
20
+ return date.getTime() / 864e5 + 2440587.5;
21
+ };
22
+ var greenwichSiderealTime = function greenwichSiderealTime(jd) {
23
+ const T = (jd - 2451545) / 36525;
24
+ let theta = (280.46061837 + 360.98564736629 * (jd - 2451545) + 387933e-9 * T * T - T * T * T / 3871e4) % 360;
25
+ if (theta < 0) theta += 360;
26
+ return theta;
27
+ };
28
+ var sunEquatorialCoordinates = function sunEquatorialCoordinates(jd) {
29
+ const T = (jd - 2451545) / 36525;
30
+ const L0 = (280.46646 + 36000.76983 * T) % 360;
31
+ const M = (357.52911 + 35999.05029 * T) % 360 * DEG;
32
+ const C = (1.9146 - .004817 * T) * Math.sin(M) + (.019993 - 101e-6 * T) * Math.sin(2 * M);
33
+ let sunLon = (L0 + C) % 360;
34
+ if (sunLon < 0) sunLon += 360;
35
+ const omega = (125.04 - 1934.136 * T) * DEG;
36
+ const lambda = sunLon * DEG - .00569 * DEG - .00478 * DEG * Math.sin(omega);
37
+ const epsilon = (23.439291 - .013004 * T) * DEG;
38
+ const decl = Math.asin(Math.sin(epsilon) * Math.sin(lambda));
39
+ const ra = Math.atan2(Math.cos(epsilon) * Math.sin(lambda), Math.cos(lambda));
40
+ return {
41
+ decl,
42
+ ra
43
+ };
44
+ };
45
+ var solarAltitude = function solarAltitude(latDeg, lngDeg, date) {
46
+ const jd = toJulianDate(date);
47
+ const { decl, ra } = sunEquatorialCoordinates(jd);
48
+ let haDeg = greenwichSiderealTime(jd) + lngDeg - ra * RAD;
49
+ haDeg = ((haDeg + 180) % 360 + 360) % 360 - 180;
50
+ const ha = haDeg * DEG;
51
+ const lat = latDeg * DEG;
52
+ const alt = Math.asin(Math.sin(lat) * Math.sin(decl) + Math.cos(lat) * Math.cos(decl) * Math.cos(ha));
53
+ return alt * RAD;
54
+ };
55
+ var zoneOffsetMinutes = function zoneOffsetMinutes(timeZone, date) {
56
+ const name = new Intl.DateTimeFormat("en-US", {
57
+ timeZone,
58
+ timeZoneName: "longOffset"
59
+ }).formatToParts(date).find((p) => p.type === "timeZoneName")?.value;
60
+ const m = name ? /GMT([+-])(\d{1,2}):?(\d{2})?/.exec(name) : null;
61
+ if (!m) return 0;
62
+ const minutes = Number(m[2]) * 60 + Number(m[3] ?? 0);
63
+ return m[1] === "-" ? -minutes : minutes;
64
+ };
65
+ var manualLocationOf = function manualLocationOf(cfg) {
66
+ const lat = cfg.hemisphere === "south" ? -DEFAULT_GEO_LOCATION.lat : DEFAULT_GEO_LOCATION.lat;
67
+ const year = new Date().getFullYear();
68
+ const standardOffset = Math.min(zoneOffsetMinutes(cfg.timeZone, new Date(year, 0, 15)), zoneOffsetMinutes(cfg.timeZone, new Date(year, 6, 15)));
69
+ return {
70
+ lat,
71
+ lng: standardOffset / 4
72
+ };
73
+ };
74
+ try {
75
+ var d = document.documentElement;
76
+ var read = function (k) { try { return localStorage.getItem(k); } catch (e) { return null; } };
77
+ var t = read("hikari-theme");
78
+ var m = read("hikari-theme-mode");
79
+ var strategy = read("hikari-solar-strategy");
80
+ if (strategy !== "timezone" && strategy !== "ip" && strategy !== "manual") strategy = "timezone";
81
+ var NOW = (typeof __hikariBootNow !== "undefined" && __hikariBootNow) ? new Date(__hikariBootNow) : new Date();
82
+ var geo = { lat: DEFAULT_GEO_LOCATION.lat, lng: -NOW.getTimezoneOffset() / 4 };
83
+ if (strategy === "manual") {
84
+ try {
85
+ var raw = read("hikari-solar-manual");
86
+ if (raw) {
87
+ var cfg = JSON.parse(raw);
88
+ var ok = cfg && typeof cfg === "object" && typeof cfg.timeZone === "string" &&
89
+ (cfg.hemisphere === "north" || cfg.hemisphere === "south");
90
+ if (ok) {
91
+ try { new Intl.DateTimeFormat("en-US", { timeZone: cfg.timeZone }); }
92
+ catch (e) { ok = false; }
93
+ }
94
+ if (ok) geo = manualLocationOf(cfg);
95
+ }
96
+ } catch (e) {}
97
+ }
98
+ var alt = solarAltitude(geo.lat, geo.lng, NOW);
99
+ if (!(m === "light" || m === "dark")) {
100
+ m = alt > 6 ? "light" : "dark";
101
+ }
102
+ var themeId = t || (typeof window !== "undefined" && window.__celestiaDefaultTheme) || "default";
103
+ d.setAttribute("data-theme", themeId);
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) {}
151
+ } catch (e) {}
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);
@@ -0,0 +1,257 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { describe, expect, it } from "vitest";
5
+
6
+ import { buildThemeBootJs, resolveSystemModeAt } from "./themeBoot";
7
+ import { THEME_VARS_MEMO_VERSION } from "./presets";
8
+
9
+ /**
10
+ * Drift contract for the SHIPPED BOOT ASSET (hikari#1546 Phase 1.5): the
11
+ * checked-in `src/styles/theme-boot.js` must be byte-identical to
12
+ * `buildThemeBootJs()`, and — the load-bearing half — the emitted IIFE must
13
+ * RESOLVE the same system mode as `resolveSystemModeAt` across a grid of
14
+ * dates. The math is serialized from useSolarTime's own functions via
15
+ * `toString()`, so math drift is impossible by construction; what this
16
+ * grid pins is the WRAPPER (storage reads, manual-config validation,
17
+ * attribute writes) staying in lockstep with the module's branch structure.
18
+ * MUT:mut-boot-grid — breaking the emitted chain's altitude call REDS the
19
+ * grid; the manual-config case additionally pins two meridians whose
20
+ * answers cannot depend on this host.
21
+ *
22
+ * Regeneration (same toolchain discipline as theme-vars.css):
23
+ *
24
+ * REGEN_THEME_VARS=1 \
25
+ * node_modules/.bin/vitest run src/theme/themeBoot.contract.test.ts
26
+ */
27
+ const here = dirname(fileURLToPath(import.meta.url));
28
+ const jsPath = join(here, "..", "styles", "theme-boot.js");
29
+
30
+ /** Execute the emitted IIFE against fakes; return what it set. */
31
+ function runBoot(
32
+ js: string,
33
+ opts: { now: Date; storage?: Record<string, string> },
34
+ ): {
35
+ theme: string | null;
36
+ mode: string | null;
37
+ styles: Array<{ tag: string; attr: Record<string, string>; text: string }>;
38
+ } {
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
+ };
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
+ },
68
+ documentElement: {
69
+ setAttribute(k: string, v: string) {
70
+ attrs[k] = v;
71
+ },
72
+ },
73
+ };
74
+ const store = opts.storage ?? {};
75
+ const fakeStorage = {
76
+ getItem(k: string) {
77
+ return k in store ? store[k] : null;
78
+ },
79
+ };
80
+ // `Date` is SHADOWED in the asset's scope with a subclass pinned to the
81
+ // grid instant — the wrapper's bare `new Date()` must observe the grid
82
+ // date, not the wall clock, or the compare is meaningless.
83
+ const pinned = opts.now.getTime();
84
+ const PinnedDate = class extends Date {
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());
93
+ }
94
+ static now() {
95
+ return pinned;
96
+ }
97
+ };
98
+ // eslint-disable-next-line no-new-func -- executing the emitted asset is the point
99
+ new Function("__hikariBootNow", "Date", "document", "localStorage", js)(
100
+ undefined,
101
+ PinnedDate,
102
+ fakeDoc,
103
+ fakeStorage,
104
+ );
105
+ return {
106
+ theme: attrs["data-theme"] ?? null,
107
+ mode: attrs["data-mode"] ?? null,
108
+ styles: appended,
109
+ };
110
+ }
111
+
112
+ describe("shipped theme boot asset (hikari#1546 Phase 1.5)", () => {
113
+ const js = buildThemeBootJs();
114
+
115
+ it("matches the shipped asset byte-for-byte", () => {
116
+ const checkedIn = readFileSync(jsPath, "utf8");
117
+ if (checkedIn === js) return;
118
+ if (process.env.REGEN_THEME_VARS === "1") {
119
+ writeFileSync(jsPath, js);
120
+ expect(readFileSync(jsPath, "utf8"), "regen wrote the composition").toBe(js);
121
+ console.log(`REGEN: rewrote drifted ${jsPath} (${js.length} bytes)`);
122
+ return;
123
+ }
124
+ expect(checkedIn).toBe(js);
125
+ });
126
+
127
+ it("resolves the same system mode as the module across a year of dates", () => {
128
+ // Hourly grid across four seasonal anchors — every branch of the
129
+ // altitude math (deep day, dusk band, deep night) must agree between
130
+ // the emitted asset and the module. The machine's local zone feeds
131
+ // BOTH sides identically (getTimezoneOffset / Intl), so the compare is
132
+ // exact regardless of where this runs.
133
+ const seasonal = [0, 91, 182, 273].map((day) => new Date(Date.UTC(2026, 0, 1 + day, 12, 0, 0)));
134
+ for (const base of seasonal) {
135
+ for (let h = 0; h < 24; h += 3) {
136
+ const at = new Date(base.getTime() + h * 3600_000);
137
+ const emitted = runBoot(js, { now: at });
138
+ const expected = resolveSystemModeAt(at);
139
+ expect(emitted.mode, `data-mode at ${at.toISOString()}`).toBe(expected);
140
+ }
141
+ }
142
+ });
143
+
144
+ it("honors an explicit stored mode over the solar answer", () => {
145
+ const at = new Date(Date.UTC(2026, 6, 1, 12, 0, 0)); // whatever the solar says
146
+ const explicit = runBoot(js, { now: at, storage: { "hikari-theme-mode": "light" } });
147
+ expect(explicit.mode).toBe("light");
148
+ const explicitDark = runBoot(js, { now: at, storage: { "hikari-theme-mode": "dark" } });
149
+ expect(explicitDark.mode).toBe("dark");
150
+ });
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
+
219
+ it("routes a stored manual config through the zone meridian, machine-independently", () => {
220
+ // Round-2 review (S1): the first version compared the wrapper (fake
221
+ // storage, manual config) against the MODULE (real localStorage, empty
222
+ // -> "timezone" estimate), which only agreed on the author's host. Both
223
+ // sides now read the SAME storage object, and the anti-vacuity pins two
224
+ // manual configs whose answers are fixed by their own timeZone — no
225
+ // dependence on this machine's zone.
226
+ const at = new Date(Date.UTC(2026, 6, 1, 12, 0, 0)); // July 1, 12:00Z
227
+ const manual = (timeZone: string) =>
228
+ JSON.stringify({ timeZone, hemisphere: "north" });
229
+ const storeFor = (timeZone: string) => ({
230
+ "hikari-solar-strategy": "manual",
231
+ "hikari-solar-manual": manual(timeZone),
232
+ });
233
+ const asBootStorage = (m: Record<string, string>) => ({
234
+ getItem: (k: string) => (k in m ? m[k]! : null),
235
+ });
236
+
237
+ // Greenwich meridian at July noon: the sun is high -> light.
238
+ const utcStore = storeFor("UTC");
239
+ const utc = runBoot(js, { now: at, storage: utcStore });
240
+ expect(utc.mode, "UTC (lng 0) at July noon is DAY").toBe("light");
241
+ expect(utc.mode, "module and asset agree on the manual path").toBe(
242
+ resolveSystemModeAt(at, asBootStorage(utcStore)),
243
+ );
244
+
245
+ // Auckland's standard meridian is 180 degrees away: the same instant is
246
+ // local midnight there -> night. Machine-independent by construction
247
+ // (both configs pin lat AND lng), so this cannot pass vacuously.
248
+ const aklStore = storeFor("Pacific/Auckland");
249
+ const akl = runBoot(js, { now: at, storage: aklStore });
250
+ expect(akl.mode, "Auckland (lng 180) at the same instant is NIGHT").toBe("dark");
251
+ expect(akl.mode, "module and asset agree on the far meridian").toBe(
252
+ resolveSystemModeAt(at, asBootStorage(aklStore)),
253
+ );
254
+ expect(utc.mode, "the two configs really do differ").not.toBe(akl.mode);
255
+ });
256
+ });
257
+
@@ -0,0 +1,254 @@
1
+ import {
2
+ THEME_VARS_MEMO_KEY,
3
+ THEME_VARS_MEMO_VERSION,
4
+ } from "./presets";
5
+ import { readStorageItem } from "./safeStorage";
6
+ import {
7
+ DEFAULT_GEO_LOCATION,
8
+ isKnownTimeZone,
9
+ manualLocationOf,
10
+ solarAltitude,
11
+ sunEquatorialCoordinates,
12
+ greenwichSiderealTime,
13
+ toJulianDate,
14
+ zoneOffsetMinutes,
15
+ SOLAR_LOCATION_STRATEGY_STORAGE_KEY,
16
+ SOLAR_MANUAL_LOCATION_STORAGE_KEY,
17
+ type SolarLocationStrategy,
18
+ type SolarManualLocation,
19
+ } from "./useSolarTime";
20
+
21
+ /**
22
+ * The PRE-PAINT theme resolver and its shipped boot asset (hikari#1546
23
+ * Phase 1.5, user direction 2026-11-25: 一整套统一 — one resolution
24
+ * executed on BOTH sides of hydration).
25
+ *
26
+ * `resolveSystemModeAt` runs the solar chain's SYNC path exactly as the
27
+ * reactive runtime resolves mode "system": manual config (when the stored
28
+ * strategy selects it and the payload validates) → the timezone estimate
29
+ * (stock default latitude + UTC-offset longitude) → solar altitude →
30
+ * day → light, else dark. Dependency-free by design (safeStorage only —
31
+ * no vue, no cronBus) so it can ride the pre-paint asset.
32
+ *
33
+ * Two documented divergences from the reactive runtime, both narrow:
34
+ * - strategy "ip": the runtime may improve the coords via a
35
+ * granted-browser-geolocation / IP cascade (async, networked). The boot
36
+ * asset cannot — it uses the timezone estimate. The runtime's answer
37
+ * lands with the bundle and self-heals.
38
+ * - stale stored values: the runtime's readers also REMOVE bad payloads;
39
+ * the boot asset is read-only (pre-paint storage writes would be a
40
+ * surprise) and falls back instead. Removal happens at initTheme.
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
+ *
48
+ * `buildThemeBootJs()` ships the chain as a dependency-free IIFE for
49
+ * consumers to inline in `<head>` (lagrange interpolates it with a `?raw`
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
56
+ * useSolarTime's OWN definitions — the asset cannot drift from the
57
+ * runtime's solar chain by construction; `themeBoot.contract.test.ts`
58
+ * executes the emitted asset against `resolveSystemModeAt` across a date
59
+ * grid to pin the wrapper (storage reads + attribute writes) instead.
60
+ */
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
+
66
+ const DEG = Math.PI / 180;
67
+ const RAD = 180 / Math.PI;
68
+
69
+ /** A read-only storage surface — the seam that lets the contract test feed
70
+ * the resolver the SAME values the emitted asset reads (a test runner may
71
+ * have no `localStorage` at all, and comparing against the environment's
72
+ * storage made the parity assertion machine-dependent: review round 2). */
73
+ export interface BootStorage {
74
+ getItem(key: string): string | null;
75
+ }
76
+
77
+ /** One strategy branch only: manual config or the offline estimate. The
78
+ * "ip" cascade is async and networked — never a pre-paint concern. */
79
+ function bootGeoLocation(
80
+ strategy: SolarLocationStrategy,
81
+ storage: BootStorage,
82
+ at: Date,
83
+ ): {
84
+ lat: number;
85
+ lng: number;
86
+ } {
87
+ if (strategy === "manual") {
88
+ const raw = storage.getItem(SOLAR_MANUAL_LOCATION_STORAGE_KEY);
89
+ if (raw) {
90
+ try {
91
+ const parsed: unknown = JSON.parse(raw);
92
+ if (
93
+ typeof parsed === "object" &&
94
+ parsed !== null &&
95
+ "timeZone" in parsed &&
96
+ "hemisphere" in parsed &&
97
+ typeof (parsed as SolarManualLocation).timeZone === "string" &&
98
+ ((parsed as SolarManualLocation).hemisphere === "north" ||
99
+ (parsed as SolarManualLocation).hemisphere === "south") &&
100
+ isKnownTimeZone((parsed as SolarManualLocation).timeZone)
101
+ ) {
102
+ return manualLocationOf(parsed as SolarManualLocation);
103
+ }
104
+ } catch {
105
+ // Corrupt payload — the estimate below is the offline answer.
106
+ }
107
+ }
108
+ }
109
+ // "timezone" (the default), manual-with-invalid-config, and "ip"-offline
110
+ // all land here: lat = the stock default, lng = the zone's center meridian
111
+ // derived from the UTC offset **at the resolved instant** — NOT at the wall
112
+ // clock. Same value when resolving "now" (the only real caller), and it
113
+ // removes the last host-and-season dependence from the parity test (a
114
+ // grid instant in another DST season would otherwise shift the meridian by
115
+ // up to 15° against the asset's NOW-based offset).
116
+ const offsetMin = -at.getTimezoneOffset();
117
+ return { lat: DEFAULT_GEO_LOCATION.lat, lng: offsetMin / 4 };
118
+ }
119
+
120
+ /** The runtime contract, sync path: mode "system" is light only while the
121
+ * sun is genuinely up (altitude > 6°); dusk and night are dark. */
122
+ export function resolveSystemModeAt(
123
+ date: Date = new Date(),
124
+ storage: BootStorage = { getItem: (k) => readStorageItem(k) },
125
+ ): "dark" | "light" {
126
+ let strategy: SolarLocationStrategy = "timezone";
127
+ const stored = storage.getItem(SOLAR_LOCATION_STRATEGY_STORAGE_KEY);
128
+ if (stored === "timezone" || stored === "ip" || stored === "manual") {
129
+ strategy = stored;
130
+ }
131
+ const geo = bootGeoLocation(strategy, storage, date);
132
+ const alt = solarAltitude(geo.lat, geo.lng, date);
133
+ return alt > 6 ? "light" : "dark";
134
+ }
135
+
136
+ /** Serialize the boot IIFE. The math is emitted from useSolarTime's own
137
+ * function sources (toString) plus the two constants they close over —
138
+ * emitted BEFORE the functions, so the copy executes exactly what the
139
+ * runtime executes. */
140
+ export function buildThemeBootJs(): string {
141
+ const constBlock = [
142
+ `var DEG = ${DEG};`,
143
+ `var RAD = ${RAD};`,
144
+ `var DEFAULT_GEO_LOCATION = ${JSON.stringify(DEFAULT_GEO_LOCATION)};`,
145
+ ].join("\n");
146
+ const serialized = [
147
+ toJulianDate,
148
+ greenwichSiderealTime,
149
+ sunEquatorialCoordinates,
150
+ solarAltitude,
151
+ zoneOffsetMinutes,
152
+ manualLocationOf,
153
+ ]
154
+ .map((fn) => `var ${fn.name} = ${fn.toString()};`)
155
+ .join("\n");
156
+ const wrapper = `try {
157
+ var d = document.documentElement;
158
+ var read = function (k) { try { return localStorage.getItem(k); } catch (e) { return null; } };
159
+ var t = read("hikari-theme");
160
+ var m = read("hikari-theme-mode");
161
+ var strategy = read("${SOLAR_LOCATION_STRATEGY_STORAGE_KEY}");
162
+ if (strategy !== "timezone" && strategy !== "ip" && strategy !== "manual") strategy = "timezone";
163
+ var NOW = (typeof __hikariBootNow !== "undefined" && __hikariBootNow) ? new Date(__hikariBootNow) : new Date();
164
+ var geo = { lat: DEFAULT_GEO_LOCATION.lat, lng: -NOW.getTimezoneOffset() / 4 };
165
+ if (strategy === "manual") {
166
+ try {
167
+ var raw = read("${SOLAR_MANUAL_LOCATION_STORAGE_KEY}");
168
+ if (raw) {
169
+ var cfg = JSON.parse(raw);
170
+ var ok = cfg && typeof cfg === "object" && typeof cfg.timeZone === "string" &&
171
+ (cfg.hemisphere === "north" || cfg.hemisphere === "south");
172
+ if (ok) {
173
+ try { new Intl.DateTimeFormat("en-US", { timeZone: cfg.timeZone }); }
174
+ catch (e) { ok = false; }
175
+ }
176
+ if (ok) geo = manualLocationOf(cfg);
177
+ }
178
+ } catch (e) {}
179
+ }
180
+ var alt = solarAltitude(geo.lat, geo.lng, NOW);
181
+ if (!(m === "light" || m === "dark")) {
182
+ m = alt > 6 ? "light" : "dark";
183
+ }
184
+ var themeId = t || (typeof window !== "undefined" && window.__celestiaDefaultTheme) || "default";
185
+ d.setAttribute("data-theme", themeId);
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) {}
233
+ } catch (e) {}`;
234
+ return `/* GENERATED by packages/vue/src/theme/themeBoot.ts (buildThemeBootJs) —
235
+ * do not edit by hand. The math functions are serialized from useSolarTime's
236
+ * own definitions via toString(), so this asset cannot drift from the
237
+ * runtime's solar chain by construction; the wrapper (storage reads +
238
+ * attribute writes) is pinned by themeBoot.contract.test.ts. Inline in
239
+ * <head> BEFORE the theme-vars sheet's first paint.
240
+ *
241
+ * SYNTAX FLOOR: ES2020 (const/let, arrow functions, optional chaining).
242
+ * The asset is inlined RAW — no consumer build step transpiles it — so it
243
+ * targets the same floor the family's bundles do (vite target es2020).
244
+ * A browser older than that cannot run the app it belongs to either; it
245
+ * simply keeps its unthemed first paint. Keep this file free of syntax
246
+ * NEWER than ES2020: a parse error would void the whole inline script and
247
+ * the surrounding try/catch cannot recover from a parse failure. */
248
+ (function () {
249
+ ${constBlock}
250
+ ${serialized}
251
+ ${wrapper}
252
+ })();
253
+ `;
254
+ }
@@ -8,23 +8,23 @@ export type TimePeriod = "day" | "dusk" | "night";
8
8
  const DEG = Math.PI / 180;
9
9
  const RAD = 180 / Math.PI;
10
10
 
11
- function toJulianDate(date: Date): number {
11
+ export function toJulianDate(date: Date): number {
12
12
  return date.getTime() / 86400000 + 2440587.5;
13
13
  }
14
14
 
15
- function greenwichSiderealTime(jd: number): number {
15
+ export function greenwichSiderealTime(jd: number): number {
16
16
  const T = (jd - 2451545.0) / 36525;
17
17
  let theta = (280.46061837 + 360.98564736629 * (jd - 2451545.0) + 0.000387933 * T * T - T * T * T / 38710000) % 360;
18
18
  if (theta < 0) theta += 360;
19
19
  return theta;
20
20
  }
21
21
 
22
- interface SunEquatorial {
22
+ export interface SunEquatorial {
23
23
  decl: number;
24
24
  ra: number;
25
25
  }
26
26
 
27
- function sunEquatorialCoordinates(jd: number): SunEquatorial {
27
+ export function sunEquatorialCoordinates(jd: number): SunEquatorial {
28
28
  const T = (jd - 2451545.0) / 36525;
29
29
  const L0 = (280.46646 + 36000.76983 * T) % 360;
30
30
  const M = ((357.52911 + 35999.05029 * T) % 360) * DEG;
@@ -146,7 +146,7 @@ function isSolarHemisphere(v: unknown): v is SolarHemisphere {
146
146
  /** Intl constructs a formatter only for ids it knows — the constructor
147
147
  * throws RangeError otherwise, which is the whole validation story for
148
148
  * manually chosen zones. */
149
- function isKnownTimeZone(timeZone: string): boolean {
149
+ export function isKnownTimeZone(timeZone: string): boolean {
150
150
  if (!timeZone) return false;
151
151
  try {
152
152
  new Intl.DateTimeFormat("en-US", { timeZone });
@@ -253,7 +253,7 @@ export function setSolarManualLocation(cfg: SolarManualLocation | null): void {
253
253
 
254
254
  /** The zone's UTC offset in minutes at the given instant, parsed from the
255
255
  * `longOffset` name ("GMT+08:00", "GMT-03:30"; plain "GMT" for UTC). */
256
- function zoneOffsetMinutes(timeZone: string, date: Date): number {
256
+ export function zoneOffsetMinutes(timeZone: string, date: Date): number {
257
257
  const name = new Intl.DateTimeFormat("en-US", { timeZone, timeZoneName: "longOffset" })
258
258
  .formatToParts(date)
259
259
  .find((p) => p.type === "timeZoneName")?.value;
@@ -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