singularity-core 0.6.0 → 0.14.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.
- package/README.md +74 -3
- package/config/biome-app.json +53 -0
- package/dist/api/server.d.ts +1 -1
- package/dist/api/server.js +14 -7
- package/dist/api/v1.d.ts +232 -113
- package/dist/api/v1.js +2 -1
- package/dist/auth/roles.d.ts +12 -5
- package/dist/auth/roles.js +15 -12
- package/dist/auth/server.d.ts +16 -6
- package/dist/auth/server.js +97 -20
- package/dist/cookie-notice/server.d.ts +11 -0
- package/dist/cookie-notice/server.js +21 -0
- package/dist/format/index.d.ts +11 -4
- package/dist/format/index.js +52 -28
- package/dist/http/index.d.ts +2 -0
- package/dist/http/index.js +6 -0
- package/dist/images/index.d.ts +4 -3
- package/dist/images/index.js +26 -10
- package/dist/paging/index.d.ts +18 -3
- package/dist/paging/index.js +22 -6
- package/dist/paging/react.d.ts +3 -1
- package/dist/paging/react.js +15 -2
- package/dist/schema/index.js +2 -1
- package/dist/security/index.d.ts +9 -4
- package/dist/security/index.js +26 -14
- package/dist/seo/index.d.ts +6 -0
- package/dist/seo/index.js +21 -0
- package/dist/theme/index.d.ts +18 -1
- package/dist/theme/index.js +35 -2
- package/dist/theme/react.d.ts +20 -2
- package/dist/theme/react.js +77 -26
- package/dist/theme/server.d.ts +3 -1
- package/dist/theme/server.js +10 -4
- package/package.json +148 -136
package/dist/paging/index.js
CHANGED
|
@@ -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
|
-
|
|
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) {
|
|
@@ -32,11 +33,26 @@ export function pageCount(page) {
|
|
|
32
33
|
export function toListParams(query) {
|
|
33
34
|
return { Page: query.page, Take: query.take, Search: query.search };
|
|
34
35
|
}
|
|
36
|
+
/**
|
|
37
|
+
* A `ListQuery` as a server function validator: `page` and `take` are int32,
|
|
38
|
+
* and `take` stops at the API's largest page. Unknown keys are stripped.
|
|
39
|
+
*/
|
|
40
|
+
export const ListQuerySchema = z.object({
|
|
41
|
+
page: z.int32().min(0).optional(),
|
|
42
|
+
take: z.int32().min(1).max(MAX_PAGE_TAKE).optional(),
|
|
43
|
+
search: z.string().optional(),
|
|
44
|
+
});
|
|
45
|
+
/** An id in the API's `{id:int}` routes (posts, images, authors, categories). */
|
|
46
|
+
export const IntIdSchema = z.int32().positive();
|
|
47
|
+
/** An id in the API's `{id:guid}` routes (users, comments, generation jobs). */
|
|
48
|
+
export const GuidIdSchema = z.guid();
|
|
35
49
|
/**
|
|
36
50
|
* `?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.
|
|
51
|
+
* the first page; `search` filters the whole list on the API. A value that
|
|
52
|
+
* does not fit (`?page=abc`, a hand-typed `?search=2026`, which the router
|
|
53
|
+
* reads as a number) is dropped instead of failing the route.
|
|
38
54
|
*/
|
|
39
55
|
export const pageSearchSchema = z.object({
|
|
40
|
-
page: z.number().int().min(0).optional(),
|
|
41
|
-
search: z.string().optional(),
|
|
56
|
+
page: z.number().int().min(0).optional().catch(undefined),
|
|
57
|
+
search: z.string().optional().catch(undefined),
|
|
42
58
|
});
|
package/dist/paging/react.d.ts
CHANGED
|
@@ -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>>];
|
package/dist/paging/react.js
CHANGED
|
@@ -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(() =>
|
|
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];
|
package/dist/schema/index.js
CHANGED
|
@@ -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
|
-
|
|
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
|
}
|
package/dist/security/index.d.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
/**
|
|
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.
|
|
23
|
-
* `strict-dynamic`
|
|
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
|
/**
|
package/dist/security/index.js
CHANGED
|
@@ -12,31 +12,43 @@ export function buildSecurityTxt({ contact, expires, canonical, preferredLanguag
|
|
|
12
12
|
].join("\n");
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
15
|
-
*
|
|
16
|
-
*
|
|
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":
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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
|
|
38
|
-
.map(([name, sources]) => [name, ...sources, ...(extraSources[name] ?? [])].join(" "))
|
|
39
|
-
|
|
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
|
package/dist/seo/index.d.ts
CHANGED
|
@@ -36,3 +36,9 @@ export type RobotsTxtOptions = {
|
|
|
36
36
|
};
|
|
37
37
|
/** robots.txt for one user agent. Serve with `plainTextResponse`. */
|
|
38
38
|
export declare function buildRobotsTxt({ userAgent, allow, disallow, sitemap, }: RobotsTxtOptions): string;
|
|
39
|
+
/**
|
|
40
|
+
* sitemap.xml listing each absolute URL once, in the order given. Serve with
|
|
41
|
+
* `xmlResponse`. It has no `lastmod`: a date that is not the page's real last
|
|
42
|
+
* change is worse than none.
|
|
43
|
+
*/
|
|
44
|
+
export declare function buildSitemapXml(urls: string[]): string;
|
package/dist/seo/index.js
CHANGED
|
@@ -37,3 +37,24 @@ export function buildRobotsTxt({ userAgent = "*", allow = [], disallow = [], sit
|
|
|
37
37
|
"",
|
|
38
38
|
].join("\n");
|
|
39
39
|
}
|
|
40
|
+
const xmlEntities = {
|
|
41
|
+
"&": "&",
|
|
42
|
+
"<": "<",
|
|
43
|
+
">": ">",
|
|
44
|
+
'"': """,
|
|
45
|
+
"'": "'",
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* sitemap.xml listing each absolute URL once, in the order given. Serve with
|
|
49
|
+
* `xmlResponse`. It has no `lastmod`: a date that is not the page's real last
|
|
50
|
+
* change is worse than none.
|
|
51
|
+
*/
|
|
52
|
+
export function buildSitemapXml(urls) {
|
|
53
|
+
return [
|
|
54
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
55
|
+
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
|
|
56
|
+
...[...new Set(urls)].map((url) => `\t<url><loc>${url.replace(/[&<>"']/g, (char) => xmlEntities[char] ?? char)}</loc></url>`),
|
|
57
|
+
"</urlset>",
|
|
58
|
+
"",
|
|
59
|
+
].join("\n");
|
|
60
|
+
}
|
package/dist/theme/index.d.ts
CHANGED
|
@@ -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.
|
|
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;
|
package/dist/theme/index.js
CHANGED
|
@@ -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.
|
|
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
|
-
|
|
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
|
}
|
package/dist/theme/react.d.ts
CHANGED
|
@@ -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
|
|
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 {};
|
package/dist/theme/react.js
CHANGED
|
@@ -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
|
-
|
|
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(
|
|
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
|
-
//
|
|
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 =
|
|
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
|
-
|
|
38
|
-
|
|
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 (
|
|
86
|
+
if (!mounted) {
|
|
41
87
|
return;
|
|
42
88
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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
|
-
|
|
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
|
|
110
|
+
* Hook to access the theme preference, the theme shown, and the setters.
|
|
60
111
|
*/
|
|
61
112
|
export const useTheme = () => React.useContext(ThemeProviderContext);
|
package/dist/theme/server.d.ts
CHANGED
|
@@ -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.
|
|
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
|
/**
|
package/dist/theme/server.js
CHANGED
|
@@ -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.
|
|
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
|
-
|
|
12
|
-
const
|
|
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
|
}
|