react-native-theme-transition 1.0.2 → 1.0.4

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.
@@ -1,92 +1,92 @@
1
- /**
2
- * Factory that wires the theme transition provider, context, and hooks.
3
- *
4
- * @remarks
5
- * Validates theme configuration at initialization: ensures at least one theme
6
- * exists and that all themes share identical token keys.
7
- * Returns a self-contained API ({@link ThemeTransitionAPI}) with no singletons,
8
- * so multiple theme scopes can coexist in the same app.
9
- *
10
- * @module
11
- */
12
-
13
- import type {
14
- ThemeTransitionAPI,
15
- ThemeTransitionConfig,
16
- ThemeDefinition,
17
- ThemeNames,
18
- } from './types';
19
- import { createProviderAndContext } from './transitionEngine';
20
- import { createUseTheme } from './hooks/useTheme';
21
- import { TAG } from './constants';
22
-
23
- /**
24
- * Creates a fully typed theme transition system.
25
- *
26
- * @typeParam T - Your application's theme map, keyed by theme name.
27
- * @param config - Theme configuration including available themes and defaults.
28
- * @returns A provider component and hooks scoped to the supplied themes.
29
- *
30
- * @example
31
- * ```tsx
32
- * const { ThemeTransitionProvider, useTheme } = createThemeTransition({
33
- * themes: { light: { bg: '#fff' }, dark: { bg: '#000' } },
34
- * });
35
- * ```
36
- */
37
- export function createThemeTransition<
38
- T extends Record<string, ThemeDefinition>,
39
- >(config: ThemeTransitionConfig<T>): ThemeTransitionAPI<T> {
40
- const themeNames = Object.keys(config.themes) as ThemeNames<T>[];
41
-
42
- if (themeNames.length === 0) {
43
- throw new Error(`${TAG} \`themes\` must contain at least one theme.`);
44
- }
45
-
46
- if ('system' in config.themes) {
47
- throw new Error(
48
- `${TAG} \`"system"\` is a reserved name and cannot be used as a theme key. Rename the theme and use \`systemThemeMap\` to map OS appearance to it.`,
49
- );
50
- }
51
-
52
- const referenceTheme = themeNames[0];
53
- const referenceKeys = Object.keys(config.themes[referenceTheme]).sort();
54
- for (const name of themeNames) {
55
- if (name === referenceTheme) continue;
56
- const keys = Object.keys(config.themes[name]).sort();
57
- if (keys.length !== referenceKeys.length || keys.some((k, i) => k !== referenceKeys[i])) {
58
- throw new Error(
59
- `${TAG} Theme "${name}" has different token keys than "${referenceTheme}". All themes must share identical keys.`,
60
- );
61
- }
62
- }
63
-
64
- if (config.duration != null && (typeof config.duration !== 'number' || !isFinite(config.duration) || config.duration < 0)) {
65
- throw new Error(
66
- `${TAG} \`duration\` must be a finite non-negative number.`,
67
- );
68
- }
69
-
70
- if (config.systemThemeMap) {
71
- if (!('light' in config.systemThemeMap) || !('dark' in config.systemThemeMap)) {
72
- throw new Error(
73
- `${TAG} \`systemThemeMap\` must provide both \`light\` and \`dark\` keys.`,
74
- );
75
- }
76
-
77
- for (const [scheme, name] of Object.entries(config.systemThemeMap)) {
78
- if (!(name in config.themes)) {
79
- throw new Error(
80
- `${TAG} \`systemThemeMap.${scheme}\` maps to "${name}" which does not exist in themes.`,
81
- );
82
- }
83
- }
84
- }
85
-
86
- const { Context, ThemeTransitionProvider } = createProviderAndContext(config);
87
-
88
- return {
89
- ThemeTransitionProvider,
90
- useTheme: createUseTheme<T>(Context),
91
- };
92
- }
1
+ /**
2
+ * Factory that wires the theme transition provider, context, and hooks.
3
+ *
4
+ * @remarks
5
+ * Validates theme configuration at initialization: ensures at least one theme
6
+ * exists and that all themes share identical token keys.
7
+ * Returns a self-contained API ({@link ThemeTransitionAPI}) with no singletons,
8
+ * so multiple theme scopes can coexist in the same app.
9
+ *
10
+ * @module
11
+ */
12
+
13
+ import type {
14
+ ThemeTransitionAPI,
15
+ ThemeTransitionConfig,
16
+ ThemeDefinition,
17
+ ThemeNames,
18
+ } from './types';
19
+ import { createProviderAndContext } from './transitionEngine';
20
+ import { createUseTheme } from './hooks/useTheme';
21
+ import { TAG } from './constants';
22
+
23
+ /**
24
+ * Creates a fully typed theme transition system.
25
+ *
26
+ * @typeParam T - Your application's theme map, keyed by theme name.
27
+ * @param config - Theme configuration including available themes and defaults.
28
+ * @returns A provider component and hooks scoped to the supplied themes.
29
+ *
30
+ * @example
31
+ * ```tsx
32
+ * const { ThemeTransitionProvider, useTheme } = createThemeTransition({
33
+ * themes: { light: { bg: '#fff' }, dark: { bg: '#000' } },
34
+ * });
35
+ * ```
36
+ */
37
+ export function createThemeTransition<
38
+ T extends Record<string, ThemeDefinition>,
39
+ >(config: ThemeTransitionConfig<T>): ThemeTransitionAPI<T> {
40
+ const themeNames = Object.keys(config.themes) as ThemeNames<T>[];
41
+
42
+ if (themeNames.length === 0) {
43
+ throw new Error(`${TAG} \`themes\` must contain at least one theme.`);
44
+ }
45
+
46
+ if ('system' in config.themes) {
47
+ throw new Error(
48
+ `${TAG} \`"system"\` is a reserved name and cannot be used as a theme key. Rename the theme and use \`systemThemeMap\` to map OS appearance to it.`,
49
+ );
50
+ }
51
+
52
+ const referenceTheme = themeNames[0];
53
+ const referenceKeys = Object.keys(config.themes[referenceTheme]).sort();
54
+ for (const name of themeNames) {
55
+ if (name === referenceTheme) continue;
56
+ const keys = Object.keys(config.themes[name]).sort();
57
+ if (keys.length !== referenceKeys.length || keys.some((k, i) => k !== referenceKeys[i])) {
58
+ throw new Error(
59
+ `${TAG} Theme "${name}" has different token keys than "${referenceTheme}". All themes must share identical keys.`,
60
+ );
61
+ }
62
+ }
63
+
64
+ if (config.duration != null && (typeof config.duration !== 'number' || !isFinite(config.duration) || config.duration < 0)) {
65
+ throw new Error(
66
+ `${TAG} \`duration\` must be a finite non-negative number.`,
67
+ );
68
+ }
69
+
70
+ if (config.systemThemeMap) {
71
+ if (!('light' in config.systemThemeMap) || !('dark' in config.systemThemeMap)) {
72
+ throw new Error(
73
+ `${TAG} \`systemThemeMap\` must provide both \`light\` and \`dark\` keys.`,
74
+ );
75
+ }
76
+
77
+ for (const [scheme, name] of Object.entries(config.systemThemeMap)) {
78
+ if (!(name in config.themes)) {
79
+ throw new Error(
80
+ `${TAG} \`systemThemeMap.${scheme}\` maps to "${name}" which does not exist in themes.`,
81
+ );
82
+ }
83
+ }
84
+ }
85
+
86
+ const { Context, ThemeTransitionProvider } = createProviderAndContext(config);
87
+
88
+ return {
89
+ ThemeTransitionProvider,
90
+ useTheme: createUseTheme<T>(Context),
91
+ };
92
+ }
@@ -1,88 +1,77 @@
1
- import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
2
- import type { Context } from 'react';
3
- import type {
4
- UseThemeResult,
5
- ThemeSelectionResult,
6
- ThemeDefinition,
7
- ThemeNames,
8
- TokenNames,
9
- } from '../types';
10
- import { TAG } from '../constants';
11
-
12
- /**
13
- * Factory that produces the `useTheme` hook bound to a specific context.
14
- *
15
- * @internal Used by {@link createThemeTransition}; not part of the public API.
16
- */
17
- export function createUseTheme<T extends Record<string, ThemeDefinition>>(
18
- Ctx: Context<UseThemeResult<TokenNames<T>, ThemeNames<T>> | null>,
19
- ) {
20
- type Tokens = TokenNames<T>;
21
- type Names = ThemeNames<T>;
22
- type BaseResult = UseThemeResult<Tokens, Names>;
23
- type FullResult = BaseResult & ThemeSelectionResult<Names>;
24
-
25
- function useTheme(): BaseResult;
26
- function useTheme(options: { initialSelection?: Names | 'system' }): FullResult;
27
- function useTheme(options?: { initialSelection?: Names | 'system' }): BaseResult | FullResult {
28
- const ctx = useContext(Ctx);
29
- if (!ctx) {
30
- throw new Error(
31
- `${TAG} \`useTheme\` must be used inside a \`ThemeTransitionProvider\`.`,
32
- );
33
- }
34
-
35
- const { setTheme, isTransitioning } = ctx;
36
-
37
- // Selection state — hooks are always called to satisfy React's rules of hooks.
38
- // Only exposed in the return value when options are provided.
39
- const [selected, setSelected] = useState<Names | 'system'>(
40
- () => options?.initialSelection ?? ctx.name,
41
- );
42
- const pressLockRef = useRef(false);
43
- // Ref tracks latest `selected` so the callback can read it without
44
- // `selected` being a dependency — avoids recreating `select` on every change.
45
- const selectedRef = useRef(selected);
46
- selectedRef.current = selected;
47
-
48
- useEffect(() => {
49
- if (!isTransitioning) pressLockRef.current = false;
50
- }, [isTransitioning]);
51
-
52
- const select = useCallback(
53
- (option: Names | 'system') => {
54
- if (pressLockRef.current) return;
55
- pressLockRef.current = true;
56
- const previousSelected = selectedRef.current;
57
- // Paint the new highlight FIRST. Deferring setTheme to the next frame
58
- // guarantees React commits + native paint before the library captures.
59
- setSelected(option);
60
- requestAnimationFrame(() => {
61
- if (!setTheme(option)) {
62
- // Rejected (same theme or already transitioning) — restore the prior selection.
63
- setSelected(previousSelected);
64
- }
65
- // Always release: the blocker view (isBlocking) handles touch
66
- // prevention during transitions at the native level.
67
- pressLockRef.current = false;
68
- });
69
- },
70
- [setTheme],
71
- );
72
-
73
- // Memoize the extended result so consumers using selection tracking
74
- // don't get a new object reference on every render (which would defeat
75
- // the context-level useMemo in the provider).
76
- const selectionResult = useMemo(
77
- () => ({ ...ctx, selected, select }),
78
- [ctx, selected, select],
79
- );
80
-
81
- if (options != null) {
82
- return selectionResult;
83
- }
84
- return ctx;
85
- }
86
-
87
- return useTheme;
88
- }
1
+ import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
2
+ import type { Context } from 'react';
3
+ import type {
4
+ UseThemeResult,
5
+ ThemeSelectionResult,
6
+ ThemeDefinition,
7
+ ThemeNames,
8
+ TokenNames,
9
+ } from '../types';
10
+ import { TAG } from '../constants';
11
+
12
+ /**
13
+ * Factory that produces the `useTheme` hook bound to a specific context.
14
+ *
15
+ * @internal Used by {@link createThemeTransition}; not part of the public API.
16
+ */
17
+ export function createUseTheme<T extends Record<string, ThemeDefinition>>(
18
+ Ctx: Context<UseThemeResult<TokenNames<T>, ThemeNames<T>> | null>,
19
+ ) {
20
+ type Tokens = TokenNames<T>;
21
+ type Names = ThemeNames<T>;
22
+ type BaseResult = UseThemeResult<Tokens, Names>;
23
+ type FullResult = BaseResult & ThemeSelectionResult<Names>;
24
+
25
+ function useTheme(): BaseResult;
26
+ function useTheme(options: { initialSelection?: Names | 'system' }): FullResult;
27
+ function useTheme(options?: { initialSelection?: Names | 'system' }): BaseResult | FullResult {
28
+ const ctx = useContext(Ctx);
29
+ if (!ctx) {
30
+ throw new Error(
31
+ `${TAG} \`useTheme\` must be used inside a \`ThemeTransitionProvider\`.`,
32
+ );
33
+ }
34
+
35
+ const { setTheme, isTransitioning } = ctx;
36
+
37
+ // Always called (rules of hooks) — only exposed when options are provided.
38
+ const [selected, setSelected] = useState<Names | 'system'>(
39
+ () => options?.initialSelection ?? ctx.name,
40
+ );
41
+ const pressLockRef = useRef(false);
42
+ // Ref avoids `selected` as a dependency — keeps `select` stable across renders.
43
+ const selectedRef = useRef(selected);
44
+ selectedRef.current = selected;
45
+
46
+ useEffect(() => {
47
+ if (!isTransitioning) pressLockRef.current = false;
48
+ }, [isTransitioning]);
49
+
50
+ const select = useCallback(
51
+ (option: Names | 'system') => {
52
+ if (pressLockRef.current) return;
53
+ pressLockRef.current = true;
54
+ const previousSelected = selectedRef.current;
55
+ // Paint highlight first — deferred setTheme lets React commit before capture.
56
+ setSelected(option);
57
+ requestAnimationFrame(() => {
58
+ if (!setTheme(option)) setSelected(previousSelected);
59
+ pressLockRef.current = false;
60
+ });
61
+ },
62
+ [setTheme],
63
+ );
64
+
65
+ const selectionResult = useMemo(
66
+ () => ({ ...ctx, selected, select }),
67
+ [ctx, selected, select],
68
+ );
69
+
70
+ if (options != null) {
71
+ return selectionResult;
72
+ }
73
+ return ctx;
74
+ }
75
+
76
+ return useTheme;
77
+ }
package/src/index.ts CHANGED
@@ -1,29 +1,29 @@
1
- /**
2
- * Public entry point for react-native-theme-transition.
3
- *
4
- * @remarks
5
- * The transition mechanism works in five steps:
6
- * 1. Blocks touch input via a Reanimated shared value (instant, no React re-render).
7
- * 2. Captures the current native view via `react-native-view-shot`.
8
- * 3. Overlays the snapshot as an absolute-positioned `Image` (`onLoad` confirms decode).
9
- * 4. Mutates context to inject new theme colors underneath.
10
- * 5. Fades the overlay to zero via `react-native-reanimated` — the native repaint
11
- * completes during the first frames while the overlay is still near-opaque.
12
- *
13
- * @see {@link createThemeTransition} for the main API surface.
14
- * @packageDocumentation
15
- */
16
-
17
- export { createThemeTransition } from './createThemeTransition';
18
-
19
- export type {
20
- ThemeTransitionConfig,
21
- ThemeTransitionAPI,
22
- UseThemeResult,
23
- ThemeSelectionResult,
24
- SystemThemeMap,
25
- SetThemeOptions,
26
- ThemeDefinition,
27
- ThemeNames,
28
- TokenNames,
29
- } from './types';
1
+ /**
2
+ * Public entry point for react-native-theme-transition.
3
+ *
4
+ * @remarks
5
+ * The transition mechanism works in five steps:
6
+ * 1. Blocks touch input via a Reanimated shared value (instant, no React re-render).
7
+ * 2. Captures the current native view via `react-native-view-shot`.
8
+ * 3. Overlays the snapshot as an absolute-positioned `Image` (`onLoad` confirms decode).
9
+ * 4. Mutates context to inject new theme colors underneath.
10
+ * 5. Fades the overlay to zero via `react-native-reanimated` — the native repaint
11
+ * completes during the first frames while the overlay is still near-opaque.
12
+ *
13
+ * @see {@link createThemeTransition} for the main API surface.
14
+ * @packageDocumentation
15
+ */
16
+
17
+ export { createThemeTransition } from './createThemeTransition';
18
+
19
+ export type {
20
+ ThemeTransitionConfig,
21
+ ThemeTransitionAPI,
22
+ UseThemeResult,
23
+ ThemeSelectionResult,
24
+ SystemThemeMap,
25
+ SetThemeOptions,
26
+ ThemeDefinition,
27
+ ThemeNames,
28
+ TokenNames,
29
+ } from './types';