ccstate-react 4.13.0 → 5.2.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/coverage/base.css +224 -0
  3. package/coverage/block-navigation.js +87 -0
  4. package/coverage/clover.xml +219 -0
  5. package/coverage/coverage-final.json +8 -0
  6. package/coverage/favicon.png +0 -0
  7. package/coverage/index.html +206 -0
  8. package/coverage/index.ts.html +100 -0
  9. package/coverage/prettify.css +1 -0
  10. package/coverage/prettify.js +2 -0
  11. package/coverage/provider.ts.html +133 -0
  12. package/coverage/sort-arrow-sprite.png +0 -0
  13. package/coverage/sorter.js +196 -0
  14. package/coverage/useGet.ts.html +160 -0
  15. package/coverage/useLoadable.ts.html +403 -0
  16. package/coverage/useLoadableSet.ts.html +295 -0
  17. package/coverage/useResolved.ts.html +133 -0
  18. package/coverage/useSet.ts.html +166 -0
  19. package/dist/experimental.cjs +92 -45
  20. package/dist/experimental.d.cts +15 -6
  21. package/dist/experimental.d.ts +15 -6
  22. package/dist/experimental.js +93 -43
  23. package/dist/index.cjs +56 -125
  24. package/dist/index.d.cts +3 -3
  25. package/dist/index.d.ts +3 -3
  26. package/dist/index.js +57 -126
  27. package/package.json +9 -9
  28. package/src/__tests__/get-and-set.test.tsx +22 -13
  29. package/src/__tests__/loadable-set.test.tsx +255 -0
  30. package/src/__tests__/loadable.test.tsx +14 -6
  31. package/src/__tests__/resolved.test.tsx +6 -1
  32. package/src/experimental.ts +1 -1
  33. package/src/provider.ts +1 -2
  34. package/src/useGet.ts +19 -6
  35. package/src/useLoadable.ts +74 -95
  36. package/src/useLoadableSet.ts +72 -0
  37. package/src/useResolved.ts +2 -2
  38. package/LICENSE +0 -21
  39. package/src/__tests__/inline-atom.test.tsx +0 -139
  40. package/src/useInlineAtom.ts +0 -40
package/src/useGet.ts CHANGED
@@ -1,12 +1,25 @@
1
- import { useSyncExternalStore } from 'react';
1
+ import { useRef, useSyncExternalStore } from 'react';
2
2
  import { useStore } from './provider';
3
- import { command } from 'ccstate';
3
+
4
4
  import type { Computed, State } from 'ccstate';
5
5
 
6
6
  export function useGet<T>(atom: State<T> | Computed<T>) {
7
7
  const store = useStore();
8
- return useSyncExternalStore(
9
- (fn) => store.sub(atom, command(fn)),
10
- () => store.get(atom),
11
- );
8
+ const onChange = useRef((fn: () => void) => {
9
+ const controller = new AbortController();
10
+ store.watch(
11
+ (get) => {
12
+ get(atom);
13
+ fn();
14
+ },
15
+ {
16
+ signal: controller.signal,
17
+ },
18
+ );
19
+ return () => {
20
+ controller.abort();
21
+ };
22
+ });
23
+
24
+ return useSyncExternalStore(onChange.current, () => store.get(atom));
12
25
  }
@@ -1,5 +1,5 @@
1
- import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
2
- import { command, type Computed, type State } from 'ccstate';
1
+ import { useCallback, useRef, useSyncExternalStore } from 'react';
2
+ import { type Computed, type State } from 'ccstate';
3
3
  import { useStore } from './provider';
4
4
 
5
5
  type Loadable<T> =
@@ -8,120 +8,99 @@ type Loadable<T> =
8
8
  }
9
9
  | {
10
10
  state: 'hasData';
11
- data: T;
11
+ data: Awaited<T>;
12
12
  }
13
13
  | {
14
14
  state: 'hasError';
15
15
  error: unknown;
16
16
  };
17
17
 
18
- /**
19
- * Handles a specific behavior of useSyncExternalStore. In React, there are situations where the getSnapshot function of
20
- * useSyncExternalStore executes, but the Render function doesn't execute.
21
- *
22
- * This can cause the promise generated in that round to not be caught, and userspace has no opportunity to handle this
23
- * promise. Therefore, this issue needs to be handled in useGetPromise.
24
- *
25
- * @param atom
26
- * @returns
27
- */
28
- function useGetPromise<T, U extends Promise<T> | T>(atom: State<U> | Computed<U>): [U, () => void] {
29
- const store = useStore();
30
- const lastPromise = useRef<Promise<unknown> | undefined>(undefined);
31
- const promiseProcessed = useRef(false);
32
-
33
- const promise = useSyncExternalStore(
34
- (fn) => store.sub(atom, command(fn)),
35
- () => {
36
- const val = store.get(atom);
37
-
38
- // If the last promise is not processed and the current value is a promise,
39
- // we need to silence the last promise to avoid unhandled rejections.
40
- if (lastPromise.current !== undefined && lastPromise.current !== val && !promiseProcessed.current) {
41
- lastPromise.current.catch(() => void 0);
42
- }
43
-
44
- if (lastPromise.current !== val) {
45
- promiseProcessed.current = false;
46
- lastPromise.current = val instanceof Promise ? val : undefined;
47
- }
48
-
49
- return val;
50
- },
51
- );
52
-
53
- return [
54
- promise,
55
- () => {
56
- promiseProcessed.current = true;
57
- },
58
- ];
59
- }
60
-
61
- function useLoadableInternal<T>(
62
- atom: State<Promise<T> | T> | Computed<Promise<T> | T>,
18
+ function useLoadableInternal<T, U extends Promise<Awaited<T>> | Awaited<T>>(
19
+ promise$: State<U> | Computed<U>,
63
20
  keepLastResolved: boolean,
64
21
  ): Loadable<T> {
65
- const [promise, setPromiseProcessed] = useGetPromise(atom);
66
- const [promiseResult, setPromiseResult] = useState<Loadable<T>>({
22
+ const promiseResult = useRef<Loadable<T>>({
67
23
  state: 'loading',
68
24
  });
69
25
 
70
- useEffect(() => {
71
- if (!(promise instanceof Promise)) {
72
- setPromiseResult({
73
- state: 'hasData',
74
- data: promise,
75
- });
76
-
77
- return;
78
- }
79
-
80
- let cancelled = false;
81
-
82
- if (!keepLastResolved) {
83
- setPromiseResult({
84
- state: 'loading',
85
- });
86
- }
87
-
88
- setPromiseProcessed();
89
-
90
- promise.then(
91
- (ret) => {
92
- if (cancelled) return;
93
-
94
- setPromiseResult({
95
- state: 'hasData',
96
- data: ret,
97
- });
98
- },
99
- (error: unknown) => {
100
- if (cancelled) return;
101
-
102
- setPromiseResult({
103
- state: 'hasError',
104
- error,
105
- });
106
- },
107
- );
26
+ const store = useStore();
27
+ const subStore = useCallback(
28
+ (fn: () => void) => {
29
+ function updateResult(result: Loadable<T>, signal: AbortSignal) {
30
+ if (signal.aborted) return;
31
+ promiseResult.current = result;
32
+ fn();
33
+ }
108
34
 
109
- return () => {
110
- cancelled = true;
111
- };
112
- }, [promise]);
35
+ const controller = new AbortController();
36
+
37
+ store.watch(
38
+ (get, { signal }) => {
39
+ const promise: Promise<Awaited<T>> | Awaited<T> = get(promise$);
40
+ if (!(promise instanceof Promise)) {
41
+ updateResult(
42
+ {
43
+ state: 'hasData',
44
+ data: promise,
45
+ },
46
+ signal,
47
+ );
48
+ return;
49
+ }
50
+
51
+ if (!keepLastResolved) {
52
+ updateResult(
53
+ {
54
+ state: 'loading',
55
+ },
56
+ signal,
57
+ );
58
+ }
59
+
60
+ promise.then(
61
+ (ret) => {
62
+ updateResult(
63
+ {
64
+ state: 'hasData',
65
+ data: ret,
66
+ },
67
+ signal,
68
+ );
69
+ },
70
+ (error: unknown) => {
71
+ updateResult(
72
+ {
73
+ state: 'hasError',
74
+ error,
75
+ },
76
+ signal,
77
+ );
78
+ },
79
+ );
80
+ },
81
+ {
82
+ signal: controller.signal,
83
+ },
84
+ );
85
+
86
+ return () => {
87
+ controller.abort();
88
+ };
89
+ },
90
+ [store, promise$],
91
+ );
113
92
 
114
- return promiseResult;
93
+ return useSyncExternalStore(subStore, () => promiseResult.current);
115
94
  }
116
95
 
117
96
  export function useLoadable<T>(
118
97
  atom: State<Promise<Awaited<T>> | Awaited<T>> | Computed<Promise<Awaited<T>> | Awaited<T>>,
119
- ): Loadable<Awaited<T>> {
98
+ ): Loadable<T> {
120
99
  return useLoadableInternal(atom, false);
121
100
  }
122
101
 
123
102
  export function useLastLoadable<T>(
124
103
  atom: State<Promise<Awaited<T>> | Awaited<T>> | Computed<Promise<Awaited<T>> | Awaited<T>>,
125
- ): Loadable<Awaited<T>> {
104
+ ): Loadable<T> {
126
105
  return useLoadableInternal(atom, true);
127
106
  }
@@ -0,0 +1,72 @@
1
+ import { useCallback, useRef, useSyncExternalStore } from 'react';
2
+ import { type Command, type State, type StateArg } from 'ccstate';
3
+ import { useStore } from './provider';
4
+
5
+ type LoadableSetResult<T> =
6
+ | { state: 'idle' }
7
+ | { state: 'loading' }
8
+ | { state: 'hasData'; data: Awaited<T> }
9
+ | { state: 'hasError'; error: unknown };
10
+
11
+ export function useLoadableSet<T>(signal: State<T>): [LoadableSetResult<void>, (val: StateArg<T>) => void];
12
+ export function useLoadableSet<T, CommandArgs extends unknown[]>(
13
+ signal: Command<T, CommandArgs>,
14
+ ): [LoadableSetResult<Awaited<T>>, (...args: CommandArgs) => T];
15
+ export function useLoadableSet<T, CommandArgs extends unknown[]>(
16
+ signal: State<T> | Command<T, CommandArgs>,
17
+ ): [LoadableSetResult<unknown>, (...args: unknown[]) => unknown] {
18
+ const store = useStore();
19
+ const resultRef = useRef<LoadableSetResult<unknown>>({ state: 'idle' });
20
+ const notifyRef = useRef<(() => void) | null>(null);
21
+ const controllerRef = useRef<AbortController | null>(null);
22
+
23
+ const subscribe = useCallback((notify: () => void) => {
24
+ notifyRef.current = notify;
25
+ return () => {
26
+ notifyRef.current = null;
27
+ controllerRef.current?.abort();
28
+ };
29
+ }, []);
30
+
31
+ const invoke = useCallback(
32
+ (...args: unknown[]) => {
33
+ controllerRef.current?.abort();
34
+ const controller = new AbortController();
35
+ controllerRef.current = controller;
36
+ const { signal: abortSignal } = controller;
37
+
38
+ function updateResult(result: LoadableSetResult<unknown>) {
39
+ if (abortSignal.aborted) return;
40
+ resultRef.current = result;
41
+ notifyRef.current?.();
42
+ }
43
+
44
+ if ('write' in signal) {
45
+ const result = store.set(signal, ...(args as CommandArgs));
46
+ if (result instanceof Promise) {
47
+ updateResult({ state: 'loading' });
48
+ void result.then(
49
+ (data: unknown) => {
50
+ updateResult({ state: 'hasData', data });
51
+ },
52
+ (error: unknown) => {
53
+ updateResult({ state: 'hasError', error });
54
+ },
55
+ );
56
+ } else {
57
+ updateResult({ state: 'hasData', data: result });
58
+ }
59
+ return result;
60
+ } else {
61
+ store.set(signal, ...(args as [StateArg<T>]));
62
+ updateResult({ state: 'hasData', data: undefined });
63
+ return undefined;
64
+ }
65
+ },
66
+ [store, signal],
67
+ );
68
+
69
+ const loadable = useSyncExternalStore(subscribe, () => resultRef.current);
70
+
71
+ return [loadable, invoke];
72
+ }
@@ -4,13 +4,13 @@ import type { Computed, State } from 'ccstate';
4
4
  export function useResolved<T>(
5
5
  atom: State<Promise<Awaited<T>> | Awaited<T>> | Computed<Promise<Awaited<T>> | Awaited<T>>,
6
6
  ): Awaited<T> | undefined {
7
- const loadable = useLoadable(atom);
7
+ const loadable = useLoadable<T>(atom);
8
8
  return loadable.state === 'hasData' ? loadable.data : undefined;
9
9
  }
10
10
 
11
11
  export function useLastResolved<T>(
12
12
  atom: State<Promise<Awaited<T>> | Awaited<T>> | Computed<Promise<Awaited<T>> | Awaited<T>>,
13
13
  ): Awaited<T> | undefined {
14
- const loadable = useLastLoadable(atom);
14
+ const loadable = useLastLoadable<T>(atom);
15
15
  return loadable.state === 'hasData' ? loadable.data : undefined;
16
16
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2019 e7h4n
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN EFFECT OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
@@ -1,139 +0,0 @@
1
- import { afterEach, expect, it } from 'vitest';
2
- import { StoreProvider, useGet, useSet } from '..';
3
- import '@testing-library/jest-dom/vitest';
4
- import { screen, cleanup, render } from '@testing-library/react';
5
- import { StrictMode } from 'react';
6
- import userEvent from '@testing-library/user-event';
7
- import { useCCState, useCommand, useComputed, useSub } from '../experimental';
8
- import { createDebugStore } from 'ccstate';
9
-
10
- afterEach(() => {
11
- cleanup();
12
- });
13
- const user = userEvent.setup();
14
-
15
- it('use atom in React component', async () => {
16
- function Counter() {
17
- const count$ = useCCState(0, {
18
- debugLabel: 'count$',
19
- });
20
- const double$ = useComputed(
21
- (get) => {
22
- return get(count$) * 2;
23
- },
24
- {
25
- debugLabel: 'double$',
26
- },
27
- );
28
- const incrementTriple$ = useCommand(
29
- ({ get, set }, diff: number) => {
30
- set(count$, get(count$) + diff * 3);
31
- },
32
- {
33
- debugLabel: 'incrementTriple$',
34
- },
35
- );
36
-
37
- const count = useGet(count$);
38
- const double = useGet(double$);
39
-
40
- const setCount = useSet(count$);
41
- const incrementTriple = useSet(incrementTriple$);
42
-
43
- return (
44
- <>
45
- <div>count: {String(count)}</div>
46
- <div>double: {String(double)}</div>
47
- <button
48
- onClick={() => {
49
- setCount((prev) => prev + 1);
50
- }}
51
- >
52
- Increment
53
- </button>
54
- <button
55
- onClick={() => {
56
- incrementTriple(1);
57
- }}
58
- >
59
- Increment Triple
60
- </button>
61
- </>
62
- );
63
- }
64
-
65
- render(
66
- <StrictMode>
67
- <Counter />
68
- </StrictMode>,
69
- );
70
- expect(screen.getByText('count: 0')).toBeInTheDocument();
71
-
72
- const button = screen.getByText('Increment');
73
- await user.click(button);
74
- expect(screen.getByText('count: 1')).toBeInTheDocument();
75
- expect(screen.getByText('double: 2')).toBeInTheDocument();
76
-
77
- const incrementTripleButton = screen.getByText('Increment Triple');
78
- await user.click(incrementTripleButton);
79
- expect(screen.getByText('count: 4')).toBeInTheDocument();
80
- expect(screen.getByText('double: 8')).toBeInTheDocument();
81
- });
82
-
83
- it('use sub in React component', async () => {
84
- function Counter() {
85
- const count$ = useCCState(0, {
86
- debugLabel: 'count$',
87
- });
88
- const double$ = useCCState(0, {
89
- debugLabel: 'double$',
90
- });
91
-
92
- const updateDouble$ = useCommand(
93
- ({ get, set }) => {
94
- const double = get(count$) * 2;
95
- set(double$, double);
96
- },
97
- {
98
- debugLabel: 'updateDouble$',
99
- },
100
- );
101
- useSub(count$, updateDouble$);
102
-
103
- const count = useGet(count$);
104
- const double = useGet(double$);
105
- const setCount = useSet(count$);
106
-
107
- return (
108
- <>
109
- <div>count: {String(count)}</div>
110
- <div>double: {String(double)}</div>
111
- <button
112
- onClick={() => {
113
- setCount((prev) => prev + 1);
114
- }}
115
- >
116
- Increment
117
- </button>
118
- </>
119
- );
120
- }
121
-
122
- const store = createDebugStore();
123
- render(
124
- <StrictMode>
125
- <StoreProvider value={store}>
126
- <Counter />
127
- </StoreProvider>
128
- </StrictMode>,
129
- );
130
- expect(screen.getByText('count: 0')).toBeInTheDocument();
131
-
132
- const button = screen.getByText('Increment');
133
- await user.click(button);
134
- expect(screen.getByText('count: 1')).toBeInTheDocument();
135
- expect(await screen.findByText('double: 2')).toBeInTheDocument();
136
-
137
- cleanup();
138
- expect(store.getSubscribeGraph()).toEqual([]);
139
- });
@@ -1,40 +0,0 @@
1
- import { command, computed, state, type Command, type Computed, type State, type Subscribe } from 'ccstate';
2
- import { useEffect, useRef } from 'react';
3
- import { useStore } from './provider';
4
-
5
- function useRefFactory<T>(factory: () => T): T {
6
- const ref = useRef<T | null>(null);
7
- if (!ref.current) {
8
- const value = factory();
9
- ref.current = value;
10
- return value;
11
- }
12
-
13
- return ref.current;
14
- }
15
-
16
- export function useCCState<T>(...args: Parameters<typeof state<T>>): State<T> {
17
- return useRefFactory<State<T>>(() => {
18
- return state(...args);
19
- });
20
- }
21
-
22
- export function useComputed<T>(...args: Parameters<typeof computed<T>>): Computed<T> {
23
- return useRefFactory<Computed<T>>(() => {
24
- return computed(...args);
25
- });
26
- }
27
-
28
- export function useCommand<T, Args extends unknown[]>(...args: Parameters<typeof command<T, Args>>): Command<T, Args> {
29
- return useRefFactory<Command<T, Args>>(() => {
30
- return command(...args);
31
- });
32
- }
33
-
34
- export function useSub(...args: Parameters<Subscribe>) {
35
- const store = useStore();
36
-
37
- useEffect(() => {
38
- return store.sub(...args);
39
- }, []);
40
- }