@codefast/theme 0.5.0-canary.0 → 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.
- package/CHANGELOG.md +39 -0
- package/README.md +116 -183
- package/dist/appearance-context.d.mts +18 -0
- package/dist/appearance-context.mjs +16 -0
- package/dist/appearance-provider.d.mts +74 -0
- package/dist/appearance-provider.mjs +180 -0
- package/dist/appearance-script.d.mts +59 -0
- package/dist/appearance-script.mjs +46 -0
- package/dist/appearance.d.mts +60 -0
- package/dist/appearance.mjs +25 -0
- package/dist/color-scheme.d.mts +27 -0
- package/dist/color-scheme.mjs +32 -0
- package/dist/constants.d.mts +15 -14
- package/dist/constants.mjs +14 -13
- package/dist/{utils/dom.d.mts → dom.d.mts} +6 -8
- package/dist/{utils/dom.mjs → dom.mjs} +7 -9
- package/dist/index.d.mts +7 -7
- package/dist/index.mjs +7 -7
- package/dist/use-appearance.d.mts +34 -0
- package/dist/use-appearance.mjs +38 -0
- package/package.json +39 -59
- package/src/appearance-context.ts +22 -0
- package/src/appearance-provider.tsx +363 -0
- package/src/appearance-script.tsx +86 -0
- package/src/appearance.ts +66 -0
- package/src/color-scheme.ts +42 -0
- package/src/constants.ts +14 -13
- package/src/{utils/dom.ts → dom.ts} +8 -10
- package/src/index.ts +19 -16
- package/src/use-appearance.ts +46 -0
- package/dist/adapters/tanstack-start/server.d.mts +0 -88
- package/dist/adapters/tanstack-start/server.mjs +0 -93
- package/dist/adapters/tanstack-start/vite.d.mts +0 -12
- package/dist/adapters/tanstack-start/vite.mjs +0 -21
- package/dist/core/context.d.mts +0 -18
- package/dist/core/context.mjs +0 -16
- package/dist/core/provider.d.mts +0 -102
- package/dist/core/provider.mjs +0 -183
- package/dist/core/use-theme.d.mts +0 -34
- package/dist/core/use-theme.mjs +0 -38
- package/dist/script/theme-script.d.mts +0 -66
- package/dist/script/theme-script.mjs +0 -43
- package/dist/start.d.mts +0 -2
- package/dist/start.mjs +0 -2
- package/dist/types.d.mts +0 -60
- package/dist/types.mjs +0 -25
- package/dist/utils/system.d.mts +0 -34
- package/dist/utils/system.mjs +0 -40
- package/src/adapters/tanstack-start/server.ts +0 -146
- package/src/adapters/tanstack-start/vite.ts +0 -50
- package/src/core/context.tsx +0 -22
- package/src/core/provider.tsx +0 -364
- package/src/core/use-theme.ts +0 -46
- package/src/script/theme-script.tsx +0 -90
- package/src/start.ts +0 -54
- package/src/types.ts +0 -61
- package/src/utils/system.ts +0 -56
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { JSX } from "react";
|
|
2
|
+
|
|
3
|
+
import { appearances } from "#/appearance";
|
|
4
|
+
import type { Appearance } from "#/appearance";
|
|
5
|
+
import { DEFAULT_APPEARANCE, MEDIA, STORAGE_KEY } from "#/constants";
|
|
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 — the inline script uses these to stay in sync */
|
|
14
|
+
const APPEARANCE_REMOVE_ARGS = appearances.map((s) => toScriptSafe(s)).join(",");
|
|
15
|
+
const APPEARANCE_VALID_CHECK = appearances.map((s) => `s===${toScriptSafe(s)}`).join("||");
|
|
16
|
+
|
|
17
|
+
/* -----------------------------------------------------------------------------
|
|
18
|
+
* Props
|
|
19
|
+
* -------------------------------------------------------------------------- */
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @since 0.5.0-canary.2
|
|
23
|
+
*/
|
|
24
|
+
export type AppearanceScriptProps = {
|
|
25
|
+
/**
|
|
26
|
+
* Fallback preference when the storage entry is absent or unrecognised.
|
|
27
|
+
* Defaults to {@link DEFAULT_APPEARANCE}.
|
|
28
|
+
*/
|
|
29
|
+
readonly appearance?: Appearance;
|
|
30
|
+
/**
|
|
31
|
+
* CSP nonce applied to the inline script element.
|
|
32
|
+
*/
|
|
33
|
+
readonly nonce?: string;
|
|
34
|
+
/**
|
|
35
|
+
* `localStorage` key the script reads before first paint — a recognised value (`"light"`,
|
|
36
|
+
* `"dark"`, or `"automatic"`) wins over `appearance`.
|
|
37
|
+
* Defaults to {@link STORAGE_KEY}; pair with `<AppearanceProvider>` using the **same key**.
|
|
38
|
+
*/
|
|
39
|
+
readonly storageKey?: string;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/* -----------------------------------------------------------------------------
|
|
43
|
+
* Component
|
|
44
|
+
* -------------------------------------------------------------------------- */
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Inline script that prevents Flash of Unstyled Content (FOUC).
|
|
48
|
+
*
|
|
49
|
+
* **Why this is needed:**
|
|
50
|
+
* React hydration occurs after the browser has already painted the page.
|
|
51
|
+
* Without this script, users would briefly see the wrong appearance before
|
|
52
|
+
* React takes over and applies the correct one.
|
|
53
|
+
*
|
|
54
|
+
* **How it works:**
|
|
55
|
+
* This script runs synchronously in the `<head>` before first paint:
|
|
56
|
+
* 1. Reads the stored preference from `localStorage`, falling back to `appearance`
|
|
57
|
+
* 2. Resolves 'automatic' to 'light' or 'dark' using `matchMedia()`
|
|
58
|
+
* 3. Removes prior `light` / `dark` / `automatic` classes on `<html>` (SSR may
|
|
59
|
+
* have applied the wrong resolved class for `automatic`, e.g. default `dark`)
|
|
60
|
+
* 4. Adds the resolved color scheme class and sets `color-scheme` for native controls
|
|
61
|
+
* 5. Writes the *preference* to `data-appearance` so preference-aware UI (e.g. a 3-state toggle)
|
|
62
|
+
* can render the right state from CSS on first paint, without a hydration flash
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```tsx
|
|
66
|
+
* // In __root.tsx (TanStack Start)
|
|
67
|
+
* <head>
|
|
68
|
+
* <AppearanceScript />
|
|
69
|
+
* </head>
|
|
70
|
+
* ```
|
|
71
|
+
*
|
|
72
|
+
* @since 0.5.0-canary.2
|
|
73
|
+
*/
|
|
74
|
+
export function AppearanceScript({
|
|
75
|
+
nonce,
|
|
76
|
+
storageKey = STORAGE_KEY,
|
|
77
|
+
appearance = DEFAULT_APPEARANCE,
|
|
78
|
+
}: AppearanceScriptProps): JSX.Element {
|
|
79
|
+
// toScriptSafe = JSON.stringify + escape <>/ so </script> cannot break out of the tag.
|
|
80
|
+
// The script reads localStorage before first paint so the stored preference applies
|
|
81
|
+
// without FOUC; an absent or invalid entry falls back to fb.
|
|
82
|
+
const appearanceScript = `(function(){try{var sk=${toScriptSafe(storageKey)},fb=${toScriptSafe(appearance)},s=localStorage.getItem(sk),appearance=(${APPEARANCE_VALID_CHECK})?s:fb,colorScheme=appearance;"automatic"===appearance&&(colorScheme=window.matchMedia(${toScriptSafe(MEDIA)}).matches?"dark":"light"),document.documentElement.classList.remove(${APPEARANCE_REMOVE_ARGS}),document.documentElement.classList.add(colorScheme),document.documentElement.style.colorScheme=colorScheme,document.documentElement.dataset.appearance=appearance}catch(e){}})()`;
|
|
83
|
+
const nonceProps = nonce === undefined ? {} : { nonce };
|
|
84
|
+
|
|
85
|
+
return <script dangerouslySetInnerHTML={{ __html: appearanceScript }} suppressHydrationWarning {...nonceProps} />;
|
|
86
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
/* -----------------------------------------------------------------------------
|
|
4
|
+
* Schema & Types
|
|
5
|
+
*
|
|
6
|
+
* Vocabulary follows Apple's Human Interface Guidelines: "appearance" is the
|
|
7
|
+
* user's preference (Light / Dark / Auto), "color scheme" is the resolved
|
|
8
|
+
* light-or-dark value actually applied (matching CSS `color-scheme` and
|
|
9
|
+
* `prefers-color-scheme`).
|
|
10
|
+
* -------------------------------------------------------------------------- */
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Zod schema for appearance validation.
|
|
14
|
+
*
|
|
15
|
+
* Acts as the single source of truth for all appearance-related types.
|
|
16
|
+
* Valid values: 'light', 'dark', 'automatic'.
|
|
17
|
+
*
|
|
18
|
+
* @since 0.5.0-canary.2
|
|
19
|
+
*/
|
|
20
|
+
export const appearanceSchema = z.enum(["light", "dark", "automatic"]);
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* User's appearance preference.
|
|
24
|
+
*
|
|
25
|
+
* - `'light'` - Force light appearance
|
|
26
|
+
* - `'dark'` - Force dark appearance
|
|
27
|
+
* - `'automatic'` - Follow OS preference
|
|
28
|
+
*
|
|
29
|
+
* @since 0.5.0-canary.2
|
|
30
|
+
*/
|
|
31
|
+
export type Appearance = z.infer<typeof appearanceSchema>;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Color scheme actually applied to the UI after resolving 'automatic'.
|
|
35
|
+
*
|
|
36
|
+
* When the appearance is 'automatic', this reflects the OS preference (light/dark).
|
|
37
|
+
*
|
|
38
|
+
* @since 0.5.0-canary.2
|
|
39
|
+
*/
|
|
40
|
+
export type ColorScheme = Exclude<Appearance, "automatic">;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Array of all available appearance options: `['light', 'dark', 'automatic']`.
|
|
44
|
+
*
|
|
45
|
+
* Useful for rendering appearance selectors in UI components.
|
|
46
|
+
*
|
|
47
|
+
* @since 0.5.0-canary.2
|
|
48
|
+
*/
|
|
49
|
+
export const appearances = appearanceSchema.options;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Shape of the context value provided by AppearanceProvider.
|
|
53
|
+
*
|
|
54
|
+
* - `appearance` - Current appearance preference
|
|
55
|
+
* - `colorScheme` - Color scheme actually applied (automatic resolved to light/dark)
|
|
56
|
+
* - `setAppearance` - Async function to update the preference (triggers optimistic update)
|
|
57
|
+
* - `isPending` - True while an appearance change is being persisted
|
|
58
|
+
*
|
|
59
|
+
* @since 0.5.0-canary.2
|
|
60
|
+
*/
|
|
61
|
+
export type AppearanceContextType = {
|
|
62
|
+
readonly isPending: boolean;
|
|
63
|
+
readonly colorScheme: ColorScheme;
|
|
64
|
+
readonly setAppearance: (value: Appearance) => Promise<void>;
|
|
65
|
+
readonly appearance: Appearance;
|
|
66
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Appearance, ColorScheme } from "#/appearance";
|
|
2
|
+
import { DEFAULT_COLOR_SCHEME, MEDIA } from "#/constants";
|
|
3
|
+
|
|
4
|
+
/* -----------------------------------------------------------------------------
|
|
5
|
+
* Color Scheme Resolution
|
|
6
|
+
* -------------------------------------------------------------------------- */
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Detect the OS color scheme preference.
|
|
10
|
+
*
|
|
11
|
+
* Uses `matchMedia()` to query the `prefers-color-scheme` media feature.
|
|
12
|
+
* Returns {@link DEFAULT_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(): ColorScheme {
|
|
19
|
+
if (typeof globalThis.window === "undefined") {
|
|
20
|
+
return DEFAULT_COLOR_SCHEME;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
return globalThis.window.matchMedia(MEDIA).matches ? "dark" : "light";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Resolve an appearance preference to the color scheme to apply.
|
|
28
|
+
*
|
|
29
|
+
* - 'light' → 'light'
|
|
30
|
+
* - 'dark' → 'dark'
|
|
31
|
+
* - 'automatic' → on the client, result of {@link getSystemColorScheme};
|
|
32
|
+
* on the server, {@link DEFAULT_COLOR_SCHEME}
|
|
33
|
+
*
|
|
34
|
+
* @since 0.3.16-canary.0
|
|
35
|
+
*/
|
|
36
|
+
export function resolveColorScheme(appearance: Appearance): ColorScheme {
|
|
37
|
+
if (appearance !== "automatic") {
|
|
38
|
+
return appearance;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return getSystemColorScheme();
|
|
42
|
+
}
|
package/src/constants.ts
CHANGED
|
@@ -1,35 +1,36 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Appearance, ColorScheme } from "#/appearance";
|
|
2
2
|
|
|
3
3
|
/* -----------------------------------------------------------------------------
|
|
4
4
|
* Public Constants
|
|
5
5
|
* -------------------------------------------------------------------------- */
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
* Default
|
|
8
|
+
* Default appearance preference when no stored value exists.
|
|
9
9
|
*
|
|
10
10
|
* Set to 'automatic' to respect OS preference by default.
|
|
11
11
|
*
|
|
12
|
-
* @since 0.
|
|
12
|
+
* @since 0.5.0-canary.2
|
|
13
13
|
*/
|
|
14
|
-
export const
|
|
14
|
+
export const DEFAULT_APPEARANCE: Appearance = "automatic";
|
|
15
15
|
|
|
16
16
|
/**
|
|
17
|
-
* Fallback color scheme
|
|
17
|
+
* Fallback color scheme when the system color scheme cannot be detected.
|
|
18
18
|
*
|
|
19
|
-
*
|
|
19
|
+
* Applies wherever `window.matchMedia()` is unavailable, e.g. during server render.
|
|
20
20
|
*
|
|
21
|
-
* @since 0.
|
|
21
|
+
* @since 0.5.0-canary.2
|
|
22
22
|
*/
|
|
23
|
-
export const
|
|
23
|
+
export const DEFAULT_COLOR_SCHEME: ColorScheme = "dark";
|
|
24
24
|
|
|
25
25
|
/**
|
|
26
|
-
*
|
|
26
|
+
* Default `localStorage` key for the appearance preference, shared by
|
|
27
|
+
* `AppearanceScript` and `AppearanceProvider`.
|
|
27
28
|
*
|
|
28
|
-
* Re-exported only from `@codefast/theme/constants` so custom
|
|
29
|
+
* Re-exported only from `@codefast/theme/constants` so custom integrations can match it exactly.
|
|
29
30
|
*
|
|
30
31
|
* @since 0.3.16-canary.0
|
|
31
32
|
*/
|
|
32
|
-
export const STORAGE_KEY = "ui-
|
|
33
|
+
export const STORAGE_KEY = "ui-appearance";
|
|
33
34
|
|
|
34
35
|
/* -----------------------------------------------------------------------------
|
|
35
36
|
* Internal Constants
|
|
@@ -44,9 +45,9 @@ export const STORAGE_KEY = "ui-theme";
|
|
|
44
45
|
export const MEDIA = "(prefers-color-scheme: dark)";
|
|
45
46
|
|
|
46
47
|
/**
|
|
47
|
-
* BroadcastChannel name for cross-tab
|
|
48
|
+
* BroadcastChannel name for cross-tab appearance synchronization.
|
|
48
49
|
* @internal
|
|
49
50
|
*
|
|
50
51
|
* @since 0.3.16-canary.0
|
|
51
52
|
*/
|
|
52
|
-
export const SYNC_CHANNEL = "
|
|
53
|
+
export const SYNC_CHANNEL = "appearance-sync";
|
|
@@ -1,36 +1,34 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ColorScheme } from "#/appearance";
|
|
2
2
|
|
|
3
3
|
/* -----------------------------------------------------------------------------
|
|
4
4
|
* DOM Utilities
|
|
5
5
|
* -------------------------------------------------------------------------- */
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
* Apply color scheme to the DOM by updating `<html>` element.
|
|
8
|
+
* Apply a color scheme to the DOM by updating the `<html>` element.
|
|
9
9
|
*
|
|
10
10
|
* Updates both:
|
|
11
11
|
* - CSS class (for Tailwind's `dark:` variants)
|
|
12
12
|
* - `color-scheme` style (for native form controls and scrollbars)
|
|
13
13
|
*
|
|
14
|
-
* @param resolved - The resolved color scheme to apply ('light' or 'dark')
|
|
15
|
-
*
|
|
16
14
|
* @since 0.3.16-canary.0
|
|
17
15
|
*/
|
|
18
|
-
export function applyColorScheme(
|
|
16
|
+
export function applyColorScheme(colorScheme: ColorScheme): void {
|
|
19
17
|
const root = window.document.documentElement;
|
|
20
18
|
|
|
21
19
|
root.classList.remove("light", "dark", "automatic");
|
|
22
|
-
root.classList.add(
|
|
23
|
-
root.style.colorScheme =
|
|
20
|
+
root.classList.add(colorScheme);
|
|
21
|
+
root.style.colorScheme = colorScheme;
|
|
24
22
|
}
|
|
25
23
|
|
|
26
24
|
/**
|
|
27
|
-
* Temporarily suppress all CSS transitions during
|
|
25
|
+
* Temporarily suppress all CSS transitions during appearance changes.
|
|
28
26
|
*
|
|
29
27
|
* Prevents jarring color animations when switching between light/dark appearances.
|
|
30
28
|
* Respects user's `prefers-reduced-motion` preference (does nothing if enabled).
|
|
31
29
|
*
|
|
32
30
|
* @param nonce - Optional CSP nonce for the injected style element
|
|
33
|
-
* @returns Cleanup function to re-enable transitions. Call after color scheme is applied.
|
|
31
|
+
* @returns Cleanup function to re-enable transitions. Call after the color scheme is applied.
|
|
34
32
|
*
|
|
35
33
|
* @example
|
|
36
34
|
* ```tsx
|
|
@@ -64,7 +62,7 @@ export function suppressTransitions(nonce?: string): () => void {
|
|
|
64
62
|
css.setAttribute("nonce", nonce);
|
|
65
63
|
}
|
|
66
64
|
|
|
67
|
-
//
|
|
65
|
+
// Only the unprefixed property is needed — all modern browsers support it
|
|
68
66
|
css.append(document.createTextNode(`*,*::before,*::after{transition:none!important}`));
|
|
69
67
|
|
|
70
68
|
document.head.append(css);
|
package/src/index.ts
CHANGED
|
@@ -1,29 +1,32 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* \@codefast/theme
|
|
3
3
|
*
|
|
4
|
-
* React 19
|
|
4
|
+
* React 19 appearance management, with vocabulary following Apple's Human Interface
|
|
5
|
+
* Guidelines: **appearance** is the user's preference (light / dark / automatic),
|
|
6
|
+
* **color scheme** is the resolved light-or-dark value actually applied. Client-only
|
|
7
|
+
* `localStorage` persistence, SSR-safe `automatic` resolution, cross-tab sync,
|
|
8
|
+
* optimistic updates.
|
|
5
9
|
*
|
|
6
|
-
* - **Root** (this module): `AppearanceProvider`, `
|
|
7
|
-
* - **`@codefast/theme/
|
|
8
|
-
* - **`@codefast/theme/
|
|
9
|
-
* - **`@codefast/theme/core`**: `ColorSchemeContext` for rare custom wiring.
|
|
10
|
+
* - **Root** (this module): `AppearanceProvider`, `useAppearance`, `AppearanceScript`, `resolveColorScheme`, types, defaults.
|
|
11
|
+
* - **`@codefast/theme/color-scheme` / `@codefast/theme/dom`**: `getSystemColorScheme`, `applyColorScheme`, `suppressTransitions`.
|
|
12
|
+
* - **`@codefast/theme/appearance-context`**: `AppearanceContext` for rare custom wiring.
|
|
10
13
|
*/
|
|
11
14
|
|
|
12
15
|
// Types & Schema
|
|
13
|
-
export type {
|
|
14
|
-
export {
|
|
16
|
+
export type { Appearance, AppearanceContextType, ColorScheme } from "#/appearance";
|
|
17
|
+
export { appearances, appearanceSchema } from "#/appearance";
|
|
15
18
|
|
|
16
19
|
// Constants
|
|
17
|
-
export {
|
|
20
|
+
export { DEFAULT_APPEARANCE, DEFAULT_COLOR_SCHEME } from "#/constants";
|
|
18
21
|
|
|
19
|
-
//
|
|
20
|
-
export { AppearanceProvider } from "#/
|
|
21
|
-
export type { AppearanceProviderProps } from "#/
|
|
22
|
-
export {
|
|
22
|
+
// Provider & Hook (use `@codefast/theme/appearance-context` for `AppearanceContext`)
|
|
23
|
+
export { AppearanceProvider } from "#/appearance-provider";
|
|
24
|
+
export type { AppearanceProviderProps } from "#/appearance-provider";
|
|
25
|
+
export { useAppearance } from "#/use-appearance";
|
|
23
26
|
|
|
24
27
|
// Script (FOUC prevention)
|
|
25
|
-
export { AppearanceScript } from "#/
|
|
26
|
-
export type { AppearanceScriptProps } from "#/
|
|
28
|
+
export { AppearanceScript } from "#/appearance-script";
|
|
29
|
+
export type { AppearanceScriptProps } from "#/appearance-script";
|
|
27
30
|
|
|
28
|
-
//
|
|
29
|
-
export { resolveColorScheme } from "#/
|
|
31
|
+
// Resolution: `getSystemColorScheme` lives under `@codefast/theme/color-scheme`
|
|
32
|
+
export { resolveColorScheme } from "#/color-scheme";
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { use } from "react";
|
|
2
|
+
|
|
3
|
+
import type { AppearanceContextType } from "#/appearance";
|
|
4
|
+
import { AppearanceContext } from "#/appearance-context";
|
|
5
|
+
|
|
6
|
+
/* -----------------------------------------------------------------------------
|
|
7
|
+
* Hook
|
|
8
|
+
* -------------------------------------------------------------------------- */
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Hook to access appearance 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 Appearance context with `appearance`, `colorScheme`, `setAppearance`, and `isPending`
|
|
18
|
+
* @throws Error if called outside of AppearanceProvider
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```tsx
|
|
22
|
+
* function AppearanceToggle() {
|
|
23
|
+
* const { appearance, setAppearance, isPending } = useAppearance();
|
|
24
|
+
*
|
|
25
|
+
* return (
|
|
26
|
+
* <button
|
|
27
|
+
* onClick={() => setAppearance(appearance === 'dark' ? 'light' : 'dark')}
|
|
28
|
+
* disabled={isPending}
|
|
29
|
+
* >
|
|
30
|
+
* {appearance}
|
|
31
|
+
* </button>
|
|
32
|
+
* );
|
|
33
|
+
* }
|
|
34
|
+
* ```
|
|
35
|
+
*
|
|
36
|
+
* @since 0.5.0-canary.2
|
|
37
|
+
*/
|
|
38
|
+
export function useAppearance(): AppearanceContextType {
|
|
39
|
+
const value = use(AppearanceContext);
|
|
40
|
+
|
|
41
|
+
if (!value) {
|
|
42
|
+
throw new Error("useAppearance must be used within an AppearanceProvider");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
import { ColorScheme, ResolvedColorScheme } from "../../types.mjs";
|
|
2
|
-
|
|
3
|
-
//#region src/adapters/tanstack-start/server.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* Data shape returned from {@link getRootColorSchemeServerFn} for the root route loader.
|
|
6
|
-
*
|
|
7
|
-
* @since 0.3.16-canary.0
|
|
8
|
-
*/
|
|
9
|
-
type RootColorSchemeLoaderData = {
|
|
10
|
-
/**
|
|
11
|
-
* Resolved `light` or `dark` from the incoming request when detectable
|
|
12
|
-
* (e.g. `Sec-CH-Prefers-Color-Scheme`). Pass to `AppearanceProvider` as `ssrColorScheme` and to
|
|
13
|
-
* `resolveColorScheme(colorScheme, ssrColorScheme)` on `<html>`. When the hint is absent, matches
|
|
14
|
-
* {@link DEFAULT_RESOLVED_COLOR_SCHEME}.
|
|
15
|
-
*/
|
|
16
|
-
readonly ssrColorScheme: ResolvedColorScheme;
|
|
17
|
-
/**
|
|
18
|
-
* User preference from the httpOnly cookie: `light`, `dark`, or `automatic`.
|
|
19
|
-
*/
|
|
20
|
-
readonly colorScheme: ColorScheme;
|
|
21
|
-
};
|
|
22
|
-
/**
|
|
23
|
-
* Everything needed for the root shell in **one** server call (fewer loader awaits).
|
|
24
|
-
*
|
|
25
|
-
* In your shell: `resolveColorScheme(colorScheme, ssrColorScheme)` on `<html>`, plus `AppearanceScript` and `AppearanceProvider`.
|
|
26
|
-
*
|
|
27
|
-
* @since 0.3.16-canary.0
|
|
28
|
-
*/
|
|
29
|
-
declare const getRootColorSchemeServerFn: import("@tanstack/react-start").OptionalFetcher<undefined, undefined, RootColorSchemeLoaderData>;
|
|
30
|
-
/**
|
|
31
|
-
* Read the user's color scheme preference from cookies.
|
|
32
|
-
*
|
|
33
|
-
* Validates the cookie value using Zod schema for type safety.
|
|
34
|
-
* Returns {@link DEFAULT_COLOR_SCHEME} if cookie is missing or invalid.
|
|
35
|
-
*
|
|
36
|
-
* @returns User's stored color scheme preference or default
|
|
37
|
-
*
|
|
38
|
-
* @example
|
|
39
|
-
* ```tsx
|
|
40
|
-
* const colorScheme = await getColorSchemeServerFn();
|
|
41
|
-
* ```
|
|
42
|
-
*
|
|
43
|
-
* @since 0.3.16-canary.0
|
|
44
|
-
*/
|
|
45
|
-
declare const getColorSchemeServerFn: import("@tanstack/react-start").OptionalFetcher<undefined, undefined, "light" | "dark" | "automatic">;
|
|
46
|
-
/**
|
|
47
|
-
* Resolved OS color scheme for SSR / hydration, from Client Hints when the browser sends them.
|
|
48
|
-
*
|
|
49
|
-
* Mirrors client `matchMedia("(prefers-color-scheme: dark)")` when hints are present.
|
|
50
|
-
* Prefer {@link getRootColorSchemeServerFn} for root loaders.
|
|
51
|
-
*
|
|
52
|
-
* Send `Accept-CH: Sec-CH-Prefers-Color-Scheme` (and `Vary`) so navigations include the hint.
|
|
53
|
-
*
|
|
54
|
-
* @since 0.3.16-canary.0
|
|
55
|
-
*/
|
|
56
|
-
declare const getSsrColorSchemeServerFn: import("@tanstack/react-start").OptionalFetcher<undefined, undefined, ResolvedColorScheme>;
|
|
57
|
-
/**
|
|
58
|
-
* Persist color scheme preference to an HTTP-only cookie.
|
|
59
|
-
*
|
|
60
|
-
* **Security:**
|
|
61
|
-
* - `httpOnly: true` - Cookie cannot be accessed from JavaScript (XSS protection)
|
|
62
|
-
* - `secure: true` in production - Cookie only sent over HTTPS
|
|
63
|
-
* - `sameSite: 'lax'` - Prevents CSRF while allowing navigation
|
|
64
|
-
*
|
|
65
|
-
* **Cookie Settings:**
|
|
66
|
-
* - `maxAge: 1 year` - Preference persists across sessions
|
|
67
|
-
* - `path: '/'` - Available to all routes
|
|
68
|
-
*
|
|
69
|
-
* @param data - Color scheme to persist ('light', 'dark', or 'automatic')
|
|
70
|
-
*
|
|
71
|
-
* @see [TanStack Start Server Functions](https://tanstack.com/start/latest/docs/framework/react/server-functions)
|
|
72
|
-
*
|
|
73
|
-
* @since 0.3.16-canary.0
|
|
74
|
-
*/
|
|
75
|
-
declare const setColorSchemeServerFn: import("@tanstack/react-start").RequiredFetcher<undefined, import("zod").ZodEnum<{
|
|
76
|
-
light: "light";
|
|
77
|
-
dark: "dark";
|
|
78
|
-
automatic: "automatic";
|
|
79
|
-
}>, void>;
|
|
80
|
-
/**
|
|
81
|
-
* Default {@link AppearanceProvider} `persistColorScheme` for the Start adapter: writes the httpOnly
|
|
82
|
-
* color scheme cookie via {@link setColorSchemeServerFn}.
|
|
83
|
-
*
|
|
84
|
-
* @since 0.3.16-canary.0
|
|
85
|
-
*/
|
|
86
|
-
declare function persistColorSchemeCookie(value: ColorScheme): Promise<void>;
|
|
87
|
-
//#endregion
|
|
88
|
-
export { RootColorSchemeLoaderData, getColorSchemeServerFn, getRootColorSchemeServerFn, getSsrColorSchemeServerFn, persistColorSchemeCookie, setColorSchemeServerFn };
|
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
import { DEFAULT_COLOR_SCHEME, DEFAULT_RESOLVED_COLOR_SCHEME, STORAGE_KEY } from "../../constants.mjs";
|
|
2
|
-
import { colorSchemeSchema } from "../../types.mjs";
|
|
3
|
-
import { createServerFn } from "@tanstack/react-start";
|
|
4
|
-
import { getCookie, getRequestHeader, setCookie } from "@tanstack/react-start/server";
|
|
5
|
-
//#region src/adapters/tanstack-start/server.ts
|
|
6
|
-
function readColorSchemeFromCookie() {
|
|
7
|
-
const cookieValue = getCookie(STORAGE_KEY);
|
|
8
|
-
const validationResult = colorSchemeSchema.safeParse(cookieValue);
|
|
9
|
-
if (validationResult.success) return validationResult.data;
|
|
10
|
-
return DEFAULT_COLOR_SCHEME;
|
|
11
|
-
}
|
|
12
|
-
function readSsrColorSchemeFromHeaders() {
|
|
13
|
-
const hint = getRequestHeader("Sec-CH-Prefers-Color-Scheme") ?? getRequestHeader("Prefers-Color-Scheme");
|
|
14
|
-
if (hint === "dark") return "dark";
|
|
15
|
-
if (hint === "light") return "light";
|
|
16
|
-
return DEFAULT_RESOLVED_COLOR_SCHEME;
|
|
17
|
-
}
|
|
18
|
-
/**
|
|
19
|
-
* Everything needed for the root shell in **one** server call (fewer loader awaits).
|
|
20
|
-
*
|
|
21
|
-
* In your shell: `resolveColorScheme(colorScheme, ssrColorScheme)` on `<html>`, plus `AppearanceScript` and `AppearanceProvider`.
|
|
22
|
-
*
|
|
23
|
-
* @since 0.3.16-canary.0
|
|
24
|
-
*/
|
|
25
|
-
const getRootColorSchemeServerFn = createServerFn().handler(() => ({
|
|
26
|
-
colorScheme: readColorSchemeFromCookie(),
|
|
27
|
-
ssrColorScheme: readSsrColorSchemeFromHeaders()
|
|
28
|
-
}));
|
|
29
|
-
/**
|
|
30
|
-
* Read the user's color scheme preference from cookies.
|
|
31
|
-
*
|
|
32
|
-
* Validates the cookie value using Zod schema for type safety.
|
|
33
|
-
* Returns {@link DEFAULT_COLOR_SCHEME} if cookie is missing or invalid.
|
|
34
|
-
*
|
|
35
|
-
* @returns User's stored color scheme preference or default
|
|
36
|
-
*
|
|
37
|
-
* @example
|
|
38
|
-
* ```tsx
|
|
39
|
-
* const colorScheme = await getColorSchemeServerFn();
|
|
40
|
-
* ```
|
|
41
|
-
*
|
|
42
|
-
* @since 0.3.16-canary.0
|
|
43
|
-
*/
|
|
44
|
-
const getColorSchemeServerFn = createServerFn().handler(() => readColorSchemeFromCookie());
|
|
45
|
-
/**
|
|
46
|
-
* Resolved OS color scheme for SSR / hydration, from Client Hints when the browser sends them.
|
|
47
|
-
*
|
|
48
|
-
* Mirrors client `matchMedia("(prefers-color-scheme: dark)")` when hints are present.
|
|
49
|
-
* Prefer {@link getRootColorSchemeServerFn} for root loaders.
|
|
50
|
-
*
|
|
51
|
-
* Send `Accept-CH: Sec-CH-Prefers-Color-Scheme` (and `Vary`) so navigations include the hint.
|
|
52
|
-
*
|
|
53
|
-
* @since 0.3.16-canary.0
|
|
54
|
-
*/
|
|
55
|
-
const getSsrColorSchemeServerFn = createServerFn().handler(() => readSsrColorSchemeFromHeaders());
|
|
56
|
-
/**
|
|
57
|
-
* Persist color scheme preference to an HTTP-only cookie.
|
|
58
|
-
*
|
|
59
|
-
* **Security:**
|
|
60
|
-
* - `httpOnly: true` - Cookie cannot be accessed from JavaScript (XSS protection)
|
|
61
|
-
* - `secure: true` in production - Cookie only sent over HTTPS
|
|
62
|
-
* - `sameSite: 'lax'` - Prevents CSRF while allowing navigation
|
|
63
|
-
*
|
|
64
|
-
* **Cookie Settings:**
|
|
65
|
-
* - `maxAge: 1 year` - Preference persists across sessions
|
|
66
|
-
* - `path: '/'` - Available to all routes
|
|
67
|
-
*
|
|
68
|
-
* @param data - Color scheme to persist ('light', 'dark', or 'automatic')
|
|
69
|
-
*
|
|
70
|
-
* @see [TanStack Start Server Functions](https://tanstack.com/start/latest/docs/framework/react/server-functions)
|
|
71
|
-
*
|
|
72
|
-
* @since 0.3.16-canary.0
|
|
73
|
-
*/
|
|
74
|
-
const setColorSchemeServerFn = createServerFn({ method: "POST" }).validator(colorSchemeSchema).handler(({ data }) => {
|
|
75
|
-
setCookie(STORAGE_KEY, data, {
|
|
76
|
-
httpOnly: true,
|
|
77
|
-
maxAge: 3600 * 24 * 365,
|
|
78
|
-
path: "/",
|
|
79
|
-
sameSite: "lax",
|
|
80
|
-
secure: process.env.NODE_ENV === "production"
|
|
81
|
-
});
|
|
82
|
-
});
|
|
83
|
-
/**
|
|
84
|
-
* Default {@link AppearanceProvider} `persistColorScheme` for the Start adapter: writes the httpOnly
|
|
85
|
-
* color scheme cookie via {@link setColorSchemeServerFn}.
|
|
86
|
-
*
|
|
87
|
-
* @since 0.3.16-canary.0
|
|
88
|
-
*/
|
|
89
|
-
async function persistColorSchemeCookie(value) {
|
|
90
|
-
await setColorSchemeServerFn({ data: value });
|
|
91
|
-
}
|
|
92
|
-
//#endregion
|
|
93
|
-
export { getColorSchemeServerFn, getRootColorSchemeServerFn, getSsrColorSchemeServerFn, persistColorSchemeCookie, setColorSchemeServerFn };
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { Plugin } from "vite";
|
|
2
|
-
|
|
3
|
-
//#region src/adapters/tanstack-start/vite.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* Create the Vite plugin that lets a TanStack Start app consume `@codefast/theme`'s server
|
|
6
|
-
* functions from npm without manual `ssr.noExternal` / `optimizeDeps.exclude` configuration.
|
|
7
|
-
*
|
|
8
|
-
* @since 0.5.0-canary.0
|
|
9
|
-
*/
|
|
10
|
-
declare function codefastTheme(): Plugin;
|
|
11
|
-
//#endregion
|
|
12
|
-
export { codefastTheme };
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
//#region src/adapters/tanstack-start/vite.ts
|
|
2
|
-
const PACKAGE_NAME = "@codefast/theme";
|
|
3
|
-
/**
|
|
4
|
-
* Create the Vite plugin that lets a TanStack Start app consume `@codefast/theme`'s server
|
|
5
|
-
* functions from npm without manual `ssr.noExternal` / `optimizeDeps.exclude` configuration.
|
|
6
|
-
*
|
|
7
|
-
* @since 0.5.0-canary.0
|
|
8
|
-
*/
|
|
9
|
-
function codefastTheme() {
|
|
10
|
-
return {
|
|
11
|
-
name: "codefast:theme",
|
|
12
|
-
config() {
|
|
13
|
-
return {
|
|
14
|
-
ssr: { noExternal: [PACKAGE_NAME] },
|
|
15
|
-
optimizeDeps: { exclude: [PACKAGE_NAME] }
|
|
16
|
-
};
|
|
17
|
-
}
|
|
18
|
-
};
|
|
19
|
-
}
|
|
20
|
-
//#endregion
|
|
21
|
-
export { codefastTheme };
|
package/dist/core/context.d.mts
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import { ColorSchemeContextType } from "../types.mjs";
|
|
2
|
-
|
|
3
|
-
//#region src/core/context.d.ts
|
|
4
|
-
type ColorSchemeContextValue = null | ColorSchemeContextType;
|
|
5
|
-
/**
|
|
6
|
-
* React context for color scheme state management.
|
|
7
|
-
*
|
|
8
|
-
* Provides access to current color scheme, resolved color scheme, setter function, and pending state.
|
|
9
|
-
* Use {@link useColorScheme} hook instead of consuming this context directly.
|
|
10
|
-
*
|
|
11
|
-
* @see {@link AppearanceProvider} - Provider component
|
|
12
|
-
* @see {@link useColorScheme} - Consumer hook
|
|
13
|
-
*
|
|
14
|
-
* @since 0.3.16-canary.0
|
|
15
|
-
*/
|
|
16
|
-
declare const ColorSchemeContext: import("react").Context<ColorSchemeContextValue>;
|
|
17
|
-
//#endregion
|
|
18
|
-
export { ColorSchemeContext };
|
package/dist/core/context.mjs
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import { createContext } from "react";
|
|
2
|
-
//#region src/core/context.tsx
|
|
3
|
-
/**
|
|
4
|
-
* React context for color scheme state management.
|
|
5
|
-
*
|
|
6
|
-
* Provides access to current color scheme, resolved color scheme, setter function, and pending state.
|
|
7
|
-
* Use {@link useColorScheme} hook instead of consuming this context directly.
|
|
8
|
-
*
|
|
9
|
-
* @see {@link AppearanceProvider} - Provider component
|
|
10
|
-
* @see {@link useColorScheme} - Consumer hook
|
|
11
|
-
*
|
|
12
|
-
* @since 0.3.16-canary.0
|
|
13
|
-
*/
|
|
14
|
-
const ColorSchemeContext = createContext(null);
|
|
15
|
-
//#endregion
|
|
16
|
-
export { ColorSchemeContext };
|