singularity-core 0.5.2 → 0.9.0

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.
@@ -8,9 +8,10 @@ export function parsePage(label, schema, data) {
8
8
  const parsed = z
9
9
  .object({
10
10
  items: z.array(schema),
11
- total: z.number(),
12
- page: z.number(),
13
- take: z.number(),
11
+ total: z.number().int().min(0),
12
+ page: z.number().int().min(0),
13
+ // pageCount divides by it.
14
+ take: z.number().int().positive(),
14
15
  })
15
16
  .safeParse(data);
16
17
  if (!parsed.success) {
@@ -34,9 +35,11 @@ export function toListParams(query) {
34
35
  }
35
36
  /**
36
37
  * `?page=&search=` for server-paged lists. `page` is zero-based and omitted on
37
- * the first page; `search` filters the whole list on the API.
38
+ * the first page; `search` filters the whole list on the API. A value that
39
+ * does not fit (`?page=abc`, a hand-typed `?search=2026`, which the router
40
+ * reads as a number) is dropped instead of failing the route.
38
41
  */
39
42
  export const pageSearchSchema = z.object({
40
- page: z.number().int().min(0).optional(),
41
- search: z.string().optional(),
43
+ page: z.number().int().min(0).optional().catch(undefined),
44
+ search: z.string().optional().catch(undefined),
42
45
  });
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * Search box state for a server-searched list (see `pageSearchSchema`). Returns the text being typed and
3
3
  * its setter; once typing pauses, `apply` gets the trimmed text (undefined when
4
- * empty) so the route can put it in the URL and reload from the API.
4
+ * empty) so the route can put it in the URL and reload from the API. When
5
+ * `current` changes from outside (Back, a link that clears the search), the
6
+ * text follows it instead of being applied again.
5
7
  */
6
8
  export declare function useListSearch(current: string | undefined, apply: (search: string | undefined) => void): readonly [string, import("react").Dispatch<import("react").SetStateAction<string>>];
@@ -3,17 +3,30 @@ const SEARCH_DEBOUNCE_MS = 300;
3
3
  /**
4
4
  * Search box state for a server-searched list (see `pageSearchSchema`). Returns the text being typed and
5
5
  * its setter; once typing pauses, `apply` gets the trimmed text (undefined when
6
- * empty) so the route can put it in the URL and reload from the API.
6
+ * empty) so the route can put it in the URL and reload from the API. When
7
+ * `current` changes from outside (Back, a link that clears the search), the
8
+ * text follows it instead of being applied again.
7
9
  */
8
10
  export function useListSearch(current, apply) {
9
11
  const [text, setText] = useState(current ?? "");
10
12
  const applyRef = useRef(apply);
11
13
  applyRef.current = apply;
14
+ // The search this hook last applied, or last took from `current`.
15
+ const appliedRef = useRef(current);
16
+ useEffect(() => {
17
+ if (current === appliedRef.current)
18
+ return;
19
+ appliedRef.current = current;
20
+ setText(current ?? "");
21
+ }, [current]);
12
22
  useEffect(() => {
13
23
  const trimmed = text.trim() || undefined;
14
24
  if (trimmed === current)
15
25
  return;
16
- const timer = setTimeout(() => applyRef.current(trimmed), SEARCH_DEBOUNCE_MS);
26
+ const timer = setTimeout(() => {
27
+ appliedRef.current = trimmed;
28
+ applyRef.current(trimmed);
29
+ }, SEARCH_DEBOUNCE_MS);
17
30
  return () => clearTimeout(timer);
18
31
  }, [text, current]);
19
32
  return [text, setText];
@@ -0,0 +1,22 @@
1
+ import { type StaticDataRouteOption } from "@tanstack/react-router";
2
+ /**
3
+ * `staticData[key]` of the deepest matched route that sets it, so a layout
4
+ * route can act on what the page under it declares. The apps use it for the
5
+ * page shell: each route sets `staticData: { page: { width, flush } }` and
6
+ * the layout passes `useDeepestStaticData("page")` to its `GenericPage`.
7
+ *
8
+ * The key is typed by the app, which adds it to TanStack Router's
9
+ * `StaticDataRouteOption`:
10
+ *
11
+ * ```ts
12
+ * declare module "@tanstack/react-router" {
13
+ * interface StaticDataRouteOption {
14
+ * page?: PageShell;
15
+ * }
16
+ * }
17
+ * ```
18
+ *
19
+ * Static data is fixed per route. A value that depends on params or loader
20
+ * data (a breadcrumb with a post title) belongs in the loader or context.
21
+ */
22
+ export declare function useDeepestStaticData<K extends keyof StaticDataRouteOption>(key: K): StaticDataRouteOption[K] | undefined;
@@ -0,0 +1,30 @@
1
+ import { useMatches } from "@tanstack/react-router";
2
+ import { deepestStaticData } from "./static-data.js";
3
+ /**
4
+ * `staticData[key]` of the deepest matched route that sets it, so a layout
5
+ * route can act on what the page under it declares. The apps use it for the
6
+ * page shell: each route sets `staticData: { page: { width, flush } }` and
7
+ * the layout passes `useDeepestStaticData("page")` to its `GenericPage`.
8
+ *
9
+ * The key is typed by the app, which adds it to TanStack Router's
10
+ * `StaticDataRouteOption`:
11
+ *
12
+ * ```ts
13
+ * declare module "@tanstack/react-router" {
14
+ * interface StaticDataRouteOption {
15
+ * page?: PageShell;
16
+ * }
17
+ * }
18
+ * ```
19
+ *
20
+ * Static data is fixed per route. A value that depends on params or loader
21
+ * data (a breadcrumb with a post title) belongs in the loader or context.
22
+ */
23
+ export function useDeepestStaticData(key) {
24
+ // `useMatches` types its result with a conditional on the selected type,
25
+ // which stays unresolved while `K` is generic. The value is what `select`
26
+ // returns, so the cast only restates it.
27
+ return useMatches({
28
+ select: (matches) => deepestStaticData(matches, key),
29
+ });
30
+ }
@@ -0,0 +1,12 @@
1
+ import type { StaticDataRouteOption } from "@tanstack/react-router";
2
+ /** A route match, as far as its static data goes. */
3
+ type MatchWithStaticData = {
4
+ staticData: StaticDataRouteOption;
5
+ };
6
+ /**
7
+ * `staticData[key]` of the deepest match that sets it, or `undefined`.
8
+ * Matches run from the root route to the leaf, so a page's value wins over
9
+ * its layout's, and a layout's over the root's.
10
+ */
11
+ export declare function deepestStaticData<K extends keyof StaticDataRouteOption>(matches: readonly MatchWithStaticData[], key: K): StaticDataRouteOption[K] | undefined;
12
+ export {};
@@ -0,0 +1,14 @@
1
+ /**
2
+ * `staticData[key]` of the deepest match that sets it, or `undefined`.
3
+ * Matches run from the root route to the leaf, so a page's value wins over
4
+ * its layout's, and a layout's over the root's.
5
+ */
6
+ export function deepestStaticData(matches, key) {
7
+ for (let i = matches.length - 1; i >= 0; i--) {
8
+ const value = matches[i]?.staticData[key];
9
+ if (value !== undefined) {
10
+ return value;
11
+ }
12
+ }
13
+ return undefined;
14
+ }
@@ -18,7 +18,8 @@ export const nb = (fallback = false) => z
18
18
  export const na = (item, fallback = []) => z
19
19
  .array(item)
20
20
  .nullish()
21
- .transform((val) => val ?? fallback);
21
+ // A copy per parse, so no two results share (and mutate) one array.
22
+ .transform((val) => val ?? [...fallback]);
22
23
  export function buildSchema(fields) {
23
24
  return z.object(fields);
24
25
  }
@@ -9,18 +9,23 @@ export type SecurityTxtOptions = {
9
9
  };
10
10
  /** Plain-text security contact file per RFC 9116. Serve with `plainTextResponse`. */
11
11
  export declare function buildSecurityTxt({ contact, expires, canonical, preferredLanguages, }: SecurityTxtOptions): string;
12
- type CspDirective = "default-src" | "script-src" | "style-src" | "img-src" | "font-src" | "media-src" | "connect-src" | "frame-ancestors";
12
+ /** Directives an app can add sources to. */
13
+ type CspDirective = "default-src" | "script-src" | "style-src" | "img-src" | "font-src" | "media-src" | "connect-src" | "frame-src" | "worker-src" | "frame-ancestors";
13
14
  export type ContentSecurityPolicyOptions = {
14
15
  /** Per-request nonce; inline scripts must carry it. */
15
16
  nonce: string;
16
- /** Dev servers need inline and eval scripts for HMR. */
17
+ /**
18
+ * Dev servers need eval for HMR. Inline scripts still need the nonce there:
19
+ * browsers ignore `'unsafe-inline'` next to a nonce or `'strict-dynamic'`.
20
+ */
17
21
  dev: boolean;
18
22
  /** Sources added after the defaults, e.g. a font host for `font-src`. */
19
23
  extraSources?: Partial<Record<CspDirective, string[]>>;
20
24
  };
21
25
  /**
22
- * Content-Security-Policy header value. Production uses the nonce with
23
- * `strict-dynamic` (no unsafe-inline / unsafe-eval in script-src).
26
+ * Content-Security-Policy header value. Scripts need the nonce, or a nonced
27
+ * script that loads them (`strict-dynamic`); dev only adds `unsafe-eval`.
28
+ * Frames and workers come from this origin unless the app adds a source.
24
29
  */
25
30
  export declare function buildContentSecurityPolicy({ nonce, dev, extraSources, }: ContentSecurityPolicyOptions): string;
26
31
  /**
@@ -12,31 +12,43 @@ export function buildSecurityTxt({ contact, expires, canonical, preferredLanguag
12
12
  ].join("\n");
13
13
  }
14
14
  /**
15
- * Content-Security-Policy header value. Production uses the nonce with
16
- * `strict-dynamic` (no unsafe-inline / unsafe-eval in script-src).
15
+ * Directives no app extends: no `<base>` pointing relative URLs elsewhere, no
16
+ * plugins, and forms post only to this origin.
17
+ */
18
+ const FIXED_DIRECTIVES = [
19
+ "base-uri 'self'",
20
+ "object-src 'none'",
21
+ "form-action 'self'",
22
+ ];
23
+ /**
24
+ * Content-Security-Policy header value. Scripts need the nonce, or a nonced
25
+ * script that loads them (`strict-dynamic`); dev only adds `unsafe-eval`.
26
+ * Frames and workers come from this origin unless the app adds a source.
17
27
  */
18
28
  export function buildContentSecurityPolicy({ nonce, dev, extraSources = {}, }) {
19
29
  const directives = {
20
30
  "default-src": ["'self'"],
21
- "script-src": dev
22
- ? [
23
- "'self'",
24
- "'unsafe-inline'",
25
- "'unsafe-eval'",
26
- "'strict-dynamic'",
27
- `'nonce-${nonce}'`,
28
- ]
29
- : ["'self'", "'strict-dynamic'", `'nonce-${nonce}'`],
31
+ "script-src": [
32
+ "'self'",
33
+ ...(dev ? ["'unsafe-eval'"] : []),
34
+ "'strict-dynamic'",
35
+ `'nonce-${nonce}'`,
36
+ ],
30
37
  "style-src": ["'self'", "'unsafe-inline'"],
31
38
  "img-src": ["'self'", "data:", "blob:", "https:"],
32
39
  "font-src": ["'self'", "data:"],
33
40
  "media-src": ["'self'"],
34
41
  "connect-src": ["'self'", "https:"],
42
+ "frame-src": ["'self'"],
43
+ // Set, so workers do not fall back to script-src and its
44
+ // 'strict-dynamic' rules: this origin, plus what the app adds.
45
+ "worker-src": ["'self'"],
35
46
  "frame-ancestors": ["'self'"],
36
47
  };
37
- return Object.entries(directives)
38
- .map(([name, sources]) => [name, ...sources, ...(extraSources[name] ?? [])].join(" "))
39
- .join("; ");
48
+ return [
49
+ ...Object.entries(directives).map(([name, sources]) => [name, ...sources, ...(extraSources[name] ?? [])].join(" ")),
50
+ ...FIXED_DIRECTIVES,
51
+ ].join("; ");
40
52
  }
41
53
  /**
42
54
  * Response headers every page should send: HSTS, framing, sniffing, referrer
@@ -10,6 +10,21 @@ export type ThemeContext = {
10
10
  theme: Theme;
11
11
  isDark: boolean;
12
12
  };
13
+ /**
14
+ * Whether a `system` preference shows dark while the OS preference is
15
+ * unknown: on the server without the client hint, and in `ThemeProvider`
16
+ * before mount. One value for both, so the server's markup and the first
17
+ * client render agree. The bootstrap script corrects the page before paint.
18
+ */
19
+ export declare const SYSTEM_DARK_WHEN_UNKNOWN = false;
20
+ /**
21
+ * Response headers asking the browser to send `Sec-CH-Prefers-Color-Scheme`
22
+ * on later requests, so `getThemeContext` can render a `system` preference
23
+ * on the server. Chromium browsers send it; others, and every first visit
24
+ * (no `Critical-CH`, which would cost a retried request), fall back to
25
+ * `SYSTEM_DARK_WHEN_UNKNOWN`. Spread into the root route's `headers`.
26
+ */
27
+ export declare function themeClientHintHeaders(): Record<string, string>;
13
28
  /**
14
29
  * Resolves whether dark mode should be active for a preference and OS hint.
15
30
  */
@@ -29,6 +44,8 @@ export declare function applyDarkClass(isDark: boolean): void;
29
44
  /**
30
45
  * Inline script for first paint when preference is `system` (or legacy localStorage-only).
31
46
  * `storageKey` is both the localStorage key and the cookie name unless
32
- * `cookieKey` is given. Logic must stay aligned with {@link resolveIsDark}.
47
+ * `cookieKey` is given. Any text works as a key: both are quoted, and the
48
+ * cookie name is matched literally. Blocked storage falls back to the cookie.
49
+ * Logic must stay aligned with {@link resolveIsDark}.
33
50
  */
34
51
  export declare function buildThemeBootstrapScript(storageKey: string, cookieKey?: string): string;
@@ -1,5 +1,23 @@
1
1
  import { z } from "zod";
2
2
  export const ThemeSchema = z.enum(["dark", "light", "system"]);
3
+ /**
4
+ * Whether a `system` preference shows dark while the OS preference is
5
+ * unknown: on the server without the client hint, and in `ThemeProvider`
6
+ * before mount. One value for both, so the server's markup and the first
7
+ * client render agree. The bootstrap script corrects the page before paint.
8
+ */
9
+ export const SYSTEM_DARK_WHEN_UNKNOWN = false;
10
+ const COLOR_SCHEME_HINT = "Sec-CH-Prefers-Color-Scheme";
11
+ /**
12
+ * Response headers asking the browser to send `Sec-CH-Prefers-Color-Scheme`
13
+ * on later requests, so `getThemeContext` can render a `system` preference
14
+ * on the server. Chromium browsers send it; others, and every first visit
15
+ * (no `Critical-CH`, which would cost a retried request), fall back to
16
+ * `SYSTEM_DARK_WHEN_UNKNOWN`. Spread into the root route's `headers`.
17
+ */
18
+ export function themeClientHintHeaders() {
19
+ return { "Accept-CH": COLOR_SCHEME_HINT, Vary: COLOR_SCHEME_HINT };
20
+ }
3
21
  /**
4
22
  * Resolves whether dark mode should be active for a preference and OS hint.
5
23
  */
@@ -36,11 +54,26 @@ export function applyDarkClass(isDark) {
36
54
  root.classList.remove("dark");
37
55
  }
38
56
  }
57
+ /**
58
+ * A JS string literal for an inline `<script>`: JSON-quoted, with `<`
59
+ * escaped so the text can never close the script tag.
60
+ */
61
+ function scriptString(text) {
62
+ return JSON.stringify(text).replaceAll("<", "\\u003c");
63
+ }
64
+ /** `text` matched literally inside a RegExp. */
65
+ function escapeRegExp(text) {
66
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
67
+ }
39
68
  /**
40
69
  * Inline script for first paint when preference is `system` (or legacy localStorage-only).
41
70
  * `storageKey` is both the localStorage key and the cookie name unless
42
- * `cookieKey` is given. Logic must stay aligned with {@link resolveIsDark}.
71
+ * `cookieKey` is given. Any text works as a key: both are quoted, and the
72
+ * cookie name is matched literally. Blocked storage falls back to the cookie.
73
+ * Logic must stay aligned with {@link resolveIsDark}.
43
74
  */
44
75
  export function buildThemeBootstrapScript(storageKey, cookieKey = storageKey) {
45
- return `(function(){try{var k='${storageKey}',c='${cookieKey}';var t=localStorage.getItem(k);if(!t){var m=document.cookie.match(new RegExp('(?:^|; )'+c+'=([^;]*)'));t=m?decodeURIComponent(m[1]):null}var p=(!t||t==='system')&&window.matchMedia('(prefers-color-scheme: dark)').matches;var d=t==='dark'||p;if(d)document.documentElement.classList.add('dark');else document.documentElement.classList.remove('dark')}catch(e){}})();`;
76
+ const k = scriptString(storageKey);
77
+ const cookiePattern = scriptString(`(?:^|; )${escapeRegExp(cookieKey)}=([^;]*)`);
78
+ return `(function(){try{var t=null;try{t=localStorage.getItem(${k})}catch(e){}if(!t){var m=document.cookie.match(new RegExp(${cookiePattern}));t=m?decodeURIComponent(m[1]):null}var p=(!t||t==='system')&&window.matchMedia('(prefers-color-scheme: dark)').matches;var d=t==='dark'||p;if(d)document.documentElement.classList.add('dark');else document.documentElement.classList.remove('dark')}catch(e){}})();`;
46
79
  }
@@ -3,6 +3,12 @@ import { type Theme } from "./index.js";
3
3
  type ThemeProviderProps = {
4
4
  children: React.ReactNode;
5
5
  initialTheme: Theme;
6
+ /**
7
+ * What the server showed (`ThemeContext.isDark`), kept until mount so the
8
+ * first client render matches it. Defaults to `SYSTEM_DARK_WHEN_UNKNOWN`
9
+ * for a `system` preference, the server's own guess without the hint.
10
+ */
11
+ initialIsDark?: boolean;
6
12
  /** localStorage key; use the same name as the theme cookie. */
7
13
  storageKey: string;
8
14
  /** Saves the preference for SSR, normally a server function setting the cookie. */
@@ -10,15 +16,27 @@ type ThemeProviderProps = {
10
16
  onResolvedIsDarkChange?: (isDark: boolean) => void;
11
17
  };
12
18
  type ThemeProviderState = {
19
+ /** The preference: light, dark or system. */
13
20
  theme: Theme;
21
+ /** Saves a preference (localStorage + `persistTheme`) and applies it. */
14
22
  setTheme: (theme: Theme) => void;
23
+ /** Switches to the opposite of what is shown, saved as an explicit preference. */
24
+ toggleTheme: () => void;
25
+ /**
26
+ * What is shown. Before mount a `system` preference reads as the server
27
+ * showed it (`initialIsDark`), since only the browser knows the OS
28
+ * preference.
29
+ */
30
+ resolvedTheme: "light" | "dark";
31
+ /** False on the server and the first client render, so their markup matches. */
32
+ mounted: boolean;
15
33
  };
16
34
  /**
17
35
  * Manages theme preference (localStorage + cookie) and syncs the `dark` class on `<html>`.
18
36
  */
19
- export declare function ThemeProvider({ children, initialTheme, storageKey, persistTheme, onResolvedIsDarkChange, }: ThemeProviderProps): React.JSX.Element;
37
+ export declare function ThemeProvider({ children, initialTheme, initialIsDark, storageKey, persistTheme, onResolvedIsDarkChange, }: ThemeProviderProps): React.JSX.Element;
20
38
  /**
21
- * Hook to access the current theme and setTheme function.
39
+ * Hook to access the theme preference, the theme shown, and the setters.
22
40
  */
23
41
  export declare const useTheme: () => ThemeProviderState;
24
42
  export {};
@@ -1,24 +1,70 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import * as React from "react";
3
- import { applyDarkClass, resolveIsDark, ThemeSchema, } from "./index.js";
3
+ import { applyDarkClass, resolveIsDark, SYSTEM_DARK_WHEN_UNKNOWN, ThemeSchema, } from "./index.js";
4
4
  const initialState = {
5
5
  theme: "system",
6
6
  setTheme: () => null,
7
+ toggleTheme: () => null,
8
+ resolvedTheme: SYSTEM_DARK_WHEN_UNKNOWN ? "dark" : "light",
9
+ mounted: false,
7
10
  };
8
- const ThemeProviderContext = React.createContext(initialState);
11
+ /**
12
+ * One context for every copy of this module. TanStack Start bundles this
13
+ * package into the app's server code (it peers on `@tanstack/react-start`)
14
+ * but bundles `singularity-components`, whose header reads this context,
15
+ * separately with its own copy of this file. A context per copy would leave
16
+ * the server-rendered header outside the app's `ThemeProvider`.
17
+ */
18
+ function sharedThemeContext() {
19
+ const key = Symbol.for("singularity-core/theme/react");
20
+ const registry = globalThis;
21
+ const existing = registry[key];
22
+ if (existing) {
23
+ return existing;
24
+ }
25
+ const context = React.createContext(initialState);
26
+ registry[key] = context;
27
+ return context;
28
+ }
29
+ const ThemeProviderContext = sharedThemeContext();
30
+ const PREFERS_DARK_QUERY = "(prefers-color-scheme: dark)";
9
31
  function getSystemPrefersDark() {
10
- return window.matchMedia("(prefers-color-scheme: dark)").matches;
32
+ return window.matchMedia(PREFERS_DARK_QUERY).matches;
33
+ }
34
+ /** The stored preference, or null when storage is empty or blocked (private mode, disabled site data). */
35
+ function readStoredTheme(storageKey) {
36
+ try {
37
+ return localStorage.getItem(storageKey);
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
43
+ /** Stores the preference when storage allows; the cookie from `persistTheme` carries it either way. */
44
+ function storeTheme(storageKey, theme) {
45
+ try {
46
+ localStorage.setItem(storageKey, theme);
47
+ }
48
+ catch {
49
+ // Blocked or full.
50
+ }
11
51
  }
12
52
  /**
13
53
  * Manages theme preference (localStorage + cookie) and syncs the `dark` class on `<html>`.
14
54
  */
15
- export function ThemeProvider({ children, initialTheme, storageKey, persistTheme, onResolvedIsDarkChange, }) {
55
+ export function ThemeProvider({ children, initialTheme, initialIsDark = SYSTEM_DARK_WHEN_UNKNOWN, storageKey, persistTheme, onResolvedIsDarkChange, }) {
16
56
  const [theme, setThemeState] = React.useState(initialTheme);
17
- // Latest callback without re-running the effects below when it changes.
57
+ // The OS preference; undefined until mounted.
58
+ const [systemPrefersDark, setSystemPrefersDark] = React.useState(undefined);
59
+ const mounted = systemPrefersDark !== undefined;
60
+ const isDark = resolveIsDark(theme, systemPrefersDark ?? initialIsDark);
61
+ // Latest callbacks without re-running the effects below when they change.
18
62
  const persistRef = React.useRef(persistTheme);
19
63
  persistRef.current = persistTheme;
64
+ const onResolvedIsDarkChangeRef = React.useRef(onResolvedIsDarkChange);
65
+ onResolvedIsDarkChangeRef.current = onResolvedIsDarkChange;
20
66
  React.useEffect(() => {
21
- const storedTheme = localStorage.getItem(storageKey);
67
+ const storedTheme = readStoredTheme(storageKey);
22
68
  if (!storedTheme) {
23
69
  return;
24
70
  }
@@ -28,34 +74,39 @@ export function ThemeProvider({ children, initialTheme, storageKey, persistTheme
28
74
  void persistRef.current(parsed.data);
29
75
  }
30
76
  }, [storageKey, initialTheme]);
31
- const applyResolvedTheme = React.useCallback((nextTheme) => {
32
- const isDark = resolveIsDark(nextTheme, getSystemPrefersDark());
33
- applyDarkClass(isDark);
34
- onResolvedIsDarkChange?.(isDark);
35
- }, [onResolvedIsDarkChange]);
36
77
  React.useEffect(() => {
37
- applyResolvedTheme(theme);
38
- }, [theme, applyResolvedTheme]);
78
+ const media = window.matchMedia(PREFERS_DARK_QUERY);
79
+ const onChange = () => setSystemPrefersDark(media.matches);
80
+ onChange();
81
+ media.addEventListener("change", onChange);
82
+ return () => media.removeEventListener("change", onChange);
83
+ }, []);
84
+ // Until mount, the class is the one the server or the bootstrap script set.
39
85
  React.useEffect(() => {
40
- if (theme !== "system") {
86
+ if (!mounted) {
41
87
  return;
42
88
  }
43
- const media = window.matchMedia("(prefers-color-scheme: dark)");
44
- const onChange = () => applyResolvedTheme("system");
45
- media.addEventListener("change", onChange);
46
- return () => media.removeEventListener("change", onChange);
47
- }, [theme, applyResolvedTheme]);
48
- const value = React.useMemo(() => ({
49
- theme,
50
- setTheme: (newTheme) => {
51
- localStorage.setItem(storageKey, newTheme);
89
+ applyDarkClass(isDark);
90
+ onResolvedIsDarkChangeRef.current?.(isDark);
91
+ }, [mounted, isDark]);
92
+ const value = React.useMemo(() => {
93
+ const setTheme = (newTheme) => {
94
+ storeTheme(storageKey, newTheme);
52
95
  void persistRef.current(newTheme);
53
96
  setThemeState(newTheme);
54
- },
55
- }), [theme, storageKey]);
97
+ };
98
+ return {
99
+ theme,
100
+ setTheme,
101
+ // Reads the OS preference now, in case it is clicked before mount.
102
+ toggleTheme: () => setTheme(resolveIsDark(theme, getSystemPrefersDark()) ? "light" : "dark"),
103
+ resolvedTheme: isDark ? "dark" : "light",
104
+ mounted,
105
+ };
106
+ }, [theme, storageKey, isDark, mounted]);
56
107
  return (_jsx(ThemeProviderContext.Provider, { value: value, children: children }));
57
108
  }
58
109
  /**
59
- * Hook to access the current theme and setTheme function.
110
+ * Hook to access the theme preference, the theme shown, and the setters.
60
111
  */
61
112
  export const useTheme = () => React.useContext(ThemeProviderContext);
@@ -1,7 +1,9 @@
1
1
  import { type Theme, type ThemeContext } from "./index.js";
2
2
  /**
3
3
  * Reads theme preference from the `cookieName` cookie and resolves dark mode
4
- * for SSR. Uses `Sec-CH-Prefers-Color-Scheme` when preference is `system`.
4
+ * for SSR. For a `system` preference it uses `Sec-CH-Prefers-Color-Scheme`,
5
+ * which browsers only send once the app asks with `themeClientHintHeaders()`;
6
+ * without it, `SYSTEM_DARK_WHEN_UNKNOWN`.
5
7
  */
6
8
  export declare function getThemeContext(cookieName: string): ThemeContext;
7
9
  /**
@@ -1,15 +1,21 @@
1
1
  import { getCookie, getRequestHeader, setCookie, } from "@tanstack/react-start/server";
2
- import { resolveIsDark, ThemeSchema, } from "./index.js";
2
+ import { resolveIsDark, SYSTEM_DARK_WHEN_UNKNOWN, ThemeSchema, } from "./index.js";
3
3
  /**
4
4
  * Reads theme preference from the `cookieName` cookie and resolves dark mode
5
- * for SSR. Uses `Sec-CH-Prefers-Color-Scheme` when preference is `system`.
5
+ * for SSR. For a `system` preference it uses `Sec-CH-Prefers-Color-Scheme`,
6
+ * which browsers only send once the app asks with `themeClientHintHeaders()`;
7
+ * without it, `SYSTEM_DARK_WHEN_UNKNOWN`.
6
8
  */
7
9
  export function getThemeContext(cookieName) {
8
10
  const raw = getCookie(cookieName);
9
11
  const parsed = ThemeSchema.safeParse(raw);
10
12
  const theme = parsed.success ? parsed.data : "system";
11
- const prefersColorScheme = getRequestHeader("sec-ch-prefers-color-scheme");
12
- const prefersDark = prefersColorScheme?.toLowerCase() === "dark";
13
+ // A structured-header string: `"dark"` or `"light"`, quotes included.
14
+ const hint = getRequestHeader("sec-ch-prefers-color-scheme")
15
+ ?.replaceAll('"', "")
16
+ .trim()
17
+ .toLowerCase();
18
+ const prefersDark = hint ? hint === "dark" : SYSTEM_DARK_WHEN_UNKNOWN;
13
19
  const isDark = resolveIsDark(theme, prefersDark);
14
20
  return { theme, isDark };
15
21
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "singularity-core",
3
- "version": "0.5.2",
4
- "description": "Shared non-UI code for Singularity TanStack Start apps: auth sessions, API client middleware, API schemas, paging, images, formatting, theme, SEO, security headers and telemetry.",
3
+ "version": "0.9.0",
4
+ "description": "Shared non-UI code for Singularity TanStack Start apps: auth sessions, API client middleware, API schemas, paging, route data, images, formatting, HTTP helpers, theme, cookie notice, SEO, security headers and telemetry.",
5
5
  "type": "module",
6
6
  "author": "Filip",
7
7
  "license": "MIT",
@@ -10,7 +10,7 @@
10
10
  ],
11
11
  "sideEffects": false,
12
12
  "engines": {
13
- "node": ">=25.0.0 <26.0.0",
13
+ "node": ">=26.0.0 <27.0.0",
14
14
  "pnpm": ">=12.0.0 <13.0.0"
15
15
  },
16
16
  "exports": {
@@ -38,6 +38,14 @@
38
38
  "types": "./dist/paging/react.d.ts",
39
39
  "import": "./dist/paging/react.js"
40
40
  },
41
+ "./router/react": {
42
+ "types": "./dist/router/react.d.ts",
43
+ "import": "./dist/router/react.js"
44
+ },
45
+ "./cookie-notice/server": {
46
+ "types": "./dist/cookie-notice/server.d.ts",
47
+ "import": "./dist/cookie-notice/server.js"
48
+ },
41
49
  "./theme": {
42
50
  "types": "./dist/theme/index.d.ts",
43
51
  "import": "./dist/theme/index.js"
@@ -77,9 +85,11 @@
77
85
  "./http": {
78
86
  "types": "./dist/http/index.d.ts",
79
87
  "import": "./dist/http/index.js"
80
- }
88
+ },
89
+ "./package.json": "./package.json"
81
90
  },
82
91
  "peerDependencies": {
92
+ "@tanstack/react-router": "^1.170.0",
83
93
  "@tanstack/react-start": "^1.168.0",
84
94
  "jose": "^6.0.0",
85
95
  "openapi-fetch": "^0.17.0",
@@ -87,6 +97,9 @@
87
97
  "zod": "^4.0.0"
88
98
  },
89
99
  "peerDependenciesMeta": {
100
+ "@tanstack/react-router": {
101
+ "optional": true
102
+ },
90
103
  "@tanstack/react-start": {
91
104
  "optional": true
92
105
  },
@@ -102,23 +115,30 @@
102
115
  },
103
116
  "devDependencies": {
104
117
  "@biomejs/biome": "2.5.15",
118
+ "@tanstack/react-router": "1.170.42",
105
119
  "@tanstack/react-start": "1.168.61",
106
- "@types/node": "25.9.5",
120
+ "@types/node": "26.6.5",
107
121
  "@types/react": "19.3.0",
122
+ "@types/react-dom": "19.3.0",
123
+ "happy-dom": "20.11.13",
108
124
  "jose": "6.2.12",
109
125
  "openapi-fetch": "0.17.0",
110
126
  "openapi-typescript": "7.13.0",
111
127
  "react": "19.3.0",
128
+ "react-dom": "19.3.0",
112
129
  "typescript": "6.0.3",
113
130
  "vitest": "5.0.3",
114
131
  "zod": "4.6.5"
115
132
  },
116
133
  "scripts": {
117
- "build": "tsc -p tsconfig.build.json",
134
+ "build": "node -e \"fs.rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json",
118
135
  "typecheck": "tsc --noEmit",
119
136
  "test": "vitest run",
120
137
  "test:watch": "vitest",
121
138
  "openapi-dev-types": "openapi-typescript http://localhost:5268/swagger/v1/swagger.json -o ./src/api/v1.ts --alphabetize --default-non-nullable --enum-values",
139
+ "openapi-types": "openapi-typescript https://api.filion.se/swagger/v1/swagger.json -o ./src/api/v1.ts --alphabetize --default-non-nullable --enum-values",
140
+ "check": "biome check",
141
+ "verify": "pnpm run typecheck && pnpm run check && pnpm run test",
122
142
  "biome:check": "biome check --write",
123
143
  "biome:lint": "biome lint --fix",
124
144
  "biome:format": "biome format --write"