@celestia-island/hikari 0.55.483 → 0.55.485

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.
@@ -0,0 +1,15 @@
1
+ /** A read-only storage surface — the seam that lets the contract test feed
2
+ * the resolver the SAME values the emitted asset reads (a test runner may
3
+ * have no `localStorage` at all, and comparing against the environment's
4
+ * storage made the parity assertion machine-dependent: review round 2). */
5
+ export interface BootStorage {
6
+ getItem(key: string): string | null;
7
+ }
8
+ /** The runtime contract, sync path: mode "system" is light only while the
9
+ * sun is genuinely up (altitude > 6°); dusk and night are dark. */
10
+ export declare function resolveSystemModeAt(date?: Date, storage?: BootStorage): "dark" | "light";
11
+ /** Serialize the boot IIFE. The math is emitted from useSolarTime's own
12
+ * function sources (toString) plus the two constants they close over —
13
+ * emitted BEFORE the functions, so the copy executes exactly what the
14
+ * runtime executes. */
15
+ export declare function buildThemeBootJs(): string;
@@ -0,0 +1 @@
1
+ export declare function buildThemeVarsCss(): 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.483",
3
+ "version": "0.55.485",
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,105 @@
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
+ d.setAttribute("data-theme", t || (typeof window !== "undefined" && window.__celestiaDefaultTheme) || "default");
103
+ d.setAttribute("data-mode", m);
104
+ } catch (e) {}
105
+ })();
@@ -0,0 +1,117 @@
1
+ /* GENERATED by themeVarsCss.contract.test.ts (REGEN_THEME_VARS=1) —
2
+ * do not edit by hand. Source: the stock `default` preset in
3
+ * presets.ts; the regen command is in the contract test doc block. */
4
+ html[data-mode="dark"] {
5
+ --color-primary: 136 192 208;
6
+ --color-on-primary: 0 0 0;
7
+ --color-on-solid-text: 46 52 64;
8
+ --color-on-solid-icon: 46 52 64;
9
+ --color-on-solid: 46 52 64;
10
+ --color-on-danger: 255 255 255;
11
+ --color-on-success: 255 255 255;
12
+ --color-on-warning: 255 255 255;
13
+ --color-on-info: 255 255 255;
14
+ --color-secondary: 143 188 187;
15
+ --color-accent: 94 129 172;
16
+ --color-text: 247 249 252;
17
+ --color-text-secondary: 230 232 234;
18
+ --color-text-tertiary: 214 215 216;
19
+ --color-muted: 180 180 180;
20
+ --color-border: 128 128 128;
21
+ --color-focused-border: 136 192 208;
22
+ --color-background: 22 27 38;
23
+ --color-surface: 34 40 54;
24
+ --color-selected-bg: 70 70 85;
25
+ --color-selected-text: 248 248 250;
26
+ --color-status-bar-bg: 34 40 54;
27
+ --color-success: 31 101 48;
28
+ --color-error: 166 41 55;
29
+ --color-warning: 137 72 0;
30
+ --color-info: 0 98 116;
31
+ --hi-color-primary: rgb(var(--color-primary));
32
+ --hi-color-secondary: rgb(var(--color-secondary));
33
+ --hi-color-surface: rgb(var(--color-surface));
34
+ --hi-color-background: rgb(var(--color-background));
35
+ --hi-color-border: rgb(var(--color-border) / 15%);
36
+ --hi-color-text-primary: rgb(var(--color-text));
37
+ --hi-color-text-secondary: rgb(var(--color-text-secondary));
38
+ --hi-color-muted: rgb(var(--color-muted));
39
+ --hi-color-on-primary: rgb(var(--color-on-primary));
40
+ --hi-color-text-on-primary: rgb(var(--color-on-primary));
41
+ --hi-color-text-on-solid: rgb(var(--color-on-solid-text, 255 255 255));
42
+ --hi-color-icon-on-solid: rgb(var(--color-on-solid-icon, 255 255 255));
43
+ --hi-color-success: rgb(var(--color-success));
44
+ --hi-color-error: rgb(var(--color-error));
45
+ --hi-color-warning: rgb(var(--color-warning));
46
+ --hi-color-info: rgb(var(--color-info));
47
+ --hi-color-text-on-danger: rgb(var(--color-on-danger));
48
+ --hi-color-text-on-success: rgb(var(--color-on-success));
49
+ --hi-color-text-on-warning: rgb(var(--color-on-warning));
50
+ --hi-color-text-on-info: rgb(var(--color-on-info));
51
+ --hi-color-success-fg: rgb(94 162 105);
52
+ --hi-color-danger-fg: rgb(233 104 109);
53
+ --hi-color-warning-fg: rgb(200 130 73);
54
+ --hi-color-info-fg: rgb(81 158 177);
55
+ --hi-color-bg-subtle: rgb(var(--color-surface) / 0.5);
56
+ --hi-color-bg-elevated: rgb(var(--color-surface));
57
+ --hi-color-bg-container: rgb(var(--color-surface));
58
+ --hi-color-bg-canvas: rgb(var(--color-background));
59
+ --hi-secondary-bg: rgb(var(--color-surface) / 0.5);
60
+ }
61
+ html[data-mode="light"] {
62
+ --color-primary: 214 51 132;
63
+ --color-on-primary: 255 255 255;
64
+ --color-on-solid-text: 255 255 255;
65
+ --color-on-solid-icon: 255 255 255;
66
+ --color-on-solid: 255 255 255;
67
+ --color-on-danger: 255 255 255;
68
+ --color-on-success: 255 255 255;
69
+ --color-on-warning: 255 255 255;
70
+ --color-on-info: 255 255 255;
71
+ --color-secondary: 156 106 222;
72
+ --color-accent: 230 167 0;
73
+ --color-text: 30 30 30;
74
+ --color-text-secondary: 43 43 43;
75
+ --color-text-tertiary: 55 55 55;
76
+ --color-muted: 80 80 80;
77
+ --color-border: 128 128 128;
78
+ --color-focused-border: 214 51 132;
79
+ --color-background: 245 245 240;
80
+ --color-surface: 255 255 255;
81
+ --color-selected-bg: 200 200 205;
82
+ --color-selected-text: 40 40 45;
83
+ --color-status-bar-bg: 230 230 225;
84
+ --color-success: 31 101 48;
85
+ --color-error: 166 41 55;
86
+ --color-warning: 137 72 0;
87
+ --color-info: 0 98 116;
88
+ --hi-color-primary: rgb(var(--color-primary));
89
+ --hi-color-secondary: rgb(var(--color-secondary));
90
+ --hi-color-surface: rgb(var(--color-surface));
91
+ --hi-color-background: rgb(var(--color-background));
92
+ --hi-color-border: rgb(var(--color-border) / 15%);
93
+ --hi-color-text-primary: rgb(var(--color-text));
94
+ --hi-color-text-secondary: rgb(var(--color-text-secondary));
95
+ --hi-color-muted: rgb(var(--color-muted));
96
+ --hi-color-on-primary: rgb(var(--color-on-primary));
97
+ --hi-color-text-on-primary: rgb(var(--color-on-primary));
98
+ --hi-color-text-on-solid: rgb(var(--color-on-solid-text, 255 255 255));
99
+ --hi-color-icon-on-solid: rgb(var(--color-on-solid-icon, 255 255 255));
100
+ --hi-color-success: rgb(var(--color-success));
101
+ --hi-color-error: rgb(var(--color-error));
102
+ --hi-color-warning: rgb(var(--color-warning));
103
+ --hi-color-info: rgb(var(--color-info));
104
+ --hi-color-text-on-danger: rgb(var(--color-on-danger));
105
+ --hi-color-text-on-success: rgb(var(--color-on-success));
106
+ --hi-color-text-on-warning: rgb(var(--color-on-warning));
107
+ --hi-color-text-on-info: rgb(var(--color-on-info));
108
+ --hi-color-success-fg: rgb(31 101 48);
109
+ --hi-color-danger-fg: rgb(166 41 55);
110
+ --hi-color-warning-fg: rgb(137 72 0);
111
+ --hi-color-info-fg: rgb(0 98 116);
112
+ --hi-color-bg-subtle: rgb(var(--color-surface) / 0.5);
113
+ --hi-color-bg-elevated: rgb(var(--color-surface));
114
+ --hi-color-bg-container: rgb(var(--color-surface));
115
+ --hi-color-bg-canvas: rgb(var(--color-background));
116
+ --hi-secondary-bg: rgb(var(--color-surface) / 0.5);
117
+ }
@@ -0,0 +1,147 @@
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
+
8
+ /**
9
+ * Drift contract for the SHIPPED BOOT ASSET (hikari#1546 Phase 1.5): the
10
+ * checked-in `src/styles/theme-boot.js` must be byte-identical to
11
+ * `buildThemeBootJs()`, and — the load-bearing half — the emitted IIFE must
12
+ * RESOLVE the same system mode as `resolveSystemModeAt` across a grid of
13
+ * dates. The math is serialized from useSolarTime's own functions via
14
+ * `toString()`, so math drift is impossible by construction; what this
15
+ * grid pins is the WRAPPER (storage reads, manual-config validation,
16
+ * attribute writes) staying in lockstep with the module's branch structure.
17
+ * MUT:mut-boot-grid — breaking the emitted chain's altitude call REDS the
18
+ * grid; the manual-config case additionally pins two meridians whose
19
+ * answers cannot depend on this host.
20
+ *
21
+ * Regeneration (same toolchain discipline as theme-vars.css):
22
+ *
23
+ * REGEN_THEME_VARS=1 \
24
+ * node_modules/.bin/vitest run src/theme/themeBoot.contract.test.ts
25
+ */
26
+ const here = dirname(fileURLToPath(import.meta.url));
27
+ const jsPath = join(here, "..", "styles", "theme-boot.js");
28
+
29
+ /** Execute the emitted IIFE against fakes; return what it set. */
30
+ function runBoot(
31
+ js: string,
32
+ opts: { now: Date; storage?: Record<string, string> },
33
+ ): { theme: string | null; mode: string | null } {
34
+ const attrs: Record<string, string> = {};
35
+ const fakeDoc = {
36
+ documentElement: {
37
+ setAttribute(k: string, v: string) {
38
+ attrs[k] = v;
39
+ },
40
+ },
41
+ };
42
+ const store = opts.storage ?? {};
43
+ const fakeStorage = {
44
+ getItem(k: string) {
45
+ return k in store ? store[k] : null;
46
+ },
47
+ };
48
+ // `Date` is SHADOWED in the asset's scope with a subclass pinned to the
49
+ // grid instant — the wrapper's bare `new Date()` must observe the grid
50
+ // date, not the wall clock, or the compare is meaningless.
51
+ const PinnedDate = class extends Date {
52
+ constructor(...args: unknown[]) {
53
+ super(...(args.length ? (args as ConstructorParameters<typeof Date>) : [opts.now.getTime()]));
54
+ }
55
+ static now() {
56
+ return opts.now.getTime();
57
+ }
58
+ };
59
+ // eslint-disable-next-line no-new-func -- executing the emitted asset is the point
60
+ new Function("__hikariBootNow", "Date", "document", "localStorage", js)(
61
+ undefined,
62
+ PinnedDate,
63
+ fakeDoc,
64
+ fakeStorage,
65
+ );
66
+ return { theme: attrs["data-theme"] ?? null, mode: attrs["data-mode"] ?? null };
67
+ }
68
+
69
+ describe("shipped theme boot asset (hikari#1546 Phase 1.5)", () => {
70
+ const js = buildThemeBootJs();
71
+
72
+ it("matches the shipped asset byte-for-byte", () => {
73
+ const checkedIn = readFileSync(jsPath, "utf8");
74
+ if (checkedIn === js) return;
75
+ if (process.env.REGEN_THEME_VARS === "1") {
76
+ writeFileSync(jsPath, js);
77
+ expect(readFileSync(jsPath, "utf8"), "regen wrote the composition").toBe(js);
78
+ console.log(`REGEN: rewrote drifted ${jsPath} (${js.length} bytes)`);
79
+ return;
80
+ }
81
+ expect(checkedIn).toBe(js);
82
+ });
83
+
84
+ it("resolves the same system mode as the module across a year of dates", () => {
85
+ // Hourly grid across four seasonal anchors — every branch of the
86
+ // altitude math (deep day, dusk band, deep night) must agree between
87
+ // the emitted asset and the module. The machine's local zone feeds
88
+ // BOTH sides identically (getTimezoneOffset / Intl), so the compare is
89
+ // exact regardless of where this runs.
90
+ const seasonal = [0, 91, 182, 273].map((day) => new Date(Date.UTC(2026, 0, 1 + day, 12, 0, 0)));
91
+ for (const base of seasonal) {
92
+ for (let h = 0; h < 24; h += 3) {
93
+ const at = new Date(base.getTime() + h * 3600_000);
94
+ const emitted = runBoot(js, { now: at });
95
+ const expected = resolveSystemModeAt(at);
96
+ expect(emitted.mode, `data-mode at ${at.toISOString()}`).toBe(expected);
97
+ }
98
+ }
99
+ });
100
+
101
+ it("honors an explicit stored mode over the solar answer", () => {
102
+ const at = new Date(Date.UTC(2026, 6, 1, 12, 0, 0)); // whatever the solar says
103
+ const explicit = runBoot(js, { now: at, storage: { "hikari-theme-mode": "light" } });
104
+ expect(explicit.mode).toBe("light");
105
+ const explicitDark = runBoot(js, { now: at, storage: { "hikari-theme-mode": "dark" } });
106
+ expect(explicitDark.mode).toBe("dark");
107
+ });
108
+
109
+ it("routes a stored manual config through the zone meridian, machine-independently", () => {
110
+ // Round-2 review (S1): the first version compared the wrapper (fake
111
+ // storage, manual config) against the MODULE (real localStorage, empty
112
+ // -> "timezone" estimate), which only agreed on the author's host. Both
113
+ // sides now read the SAME storage object, and the anti-vacuity pins two
114
+ // manual configs whose answers are fixed by their own timeZone — no
115
+ // dependence on this machine's zone.
116
+ const at = new Date(Date.UTC(2026, 6, 1, 12, 0, 0)); // July 1, 12:00Z
117
+ const manual = (timeZone: string) =>
118
+ JSON.stringify({ timeZone, hemisphere: "north" });
119
+ const storeFor = (timeZone: string) => ({
120
+ "hikari-solar-strategy": "manual",
121
+ "hikari-solar-manual": manual(timeZone),
122
+ });
123
+ const asBootStorage = (m: Record<string, string>) => ({
124
+ getItem: (k: string) => (k in m ? m[k]! : null),
125
+ });
126
+
127
+ // Greenwich meridian at July noon: the sun is high -> light.
128
+ const utcStore = storeFor("UTC");
129
+ const utc = runBoot(js, { now: at, storage: utcStore });
130
+ expect(utc.mode, "UTC (lng 0) at July noon is DAY").toBe("light");
131
+ expect(utc.mode, "module and asset agree on the manual path").toBe(
132
+ resolveSystemModeAt(at, asBootStorage(utcStore)),
133
+ );
134
+
135
+ // Auckland's standard meridian is 180 degrees away: the same instant is
136
+ // local midnight there -> night. Machine-independent by construction
137
+ // (both configs pin lat AND lng), so this cannot pass vacuously.
138
+ const aklStore = storeFor("Pacific/Auckland");
139
+ const akl = runBoot(js, { now: at, storage: aklStore });
140
+ expect(akl.mode, "Auckland (lng 180) at the same instant is NIGHT").toBe("dark");
141
+ expect(akl.mode, "module and asset agree on the far meridian").toBe(
142
+ resolveSystemModeAt(at, asBootStorage(aklStore)),
143
+ );
144
+ expect(utc.mode, "the two configs really do differ").not.toBe(akl.mode);
145
+ });
146
+ });
147
+
@@ -0,0 +1,188 @@
1
+ import { readStorageItem } from "./safeStorage";
2
+ import {
3
+ DEFAULT_GEO_LOCATION,
4
+ isKnownTimeZone,
5
+ manualLocationOf,
6
+ solarAltitude,
7
+ sunEquatorialCoordinates,
8
+ greenwichSiderealTime,
9
+ toJulianDate,
10
+ zoneOffsetMinutes,
11
+ SOLAR_LOCATION_STRATEGY_STORAGE_KEY,
12
+ SOLAR_MANUAL_LOCATION_STORAGE_KEY,
13
+ type SolarLocationStrategy,
14
+ type SolarManualLocation,
15
+ } from "./useSolarTime";
16
+
17
+ /**
18
+ * The PRE-PAINT theme resolver and its shipped boot asset (hikari#1546
19
+ * Phase 1.5, user direction 2026-11-25: 一整套统一 — one resolution
20
+ * executed on BOTH sides of hydration).
21
+ *
22
+ * `resolveSystemModeAt` runs the solar chain's SYNC path exactly as the
23
+ * reactive runtime resolves mode "system": manual config (when the stored
24
+ * strategy selects it and the payload validates) → the timezone estimate
25
+ * (stock default latitude + UTC-offset longitude) → solar altitude →
26
+ * day → light, else dark. Dependency-free by design (safeStorage only —
27
+ * no vue, no cronBus) so it can ride the pre-paint asset.
28
+ *
29
+ * Two documented divergences from the reactive runtime, both narrow:
30
+ * - strategy "ip": the runtime may improve the coords via a
31
+ * granted-browser-geolocation / IP cascade (async, networked). The boot
32
+ * asset cannot — it uses the timezone estimate. The runtime's answer
33
+ * lands with the bundle and self-heals.
34
+ * - stale stored values: the runtime's readers also REMOVE bad payloads;
35
+ * the boot asset is read-only (pre-paint storage writes would be a
36
+ * surprise) and falls back instead. Removal happens at initTheme.
37
+ *
38
+ * `buildThemeBootJs()` ships the chain as a dependency-free IIFE for
39
+ * consumers to inline in `<head>` (lagrange interpolates it with a `?raw`
40
+ * import). The math is serialized via `Function.prototype.toString` from
41
+ * useSolarTime's OWN definitions — the asset cannot drift from the
42
+ * runtime's solar chain by construction; `themeBoot.contract.test.ts`
43
+ * executes the emitted asset against `resolveSystemModeAt` across a date
44
+ * grid to pin the wrapper (storage reads + attribute writes) instead.
45
+ */
46
+
47
+ const DEG = Math.PI / 180;
48
+ const RAD = 180 / Math.PI;
49
+
50
+ /** A read-only storage surface — the seam that lets the contract test feed
51
+ * the resolver the SAME values the emitted asset reads (a test runner may
52
+ * have no `localStorage` at all, and comparing against the environment's
53
+ * storage made the parity assertion machine-dependent: review round 2). */
54
+ export interface BootStorage {
55
+ getItem(key: string): string | null;
56
+ }
57
+
58
+ /** One strategy branch only: manual config or the offline estimate. The
59
+ * "ip" cascade is async and networked — never a pre-paint concern. */
60
+ function bootGeoLocation(
61
+ strategy: SolarLocationStrategy,
62
+ storage: BootStorage,
63
+ at: Date,
64
+ ): {
65
+ lat: number;
66
+ lng: number;
67
+ } {
68
+ if (strategy === "manual") {
69
+ const raw = storage.getItem(SOLAR_MANUAL_LOCATION_STORAGE_KEY);
70
+ if (raw) {
71
+ try {
72
+ const parsed: unknown = JSON.parse(raw);
73
+ if (
74
+ typeof parsed === "object" &&
75
+ parsed !== null &&
76
+ "timeZone" in parsed &&
77
+ "hemisphere" in parsed &&
78
+ typeof (parsed as SolarManualLocation).timeZone === "string" &&
79
+ ((parsed as SolarManualLocation).hemisphere === "north" ||
80
+ (parsed as SolarManualLocation).hemisphere === "south") &&
81
+ isKnownTimeZone((parsed as SolarManualLocation).timeZone)
82
+ ) {
83
+ return manualLocationOf(parsed as SolarManualLocation);
84
+ }
85
+ } catch {
86
+ // Corrupt payload — the estimate below is the offline answer.
87
+ }
88
+ }
89
+ }
90
+ // "timezone" (the default), manual-with-invalid-config, and "ip"-offline
91
+ // all land here: lat = the stock default, lng = the zone's center meridian
92
+ // derived from the UTC offset **at the resolved instant** — NOT at the wall
93
+ // clock. Same value when resolving "now" (the only real caller), and it
94
+ // removes the last host-and-season dependence from the parity test (a
95
+ // grid instant in another DST season would otherwise shift the meridian by
96
+ // up to 15° against the asset's NOW-based offset).
97
+ const offsetMin = -at.getTimezoneOffset();
98
+ return { lat: DEFAULT_GEO_LOCATION.lat, lng: offsetMin / 4 };
99
+ }
100
+
101
+ /** The runtime contract, sync path: mode "system" is light only while the
102
+ * sun is genuinely up (altitude > 6°); dusk and night are dark. */
103
+ export function resolveSystemModeAt(
104
+ date: Date = new Date(),
105
+ storage: BootStorage = { getItem: (k) => readStorageItem(k) },
106
+ ): "dark" | "light" {
107
+ let strategy: SolarLocationStrategy = "timezone";
108
+ const stored = storage.getItem(SOLAR_LOCATION_STRATEGY_STORAGE_KEY);
109
+ if (stored === "timezone" || stored === "ip" || stored === "manual") {
110
+ strategy = stored;
111
+ }
112
+ const geo = bootGeoLocation(strategy, storage, date);
113
+ const alt = solarAltitude(geo.lat, geo.lng, date);
114
+ return alt > 6 ? "light" : "dark";
115
+ }
116
+
117
+ /** Serialize the boot IIFE. The math is emitted from useSolarTime's own
118
+ * function sources (toString) plus the two constants they close over —
119
+ * emitted BEFORE the functions, so the copy executes exactly what the
120
+ * runtime executes. */
121
+ export function buildThemeBootJs(): string {
122
+ const constBlock = [
123
+ `var DEG = ${DEG};`,
124
+ `var RAD = ${RAD};`,
125
+ `var DEFAULT_GEO_LOCATION = ${JSON.stringify(DEFAULT_GEO_LOCATION)};`,
126
+ ].join("\n");
127
+ const serialized = [
128
+ toJulianDate,
129
+ greenwichSiderealTime,
130
+ sunEquatorialCoordinates,
131
+ solarAltitude,
132
+ zoneOffsetMinutes,
133
+ manualLocationOf,
134
+ ]
135
+ .map((fn) => `var ${fn.name} = ${fn.toString()};`)
136
+ .join("\n");
137
+ const wrapper = `try {
138
+ var d = document.documentElement;
139
+ var read = function (k) { try { return localStorage.getItem(k); } catch (e) { return null; } };
140
+ var t = read("hikari-theme");
141
+ var m = read("hikari-theme-mode");
142
+ var strategy = read("${SOLAR_LOCATION_STRATEGY_STORAGE_KEY}");
143
+ if (strategy !== "timezone" && strategy !== "ip" && strategy !== "manual") strategy = "timezone";
144
+ var NOW = (typeof __hikariBootNow !== "undefined" && __hikariBootNow) ? new Date(__hikariBootNow) : new Date();
145
+ var geo = { lat: DEFAULT_GEO_LOCATION.lat, lng: -NOW.getTimezoneOffset() / 4 };
146
+ if (strategy === "manual") {
147
+ try {
148
+ var raw = read("${SOLAR_MANUAL_LOCATION_STORAGE_KEY}");
149
+ if (raw) {
150
+ var cfg = JSON.parse(raw);
151
+ var ok = cfg && typeof cfg === "object" && typeof cfg.timeZone === "string" &&
152
+ (cfg.hemisphere === "north" || cfg.hemisphere === "south");
153
+ if (ok) {
154
+ try { new Intl.DateTimeFormat("en-US", { timeZone: cfg.timeZone }); }
155
+ catch (e) { ok = false; }
156
+ }
157
+ if (ok) geo = manualLocationOf(cfg);
158
+ }
159
+ } catch (e) {}
160
+ }
161
+ var alt = solarAltitude(geo.lat, geo.lng, NOW);
162
+ if (!(m === "light" || m === "dark")) {
163
+ m = alt > 6 ? "light" : "dark";
164
+ }
165
+ d.setAttribute("data-theme", t || (typeof window !== "undefined" && window.__celestiaDefaultTheme) || "default");
166
+ d.setAttribute("data-mode", m);
167
+ } catch (e) {}`;
168
+ return `/* GENERATED by packages/vue/src/theme/themeBoot.ts (buildThemeBootJs) —
169
+ * do not edit by hand. The math functions are serialized from useSolarTime's
170
+ * own definitions via toString(), so this asset cannot drift from the
171
+ * runtime's solar chain by construction; the wrapper (storage reads +
172
+ * attribute writes) is pinned by themeBoot.contract.test.ts. Inline in
173
+ * <head> BEFORE the theme-vars sheet's first paint.
174
+ *
175
+ * SYNTAX FLOOR: ES2020 (const/let, arrow functions, optional chaining).
176
+ * The asset is inlined RAW — no consumer build step transpiles it — so it
177
+ * targets the same floor the family's bundles do (vite target es2020).
178
+ * A browser older than that cannot run the app it belongs to either; it
179
+ * simply keeps its unthemed first paint. Keep this file free of syntax
180
+ * NEWER than ES2020: a parse error would void the whole inline script and
181
+ * the surrounding try/catch cannot recover from a parse failure. */
182
+ (function () {
183
+ ${constBlock}
184
+ ${serialized}
185
+ ${wrapper}
186
+ })();
187
+ `;
188
+ }
@@ -0,0 +1,65 @@
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 { buildThemeVarsCss } from "./themeVarsCss";
7
+
8
+ /**
9
+ * Drift contract for the PRE-RENDERED theme CSS (hikari#1546): the checked
10
+ * -in `src/styles/theme-vars.css` must be byte-identical to what
11
+ * `buildThemeVarsCss()` composes from the live preset table. When the
12
+ * table changes (new slot, adjusted color), the CSS MUST be regenerated in
13
+ * the same PR — otherwise a returning visitor's pre-hydration paint uses
14
+ * stale colors and the runtime injection visibly snaps them on mount.
15
+ *
16
+ * Regeneration (the preset table is TS, so the toolchain that can execute
17
+ * it IS this runner — the vue-mirror discipline):
18
+ *
19
+ * REGEN_THEME_VARS=1 \
20
+ * node_modules/.bin/vitest run src/theme/themeVarsCss.contract.test.ts
21
+ *
22
+ * The test executes the same composition any future generator would, so
23
+ * the writer and the checker cannot disagree.
24
+ */
25
+ const here = dirname(fileURLToPath(import.meta.url));
26
+ const cssPath = join(here, "..", "styles", "theme-vars.css");
27
+
28
+ describe("pre-rendered theme vars CSS (hikari#1546)", () => {
29
+ const css = buildThemeVarsCss();
30
+
31
+ it("matches the composition of the live preset table", () => {
32
+ const checkedIn = readFileSync(cssPath, "utf8");
33
+ if (checkedIn === css) return;
34
+ // Drift: the preset table moved without a regen. Rewrite ONLY under the
35
+ // explicit env (a stray REGEN_THEME_VARS in a normal run must not touch
36
+ // the worktree silently), then re-read for a real assertion — the write
37
+ // happens AFTER the drift is established, never before the compare.
38
+ // MUT:mut-regen-write-order — reverting to write-before-compare silences
39
+ // this test entirely (the round-1 review footgun).
40
+ if (process.env.REGEN_THEME_VARS === "1") {
41
+ writeFileSync(cssPath, css);
42
+ expect(readFileSync(cssPath, "utf8"), "regen wrote the composition").toBe(css);
43
+ console.log(`REGEN: rewrote drifted ${cssPath} (${css.length} bytes)`);
44
+ return;
45
+ }
46
+ expect(checkedIn).toBe(css);
47
+ });
48
+
49
+ it("covers both modes with the core color tokens", () => {
50
+ expect(css).toContain('html[data-mode="dark"]');
51
+ expect(css).toContain('html[data-mode="light"]');
52
+ // The slots with no per-component CSS fallback — a missing one leaves
53
+ // the unthemed flash hikari#1546 describes, so each is load-bearing.
54
+ for (const slot of [
55
+ "--color-primary",
56
+ "--color-text",
57
+ "--color-background",
58
+ "--color-surface",
59
+ "--color-muted",
60
+ "--color-border",
61
+ ]) {
62
+ expect(css, `${slot} must be pre-rendered`).toContain(`${slot}:`);
63
+ }
64
+ });
65
+ });
@@ -0,0 +1,56 @@
1
+ import { themePresets, tokensToCSSVars, getThemeTokens } from "./presets";
2
+
3
+ /**
4
+ * The PRE-RENDERED static form of the stock theme table (hikari#1546).
5
+ *
6
+ * `applyTheme()` injects the whole cssvar set from JS, which is why a
7
+ * phone's first paint used to flash the unthemed default: no JS, no vars.
8
+ * This module composes the SAME `tokensToCSSVars` output the runtime uses
9
+ * into plain CSS blocks keyed on the `data-mode` attribute — the SSR
10
+ * template ships it in `<head>`, and a tiny inline bootstrap only sets
11
+ * `data-theme`/`data-mode` (attribute writes, no computation) before body
12
+ * paint. The cascade picks the block instantly.
13
+ *
14
+ * Selectors are mode-keyed and deliberately NOT theme-keyed: a stored
15
+ * CUSTOM theme id cannot be pre-rendered (user-authored, lives in
16
+ * localStorage), so pre-hydration those users see the stock colors in the
17
+ * right MODE — strictly better than the previous unthemed flash — and
18
+ * `applyTheme()` replaces them the moment the bundle lands. Override
19
+ * mechanics: the runtime writes a managed `<style data-hikari-theme-vars>`
20
+ * block whose selector (`html:root`, 0-1-1) TIES with these `html[data-mode]`
21
+ * blocks — the runtime wins by head ORDER (its block is appended after the
22
+ * SSR sheet), so the static sheet must stay in the SSR head; a late/async
23
+ * -loaded copy would re-tie and could snap the theme back.
24
+ *
25
+ * Phase 2 (de-Vue): the table itself moves to the Rust palette crate
26
+ * (tairitsu lane) and this module consumes generated JSON — the CSS form
27
+ * and the bootstrap contract stay exactly as they are here.
28
+ *
29
+ * Group tokens (shape/radius) are intentionally NOT included: every
30
+ * component reads them with its own CSS fallback (e.g.
31
+ * `var(--hk-radius-sm, 4px)` in HkSkeleton, `var(--hk-z-*)`,
32
+ * `var(--hk-picker-*)`), so the pre-hydration window degrades to identical
33
+ * geometry, and the runtime emission covers them anyway.
34
+ */
35
+ const MODES = ["dark", "light"] as const;
36
+
37
+ export function buildThemeVarsCss(): string {
38
+ const preset = themePresets.default;
39
+ if (!preset) return "/* stock preset table is empty — nothing to pre-render */\n";
40
+ const chunks: string[] = [
41
+ "/* GENERATED by themeVarsCss.contract.test.ts (REGEN_THEME_VARS=1) —",
42
+ " * do not edit by hand. Source: the stock `default` preset in",
43
+ " * presets.ts; the regen command is in the contract test doc block. */",
44
+ ];
45
+ for (const mode of MODES) {
46
+ const tokens = getThemeTokens("default", mode);
47
+ if (!tokens) continue;
48
+ const vars = tokensToCSSVars(tokens);
49
+ chunks.push(`html[data-mode="${mode}"] {`);
50
+ for (const name of Object.keys(vars)) {
51
+ chunks.push(` ${name}: ${vars[name]};`);
52
+ }
53
+ chunks.push("}");
54
+ }
55
+ return chunks.join("\n") + "\n";
56
+ }
@@ -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;