@codefast/theme 0.3.16-canary.2 → 0.3.16-canary.3

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,103 @@
1
+ import type { JSX } from "react";
2
+
3
+ import { MEDIA } from "#/constants";
4
+ import { colorSchemes } from "#/types";
5
+ import type { ColorScheme } from "#/types";
6
+
7
+ /* JSON.stringify does not escape </script>, so we replace the three characters that
8
+ * can form a closing tag: < > /. Unicode escapes are valid JS and safe in HTML. */
9
+ function toScriptSafe(value: unknown): string {
10
+ return JSON.stringify(value)
11
+ .replaceAll("<", "\\u003C")
12
+ .replaceAll(">", "\\u003E")
13
+ .replaceAll("/", "\\u002F");
14
+ }
15
+
16
+ /* Derived once from schema + constants — inline script uses these to stay in sync */
17
+ const COLOR_SCHEME_REMOVE_ARGS = colorSchemes.map((s) => toScriptSafe(s)).join(",");
18
+ const COLOR_SCHEME_VALID_CHECK = colorSchemes.map((s) => `s===${toScriptSafe(s)}`).join("||");
19
+
20
+ /* -----------------------------------------------------------------------------
21
+ * Props
22
+ * -------------------------------------------------------------------------- */
23
+
24
+ /**
25
+ * @since 0.3.16-canary.3
26
+ */
27
+ export type AppearanceScriptProps = {
28
+ /**
29
+ * Initial color scheme from server (e.g., from cookie via loader).
30
+ *
31
+ * When `storageKey` is provided, this acts as a fallback if the storage entry is absent
32
+ * or contains an unrecognised value.
33
+ */
34
+ readonly colorScheme: ColorScheme;
35
+ /**
36
+ * CSP nonce applied to the inline script element.
37
+ */
38
+ readonly nonce?: string;
39
+ /**
40
+ * When provided, the inline script reads `localStorage.getItem(storageKey)` before
41
+ * first paint and uses that value if it is a recognised color scheme (`"light"`, `"dark"`,
42
+ * or `"automatic"`). Falls back to `colorScheme` when the key is absent or invalid.
43
+ *
44
+ * Use this for client-only React apps that persist the color scheme in `localStorage` instead
45
+ * of an HTTP cookie to prevent FOUC.
46
+ *
47
+ * @example
48
+ * ```tsx
49
+ * <AppearanceScript colorScheme="automatic" storageKey="my-app-color-scheme" />
50
+ * ```
51
+ */
52
+ readonly storageKey?: string;
53
+ };
54
+
55
+ /* -----------------------------------------------------------------------------
56
+ * Component
57
+ * -------------------------------------------------------------------------- */
58
+
59
+ /**
60
+ * Inline script that prevents Flash of Unstyled Content (FOUC).
61
+ *
62
+ * **Why this is needed:**
63
+ * React hydration occurs after the browser has already painted the page.
64
+ * Without this script, users would briefly see the wrong appearance before
65
+ * React takes over and applies the correct one.
66
+ *
67
+ * **How it works:**
68
+ * This script runs synchronously in the `<head>` before first paint:
69
+ * 1. Resolves 'automatic' to 'light' or 'dark' using `matchMedia()`
70
+ * 2. Removes prior `light` / `dark` / `automatic` classes on `<html>` (SSR may
71
+ * have applied the wrong resolved class for `automatic`, e.g. default `dark`)
72
+ * 3. Adds the resolved color scheme class and sets `color-scheme` for native controls
73
+ *
74
+ * @example
75
+ * ```tsx
76
+ * // In __root.tsx (TanStack Start)
77
+ * <head>
78
+ * <AppearanceScript colorScheme={colorScheme} />
79
+ * </head>
80
+ * ```
81
+ *
82
+ * @since 0.3.16-canary.0
83
+ */
84
+ export function AppearanceScript({
85
+ nonce,
86
+ storageKey,
87
+ colorScheme,
88
+ }: AppearanceScriptProps): JSX.Element {
89
+ // S2: toScriptSafe = JSON.stringify + escape <>/ so </script> cannot break out of the tag.
90
+ // F1: When storageKey is provided, the script reads localStorage before first paint so
91
+ // client-only apps (no SSR cookie) get the right color scheme without FOUC.
92
+ // sk=null short-circuits to s=null so color scheme falls back to fbt — backward-compatible.
93
+ const appearanceScript = `(function(){try{var sk=${toScriptSafe(storageKey ?? null)},fbt=${toScriptSafe(colorScheme)},s=sk&&localStorage.getItem(sk),theme=(${COLOR_SCHEME_VALID_CHECK})?s:fbt,resolvedTheme=theme;"automatic"===theme&&(resolvedTheme=window.matchMedia(${toScriptSafe(MEDIA)}).matches?"dark":"light"),document.documentElement.classList.remove(${COLOR_SCHEME_REMOVE_ARGS}),document.documentElement.classList.add(resolvedTheme),document.documentElement.style.colorScheme=resolvedTheme}catch(e){}})()`;
94
+ const nonceProps = nonce === undefined ? {} : { nonce };
95
+
96
+ return (
97
+ <script
98
+ dangerouslySetInnerHTML={{ __html: appearanceScript }}
99
+ suppressHydrationWarning
100
+ {...nonceProps}
101
+ />
102
+ );
103
+ }
package/src/start.ts ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * TanStack Start integration: HTTP-only color scheme cookie + server functions.
3
+ *
4
+ * Peer: `@tanstack/react-start`. The app keeps full control of `<html>`, `<head>`, and `<body>`.
5
+ * Use {@link getRootColorSchemeServerFn} in the root loader, then wire `@codefast/theme` primitives
6
+ * (`AppearanceProvider`, `AppearanceScript`, `resolveColorScheme`).
7
+ *
8
+ * @example
9
+ * ```tsx
10
+ * // __root.tsx
11
+ * import { HeadContent, Scripts, createRootRouteWithContext } from "@tanstack/react-router";
12
+ * import { getRootColorSchemeServerFn, getColorSchemeServerFn, persistColorSchemeCookie } from "@codefast/theme/start";
13
+ * import { AppearanceProvider, AppearanceScript, resolveColorScheme } from "@codefast/theme";
14
+ *
15
+ * export const Route = createRootRouteWithContext<RootRouterContext>()({
16
+ * loader: async () => getRootColorSchemeServerFn(),
17
+ * shellComponent: RootShellComponent,
18
+ * });
19
+ *
20
+ * function RootShellComponent({ children }: PropsWithChildren) {
21
+ * const { colorScheme, ssrColorScheme } = Route.useLoaderData();
22
+ * const resolvedColorScheme = resolveColorScheme(colorScheme, ssrColorScheme);
23
+ *
24
+ * return (
25
+ * <html className={resolvedColorScheme} lang="en" style={{ colorScheme: resolvedColorScheme }} suppressHydrationWarning>
26
+ * <head>
27
+ * <HeadContent />
28
+ * <AppearanceScript colorScheme={colorScheme} />
29
+ * </head>
30
+ * <body>
31
+ * <AppearanceProvider
32
+ * colorScheme={colorScheme}
33
+ * ssrColorScheme={ssrColorScheme}
34
+ * persistColorScheme={persistColorSchemeCookie}
35
+ * syncColorSchemeFromServer={getColorSchemeServerFn}
36
+ * >
37
+ * {children}
38
+ * </AppearanceProvider>
39
+ * <Scripts />
40
+ * </body>
41
+ * </html>
42
+ * );
43
+ * }
44
+ * ```
45
+ */
46
+
47
+ export {
48
+ getRootColorSchemeServerFn,
49
+ getSsrColorSchemeServerFn,
50
+ getColorSchemeServerFn,
51
+ persistColorSchemeCookie,
52
+ setColorSchemeServerFn,
53
+ type RootColorSchemeLoaderData,
54
+ } from "#/adapters/tanstack-start/server";
package/src/types.ts ADDED
@@ -0,0 +1,61 @@
1
+ import { z } from "zod";
2
+
3
+ /* -----------------------------------------------------------------------------
4
+ * Schema & Types
5
+ * -------------------------------------------------------------------------- */
6
+
7
+ /**
8
+ * Zod schema for color scheme validation.
9
+ *
10
+ * Acts as the single source of truth for all color-scheme-related types.
11
+ * Valid values: 'light', 'dark', 'automatic'.
12
+ *
13
+ * @since 0.3.16-canary.0
14
+ */
15
+ export const colorSchemeSchema = z.enum(["light", "dark", "automatic"]);
16
+
17
+ /**
18
+ * User's color scheme preference.
19
+ *
20
+ * - `'light'` - Force light appearance
21
+ * - `'dark'` - Force dark appearance
22
+ * - `'automatic'` - Follow OS preference
23
+ *
24
+ * @since 0.3.16-canary.0
25
+ */
26
+ export type ColorScheme = z.infer<typeof colorSchemeSchema>;
27
+
28
+ /**
29
+ * Actual color scheme applied to the UI after resolving 'automatic'.
30
+ *
31
+ * When color scheme is 'automatic', this reflects the OS preference (light/dark).
32
+ *
33
+ * @since 0.3.16-canary.0
34
+ */
35
+ export type ResolvedColorScheme = Exclude<ColorScheme, "automatic">;
36
+
37
+ /**
38
+ * Array of all available color scheme options: `['light', 'dark', 'automatic']`.
39
+ *
40
+ * Useful for rendering appearance selectors in UI components.
41
+ *
42
+ * @since 0.3.16-canary.0
43
+ */
44
+ export const colorSchemes = colorSchemeSchema.options;
45
+
46
+ /**
47
+ * Shape of the color scheme context value provided by AppearanceProvider.
48
+ *
49
+ * - `colorScheme` - Current color scheme preference
50
+ * - `resolvedColorScheme` - Actual color scheme applied (automatic resolved to light/dark)
51
+ * - `setPreferredColorScheme` - Async function to update color scheme (triggers optimistic update)
52
+ * - `isPending` - True while color scheme change is being persisted
53
+ *
54
+ * @since 0.3.16-canary.0
55
+ */
56
+ export type ColorSchemeContextType = {
57
+ readonly isPending: boolean;
58
+ readonly resolvedColorScheme: ResolvedColorScheme;
59
+ readonly setColorScheme: (value: ColorScheme) => Promise<void>;
60
+ readonly colorScheme: ColorScheme;
61
+ };
@@ -0,0 +1,87 @@
1
+ import type { ResolvedColorScheme } from "#/types";
2
+
3
+ /* -----------------------------------------------------------------------------
4
+ * DOM Utilities
5
+ * -------------------------------------------------------------------------- */
6
+
7
+ /**
8
+ * Apply color scheme to the DOM by updating `<html>` element.
9
+ *
10
+ * Updates both:
11
+ * - CSS class (for Tailwind's `dark:` variants)
12
+ * - `color-scheme` style (for native form controls and scrollbars)
13
+ *
14
+ * @param resolved - The resolved color scheme to apply ('light' or 'dark')
15
+ *
16
+ * @since 0.3.16-canary.0
17
+ */
18
+ export function applyColorScheme(resolved: ResolvedColorScheme): void {
19
+ const root = window.document.documentElement;
20
+
21
+ root.classList.remove("light", "dark", "automatic");
22
+ root.classList.add(resolved);
23
+ root.style.colorScheme = resolved;
24
+ }
25
+
26
+ /**
27
+ * Temporarily suppress all CSS transitions during color scheme changes.
28
+ *
29
+ * Prevents jarring color animations when switching between light/dark appearances.
30
+ * Respects user's `prefers-reduced-motion` preference (does nothing if enabled).
31
+ *
32
+ * @param nonce - Optional CSP nonce for the injected style element
33
+ * @returns Cleanup function to re-enable transitions. Call after color scheme is applied.
34
+ *
35
+ * @example
36
+ * ```tsx
37
+ * const enableTransitions = suppressTransitions();
38
+ * applyColorScheme('dark');
39
+ * enableTransitions(); // Re-enables CSS transitions
40
+ * ```
41
+ *
42
+ * @since 0.3.16-canary.0
43
+ */
44
+ export function suppressTransitions(nonce?: string): () => void {
45
+ if (typeof globalThis.window === "undefined") {
46
+ return () => {
47
+ /* noop */
48
+ };
49
+ }
50
+
51
+ // Respect user's motion preferences
52
+ const prefersReducedMotion = globalThis.window.matchMedia(
53
+ "(prefers-reduced-motion: reduce)",
54
+ ).matches;
55
+
56
+ if (prefersReducedMotion) {
57
+ return () => {
58
+ /* noop */
59
+ };
60
+ }
61
+
62
+ // Inject style to suppress all transitions
63
+ const css = document.createElement("style");
64
+
65
+ if (nonce) {
66
+ css.setAttribute("nonce", nonce);
67
+ }
68
+
69
+ // P3: Only the unprefixed property is needed — all modern browsers support it
70
+ css.append(document.createTextNode(`*,*::before,*::after{transition:none!important}`));
71
+
72
+ document.head.append(css);
73
+
74
+ return () => {
75
+ // Force reflow to ensure styles are applied before removing
76
+ void window.getComputedStyle(document.body);
77
+
78
+ // Use double RAF to ensure paint happens before removing style
79
+ requestAnimationFrame(() => {
80
+ requestAnimationFrame(() => {
81
+ if (css.parentNode) {
82
+ css.remove();
83
+ }
84
+ });
85
+ });
86
+ };
87
+ }
@@ -0,0 +1,57 @@
1
+ import type { ResolvedColorScheme, ColorScheme } from "#/types";
2
+
3
+ import { DEFAULT_RESOLVED_COLOR_SCHEME, MEDIA } from "#/constants";
4
+
5
+ /* -----------------------------------------------------------------------------
6
+ * System Color Scheme Detection
7
+ * -------------------------------------------------------------------------- */
8
+
9
+ /**
10
+ * Detect the user's OS color scheme preference.
11
+ *
12
+ * Uses `matchMedia()` to query the `prefers-color-scheme` media feature.
13
+ * Returns {@link DEFAULT_RESOLVED_COLOR_SCHEME} during SSR since `window` is unavailable.
14
+ *
15
+ * @returns 'light' or 'dark' based on OS preference
16
+ *
17
+ * @since 0.3.16-canary.0
18
+ */
19
+ export function getSystemColorScheme(): ResolvedColorScheme {
20
+ if (typeof globalThis.window === "undefined") {
21
+ return DEFAULT_RESOLVED_COLOR_SCHEME;
22
+ }
23
+
24
+ return globalThis.window.matchMedia(MEDIA).matches ? "dark" : "light";
25
+ }
26
+
27
+ /**
28
+ * Resolve color scheme preference to actual light/dark value.
29
+ *
30
+ * - 'light' → 'light'
31
+ * - 'dark' → 'dark'
32
+ * - 'automatic' → on the client, result of {@link getSystemColorScheme}; on the server,
33
+ * `ssrColorScheme` when provided, otherwise {@link DEFAULT_RESOLVED_COLOR_SCHEME}
34
+ *
35
+ * @param colorScheme - User's color scheme preference (`light`, `dark`, or `automatic`)
36
+ * @param ssrColorScheme - When `colorScheme` is `automatic` and this runs during SSR (no `window`),
37
+ * uses this as the resolved appearance—typically from Client Hints
38
+ * (`Sec-CH-Prefers-Color-Scheme`) so `<html class>` matches the real OS preference.
39
+ * Ignored for non-`automatic` schemes and on the client (where {@link getSystemColorScheme} wins).
40
+ * @returns The resolved color scheme to apply (`light` or `dark`)
41
+ *
42
+ * @since 0.3.16-canary.0
43
+ */
44
+ export function resolveColorScheme(
45
+ colorScheme: ColorScheme,
46
+ ssrColorScheme?: ResolvedColorScheme,
47
+ ): ResolvedColorScheme {
48
+ if (colorScheme !== "automatic") {
49
+ return colorScheme;
50
+ }
51
+
52
+ if (typeof globalThis.window === "undefined") {
53
+ return ssrColorScheme ?? DEFAULT_RESOLVED_COLOR_SCHEME;
54
+ }
55
+
56
+ return getSystemColorScheme();
57
+ }