@codefast/theme 0.5.0-canary.1 → 0.5.0-canary.2

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.
Files changed (57) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +107 -178
  3. package/dist/appearance-context.d.mts +18 -0
  4. package/dist/appearance-context.mjs +16 -0
  5. package/dist/appearance-provider.d.mts +74 -0
  6. package/dist/appearance-provider.mjs +180 -0
  7. package/dist/appearance-script.d.mts +59 -0
  8. package/dist/appearance-script.mjs +46 -0
  9. package/dist/appearance.d.mts +60 -0
  10. package/dist/appearance.mjs +25 -0
  11. package/dist/color-scheme.d.mts +27 -0
  12. package/dist/color-scheme.mjs +32 -0
  13. package/dist/constants.d.mts +15 -14
  14. package/dist/constants.mjs +14 -13
  15. package/dist/{utils/dom.d.mts → dom.d.mts} +6 -8
  16. package/dist/{utils/dom.mjs → dom.mjs} +7 -9
  17. package/dist/index.d.mts +7 -7
  18. package/dist/index.mjs +7 -7
  19. package/dist/use-appearance.d.mts +34 -0
  20. package/dist/use-appearance.mjs +38 -0
  21. package/package.json +39 -63
  22. package/src/appearance-context.ts +22 -0
  23. package/src/appearance-provider.tsx +363 -0
  24. package/src/appearance-script.tsx +86 -0
  25. package/src/appearance.ts +66 -0
  26. package/src/color-scheme.ts +42 -0
  27. package/src/constants.ts +14 -13
  28. package/src/{utils/dom.ts → dom.ts} +8 -10
  29. package/src/index.ts +19 -16
  30. package/src/use-appearance.ts +46 -0
  31. package/dist/adapters/tanstack-start/server.d.mts +0 -88
  32. package/dist/adapters/tanstack-start/server.mjs +0 -93
  33. package/dist/adapters/tanstack-start/vite.d.mts +0 -12
  34. package/dist/adapters/tanstack-start/vite.mjs +0 -21
  35. package/dist/core/context.d.mts +0 -18
  36. package/dist/core/context.mjs +0 -16
  37. package/dist/core/provider.d.mts +0 -118
  38. package/dist/core/provider.mjs +0 -231
  39. package/dist/core/use-theme.d.mts +0 -34
  40. package/dist/core/use-theme.mjs +0 -38
  41. package/dist/script/theme-script.d.mts +0 -68
  42. package/dist/script/theme-script.mjs +0 -45
  43. package/dist/start.d.mts +0 -2
  44. package/dist/start.mjs +0 -2
  45. package/dist/types.d.mts +0 -60
  46. package/dist/types.mjs +0 -25
  47. package/dist/utils/system.d.mts +0 -34
  48. package/dist/utils/system.mjs +0 -40
  49. package/src/adapters/tanstack-start/server.ts +0 -146
  50. package/src/adapters/tanstack-start/vite.ts +0 -50
  51. package/src/core/context.tsx +0 -22
  52. package/src/core/provider.tsx +0 -470
  53. package/src/core/use-theme.ts +0 -46
  54. package/src/script/theme-script.tsx +0 -92
  55. package/src/start.ts +0 -54
  56. package/src/types.ts +0 -61
  57. package/src/utils/system.ts +0 -56
@@ -1,46 +0,0 @@
1
- import { use } from "react";
2
-
3
- import { ColorSchemeContext } from "#/core/context";
4
- import type { ColorSchemeContextType } from "#/types";
5
-
6
- /* -----------------------------------------------------------------------------
7
- * Hook
8
- * -------------------------------------------------------------------------- */
9
-
10
- /**
11
- * Hook to access color scheme context.
12
- *
13
- * Uses React 19's `use()` API for context consumption, enabling:
14
- * - Conditional context reading
15
- * - Better Suspense boundary integration
16
- *
17
- * @returns Color scheme context with `colorScheme`, `resolvedColorScheme`, `setPreferredColorScheme`, and `isPending`
18
- * @throws Error if called outside of AppearanceProvider
19
- *
20
- * @example
21
- * ```tsx
22
- * function AppearanceToggle() {
23
- * const { colorScheme, setPreferredColorScheme, isPending } = useColorScheme();
24
- *
25
- * return (
26
- * <button
27
- * onClick={() => setPreferredColorScheme(colorScheme === 'dark' ? 'light' : 'dark')}
28
- * disabled={isPending}
29
- * >
30
- * {colorScheme}
31
- * </button>
32
- * );
33
- * }
34
- * ```
35
- *
36
- * @since 0.3.16-canary.0
37
- */
38
- export function useColorScheme(): ColorSchemeContextType {
39
- const value = use(ColorSchemeContext);
40
-
41
- if (!value) {
42
- throw new Error("useColorScheme must be used within an AppearanceProvider");
43
- }
44
-
45
- return value;
46
- }
@@ -1,92 +0,0 @@
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).replaceAll("<", "\\u003C").replaceAll(">", "\\u003E").replaceAll("/", "\\u002F");
11
- }
12
-
13
- /* Derived once from schema + constants — inline script uses these to stay in sync */
14
- const COLOR_SCHEME_REMOVE_ARGS = colorSchemes.map((s) => toScriptSafe(s)).join(",");
15
- const COLOR_SCHEME_VALID_CHECK = colorSchemes.map((s) => `s===${toScriptSafe(s)}`).join("||");
16
-
17
- /* -----------------------------------------------------------------------------
18
- * Props
19
- * -------------------------------------------------------------------------- */
20
-
21
- /**
22
- * @since 0.3.16-canary.3
23
- */
24
- export type AppearanceScriptProps = {
25
- /**
26
- * Initial color scheme from server (e.g., from cookie via loader).
27
- *
28
- * When `storageKey` is provided, this acts as a fallback if the storage entry is absent
29
- * or contains an unrecognised value.
30
- */
31
- readonly colorScheme: ColorScheme;
32
- /**
33
- * CSP nonce applied to the inline script element.
34
- */
35
- readonly nonce?: string;
36
- /**
37
- * When provided, the inline script reads `localStorage.getItem(storageKey)` before
38
- * first paint and uses that value if it is a recognised color scheme (`"light"`, `"dark"`,
39
- * or `"automatic"`). Falls back to `colorScheme` when the key is absent or invalid.
40
- *
41
- * Use this for client-only React apps that persist the color scheme in `localStorage` instead
42
- * of an HTTP cookie to prevent FOUC.
43
- *
44
- * @example
45
- * ```tsx
46
- * <AppearanceScript colorScheme="automatic" storageKey="my-app-color-scheme" />
47
- * ```
48
- */
49
- readonly storageKey?: string;
50
- };
51
-
52
- /* -----------------------------------------------------------------------------
53
- * Component
54
- * -------------------------------------------------------------------------- */
55
-
56
- /**
57
- * Inline script that prevents Flash of Unstyled Content (FOUC).
58
- *
59
- * **Why this is needed:**
60
- * React hydration occurs after the browser has already painted the page.
61
- * Without this script, users would briefly see the wrong appearance before
62
- * React takes over and applies the correct one.
63
- *
64
- * **How it works:**
65
- * This script runs synchronously in the `<head>` before first paint:
66
- * 1. Resolves 'automatic' to 'light' or 'dark' using `matchMedia()`
67
- * 2. Removes prior `light` / `dark` / `automatic` classes on `<html>` (SSR may
68
- * have applied the wrong resolved class for `automatic`, e.g. default `dark`)
69
- * 3. Adds the resolved color scheme class and sets `color-scheme` for native controls
70
- * 4. Writes the *preference* to `data-appearance` so preference-aware UI (e.g. a 3-state toggle)
71
- * can render the right state from CSS on first paint, without a hydration flash
72
- *
73
- * @example
74
- * ```tsx
75
- * // In __root.tsx (TanStack Start)
76
- * <head>
77
- * <AppearanceScript colorScheme={colorScheme} />
78
- * </head>
79
- * ```
80
- *
81
- * @since 0.3.16-canary.0
82
- */
83
- export function AppearanceScript({ nonce, storageKey, colorScheme }: AppearanceScriptProps): JSX.Element {
84
- // S2: toScriptSafe = JSON.stringify + escape <>/ so </script> cannot break out of the tag.
85
- // F1: When storageKey is provided, the script reads localStorage before first paint so
86
- // client-only apps (no SSR cookie) get the right color scheme without FOUC.
87
- // sk=null short-circuits to s=null so color scheme falls back to fbt — backward-compatible.
88
- 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,document.documentElement.dataset.appearance=theme}catch(e){}})()`;
89
- const nonceProps = nonce === undefined ? {} : { nonce };
90
-
91
- return <script dangerouslySetInnerHTML={{ __html: appearanceScript }} suppressHydrationWarning {...nonceProps} />;
92
- }
package/src/start.ts DELETED
@@ -1,54 +0,0 @@
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 DELETED
@@ -1,61 +0,0 @@
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
- };
@@ -1,56 +0,0 @@
1
- import { DEFAULT_RESOLVED_COLOR_SCHEME, MEDIA } from "#/constants";
2
- import type { ResolvedColorScheme, ColorScheme } from "#/types";
3
-
4
- /* -----------------------------------------------------------------------------
5
- * System Color Scheme Detection
6
- * -------------------------------------------------------------------------- */
7
-
8
- /**
9
- * Detect the user's OS color scheme preference.
10
- *
11
- * Uses `matchMedia()` to query the `prefers-color-scheme` media feature.
12
- * Returns {@link DEFAULT_RESOLVED_COLOR_SCHEME} during SSR since `window` is unavailable.
13
- *
14
- * @returns 'light' or 'dark' based on OS preference
15
- *
16
- * @since 0.3.16-canary.0
17
- */
18
- export function getSystemColorScheme(): ResolvedColorScheme {
19
- if (typeof globalThis.window === "undefined") {
20
- return DEFAULT_RESOLVED_COLOR_SCHEME;
21
- }
22
-
23
- return globalThis.window.matchMedia(MEDIA).matches ? "dark" : "light";
24
- }
25
-
26
- /**
27
- * Resolve color scheme preference to actual light/dark value.
28
- *
29
- * - 'light' → 'light'
30
- * - 'dark' → 'dark'
31
- * - 'automatic' → on the client, result of {@link getSystemColorScheme}; on the server,
32
- * `ssrColorScheme` when provided, otherwise {@link DEFAULT_RESOLVED_COLOR_SCHEME}
33
- *
34
- * @param colorScheme - User's color scheme preference (`light`, `dark`, or `automatic`)
35
- * @param ssrColorScheme - When `colorScheme` is `automatic` and this runs during SSR (no `window`),
36
- * uses this as the resolved appearance—typically from Client Hints
37
- * (`Sec-CH-Prefers-Color-Scheme`) so `<html class>` matches the real OS preference.
38
- * Ignored for non-`automatic` schemes and on the client (where {@link getSystemColorScheme} wins).
39
- * @returns The resolved color scheme to apply (`light` or `dark`)
40
- *
41
- * @since 0.3.16-canary.0
42
- */
43
- export function resolveColorScheme(
44
- colorScheme: ColorScheme,
45
- ssrColorScheme?: ResolvedColorScheme,
46
- ): ResolvedColorScheme {
47
- if (colorScheme !== "automatic") {
48
- return colorScheme;
49
- }
50
-
51
- if (typeof globalThis.window === "undefined") {
52
- return ssrColorScheme ?? DEFAULT_RESOLVED_COLOR_SCHEME;
53
- }
54
-
55
- return getSystemColorScheme();
56
- }