small-state-react 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 qyvvy
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 ACTION 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.
package/README.ja.md ADDED
@@ -0,0 +1,44 @@
1
+ # small-state-react
2
+
3
+ [small\-state](https://github.com/qyvvy/small-state) の React カスタムフック、および、[Jotai](https://github.com/pmndrs/jotai) の React 拡張。
4
+
5
+ ## Installation
6
+
7
+ ```
8
+ npm i small-state-react
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Import from "./small-state-react"
14
+
15
+ #### `useRuntime(machine, options?)`
16
+
17
+ `<M extends AnyMachine>(machine: M, options?: RuntimeOptions<M> & { onPreStart?: (runtime: Runtime<M>) => void }) => {snapshot, send, runtime}`
18
+
19
+ - マシンを受け取り、ランタイムとして start させ、 `{snapshot, send, runtime}` のオブジェクトを返す。
20
+ - オプション引数は一番最初の呼び出しに与えられた引数のみが使われる。インラインで指定されて参照が変わっても同一の値と見なすためである。
21
+ - オプション `onPreStart` はランタイムが start される直前に実行されるフック関数であり、マシンから作られたランタイムを引数に受け取る。
22
+ - `.onEmitted` や `.subscribe` を実行するのに使うと良い。
23
+
24
+
25
+ #### `useSelectedSnapshot(runtime, selector, compare?)`
26
+
27
+ `<M extends AnyMachine, Sel>(runtime: Runtime<M>, selector: (snapshot: Snapshot<M>)=>Sel, compare?: (current: Sel, next: Sel)=>boolean) => Sel`
28
+
29
+ - ランタイムを受け取り、そのランタイムのスナップショットを `selector` で加工したスナップショットを返す。
30
+ - スナップショットの一部の値だけ利用・監視したいときなどに使う。
31
+ - 引数 compare は selection の旧値と新値を比較する関数である。 true なら同一と見なし再レンダリングを抑制する。 false なら更新を反映する。省略時は `===` による同一性比較である。
32
+
33
+
34
+ ### Import from "./small-state-react/jotai"
35
+
36
+ #### `atomWithRuntimeSnapshot(machine, options?)`
37
+
38
+ `<M extends AnyMachine>(machine: M | ((get:Getter)=>M), options?: RuntimeOptions<M> & { onPreStart?: (runtime: Runtime<M>) => void }) => WritableAtom<Snapshot<M>, [event: SendFnEvent<M>], void>`
39
+
40
+ - 指定したマシンについての atom を返す。
41
+ - これはどこかでマウントされたときランタイム化され起動される。どこにもマウントされなくなったとき、このランタイムは破棄される。
42
+ - `useAtom` に渡して戻ってくる値は `[snapshot, send]` である。
43
+ - オプション `onPreStart` はランタイムが start される直前に実行されるフック関数であり、マシンから作られたランタイムを引数に受け取る。
44
+ - `.onEmitted` や `.subscribe` を実行するのに使うと良い。
package/README.md CHANGED
@@ -1,3 +1,47 @@
1
- # Temporary Holding Version
1
+ # small-state-react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ This README.md was automatically translated from the Japanese version and may contain inaccuracies. For accurate information, please refer to [the Japanese version](https://github.com/qyvvy/small-state-react/blob/main/README.ja.md).
4
+
5
+ ---
6
+
7
+ React custom hooks for [small\-state](https://github.com/qyvvy/small-state), and React extensions for [Jotai](https://github.com/pmndrs/jotai).
8
+
9
+
10
+ ## Installation
11
+
12
+ ```
13
+ npm i small-state-react
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ ### Import from "./small-state-react"
19
+
20
+ #### `useRuntime(machine, options?)`
21
+
22
+ `<M extends AnyMachine>(machine: M, options?: RuntimeOptions<M> & { onPreStart?: (runtime: Runtime<M>) => void }) => {snapshot, send, runtime}`
23
+
24
+ - Accepts a machine, starts it as a Runtime, and returns an `{snapshot, send, runtime}` object.
25
+ - Only the options passed to the initial call are used. Even if the options are specified inline and their references change between renders, they are treated as the same values.
26
+ - The `onPreStart` option is a hook function that is called immediately before the runtime starts. It receives `runtime` as an argument.
27
+ - This is useful for registering `.onEmitted` or `.subscribe` handlers.
28
+
29
+
30
+ #### `useSelectedSnapshot(runtime, selector, compare?)`
31
+
32
+ `<M extends AnyMachine, Sel>(runtime: Runtime<M>, selector: (snapshot: Snapshot<M>)=>Sel, compare?: (current: Sel, next: Sel)=>boolean) => Sel`
33
+
34
+ - Accepts a runtime and returns a snapshot processed by the `selector`.
35
+ - Useful when you want to use or monitor only a specific part of the snapshot values.
36
+ - The compare argument is a function that compares the old and new values of the selection. If true, they are considered identical and re-rendering is suppressed. If false, the update is applied. If omitted, identity comparison (===) is used.
37
+
38
+
39
+ ### Import from "./small-state-react/jotai"
40
+
41
+ #### `atomWithRuntimeSnapshot(machine, options?)`
42
+
43
+ `<M extends AnyMachine>(machine: M | ((get:Getter)=>M), options?: RuntimeOptions<M>) => WritableAtom<Snapshot<M>, [event: SendFnEvent<M>], void>`
44
+
45
+ - Returns an atom for the specified machine.
46
+ - It is initialized as a runtime and started when mounted somewhere. When it is no longer mounted anywhere, the runtime is destroyed.
47
+ - The values returned when passed to `useAtom` are `[snapshot, send]`.
package/dist/index.cjs ADDED
@@ -0,0 +1,39 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let react = require("react");
3
+ let small_state = require("small-state");
4
+ let use_sync_external_store_with_selector = require("use-sync-external-store/with-selector");
5
+ // src/react/useRuntime.ts
6
+ function useRuntime(machine, options) {
7
+ if (!(0, small_state.isMachine)(machine)) throw new Error(`useRuntime() expects Machine object.`);
8
+ const qOptions = (0, react.useMemo)(() => options, []);
9
+ const runtime = (0, react.useMemo)(() => (0, small_state.makeRuntime)(machine, qOptions), [machine, qOptions]);
10
+ const subscribe = (0, react.useCallback)((onStoreChange) => {
11
+ return runtime.subscribe(onStoreChange, onStoreChange);
12
+ }, [runtime]);
13
+ const getSnapshot = (0, react.useCallback)(() => runtime?.getSnapshot(), [runtime]);
14
+ const snapshot = (0, react.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
15
+ (0, react.useEffect)(() => {
16
+ qOptions?.onPreStart?.(runtime);
17
+ runtime.start();
18
+ return () => {
19
+ runtime.stop();
20
+ };
21
+ }, [runtime, qOptions]);
22
+ return {
23
+ snapshot,
24
+ send: runtime.send.bind(runtime),
25
+ runtime
26
+ };
27
+ }
28
+ // src/react/useSelectedSnapshot.ts
29
+ const DEFAULT_COMPARE = (a, b) => a === b;
30
+ function useSelectedSnapshot(runtime, selector, compare = DEFAULT_COMPARE) {
31
+ const subscribe = (0, react.useCallback)((onStoreChange) => {
32
+ if (!runtime) return () => {};
33
+ return runtime.subscribe(onStoreChange, onStoreChange);
34
+ }, [runtime]);
35
+ const getSnapshot = (0, react.useCallback)(() => runtime?.getSnapshot(), [runtime]);
36
+ return (0, use_sync_external_store_with_selector.useSyncExternalStoreWithSelector)(subscribe, getSnapshot, getSnapshot, selector, compare);
37
+ }
38
+ exports.useRuntime = useRuntime;
39
+ exports.useSelectedSnapshot = useSelectedSnapshot;
@@ -0,0 +1,9 @@
1
+ import { AnyMachine, Runtime, RuntimeOptions, Snapshot } from "small-state";
2
+ export declare function useRuntime<M extends AnyMachine>(machine: M, options?: RuntimeOptions<M> & {
3
+ onPreStart?: (runtime: Runtime<M>) => void;
4
+ }): {
5
+ snapshot: import("small-state").Snapshot<M>;
6
+ send: (event: import("small-state").SendFnEvent<M>) => Runtime<M>;
7
+ runtime: Runtime<M>;
8
+ };
9
+ export declare function useSelectedSnapshot<M extends AnyMachine, Sel>(runtime: Runtime<M> | undefined, selector: (snapshot: Snapshot<M>) => Sel, compare?: (current: Sel, next: Sel) => boolean): Sel;
@@ -0,0 +1,9 @@
1
+ import { AnyMachine, Runtime, RuntimeOptions, Snapshot } from "small-state";
2
+ export declare function useRuntime<M extends AnyMachine>(machine: M, options?: RuntimeOptions<M> & {
3
+ onPreStart?: (runtime: Runtime<M>) => void;
4
+ }): {
5
+ snapshot: import("small-state").Snapshot<M>;
6
+ send: (event: import("small-state").SendFnEvent<M>) => Runtime<M>;
7
+ runtime: Runtime<M>;
8
+ };
9
+ export declare function useSelectedSnapshot<M extends AnyMachine, Sel>(runtime: Runtime<M> | undefined, selector: (snapshot: Snapshot<M>) => Sel, compare?: (current: Sel, next: Sel) => boolean): Sel;
package/dist/index.mjs ADDED
@@ -0,0 +1,37 @@
1
+ import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
2
+ import { isMachine, makeRuntime } from "small-state";
3
+ import { useSyncExternalStoreWithSelector } from "use-sync-external-store/with-selector";
4
+ // src/react/useRuntime.ts
5
+ function useRuntime(machine, options) {
6
+ if (!isMachine(machine)) throw new Error(`useRuntime() expects Machine object.`);
7
+ const qOptions = useMemo(() => options, []);
8
+ const runtime = useMemo(() => makeRuntime(machine, qOptions), [machine, qOptions]);
9
+ const subscribe = useCallback((onStoreChange) => {
10
+ return runtime.subscribe(onStoreChange, onStoreChange);
11
+ }, [runtime]);
12
+ const getSnapshot = useCallback(() => runtime?.getSnapshot(), [runtime]);
13
+ const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
14
+ useEffect(() => {
15
+ qOptions?.onPreStart?.(runtime);
16
+ runtime.start();
17
+ return () => {
18
+ runtime.stop();
19
+ };
20
+ }, [runtime, qOptions]);
21
+ return {
22
+ snapshot,
23
+ send: runtime.send.bind(runtime),
24
+ runtime
25
+ };
26
+ }
27
+ // src/react/useSelectedSnapshot.ts
28
+ const DEFAULT_COMPARE = (a, b) => a === b;
29
+ function useSelectedSnapshot(runtime, selector, compare = DEFAULT_COMPARE) {
30
+ const subscribe = useCallback((onStoreChange) => {
31
+ if (!runtime) return () => {};
32
+ return runtime.subscribe(onStoreChange, onStoreChange);
33
+ }, [runtime]);
34
+ const getSnapshot = useCallback(() => runtime?.getSnapshot(), [runtime]);
35
+ return useSyncExternalStoreWithSelector(subscribe, getSnapshot, getSnapshot, selector, compare);
36
+ }
37
+ export { useRuntime, useSelectedSnapshot };
package/dist/jotai.cjs ADDED
@@ -0,0 +1,53 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let small_state = require("small-state");
3
+ let jotai_vanilla = require("jotai/vanilla");
4
+ // src/jotai/atomWithRuntimeSnapshot.ts
5
+ const FINALIZE_EVENT = Symbol();
6
+ function atomWithRuntimeSnapshot(machine, options) {
7
+ const rtCacheAtom = (0, jotai_vanilla.atom)(null);
8
+ const snapshotAtom = (0, jotai_vanilla.atom)(null);
9
+ const setupAtom = (0, jotai_vanilla.atom)((get) => {
10
+ const cache = get(rtCacheAtom);
11
+ if (cache) return cache;
12
+ let initializing = true;
13
+ const safeGet = (...args) => {
14
+ if (initializing) return get(...args);
15
+ throw new Error("get not allowed after initialization");
16
+ };
17
+ try {
18
+ return (0, small_state.makeRuntime)(typeof machine === "function" ? machine(safeGet) : machine, options);
19
+ } finally {
20
+ initializing = false;
21
+ }
22
+ }, (get, set, event) => {
23
+ if (event === FINALIZE_EVENT) {
24
+ const rt = get(setupAtom);
25
+ set(rtCacheAtom, null);
26
+ set(snapshotAtom, null);
27
+ rt.stop();
28
+ } else {
29
+ const rt = get(setupAtom);
30
+ set(rtCacheAtom, rt);
31
+ const sync = () => set(snapshotAtom, rt.getSnapshot());
32
+ const unsubscribe = rt.subscribe(sync, sync);
33
+ options?.onPreStart?.(rt);
34
+ rt.start();
35
+ sync();
36
+ return unsubscribe;
37
+ }
38
+ });
39
+ setupAtom.onMount = (write) => {
40
+ const unsubscribe = write();
41
+ return () => {
42
+ unsubscribe?.();
43
+ write(FINALIZE_EVENT);
44
+ };
45
+ };
46
+ return (0, jotai_vanilla.atom)((get) => {
47
+ const rt = get(setupAtom);
48
+ return get(snapshotAtom) ?? rt.getSnapshot();
49
+ }, (get, _, event) => {
50
+ get(setupAtom).send(event);
51
+ });
52
+ }
53
+ exports.atomWithRuntimeSnapshot = atomWithRuntimeSnapshot;
@@ -0,0 +1,5 @@
1
+ import { AnyMachine, Runtime, RuntimeOptions, SendFnEvent, Snapshot } from "small-state";
2
+ import { Getter } from "jotai/vanilla";
3
+ export declare function atomWithRuntimeSnapshot<M extends AnyMachine>(machine: M | ((get: Getter) => M), options?: RuntimeOptions<M> & {
4
+ onPreStart?: (runtime: Runtime<M>) => void;
5
+ }): import("jotai/vanilla").WritableAtom<Snapshot<M>, [event: SendFnEvent<M>], void>;
@@ -0,0 +1,5 @@
1
+ import { AnyMachine, Runtime, RuntimeOptions, SendFnEvent, Snapshot } from "small-state";
2
+ import { Getter } from "jotai/vanilla";
3
+ export declare function atomWithRuntimeSnapshot<M extends AnyMachine>(machine: M | ((get: Getter) => M), options?: RuntimeOptions<M> & {
4
+ onPreStart?: (runtime: Runtime<M>) => void;
5
+ }): import("jotai/vanilla").WritableAtom<Snapshot<M>, [event: SendFnEvent<M>], void>;
package/dist/jotai.mjs ADDED
@@ -0,0 +1,52 @@
1
+ import { makeRuntime } from "small-state";
2
+ import { atom } from "jotai/vanilla";
3
+ // src/jotai/atomWithRuntimeSnapshot.ts
4
+ const FINALIZE_EVENT = Symbol();
5
+ function atomWithRuntimeSnapshot(machine, options) {
6
+ const rtCacheAtom = atom(null);
7
+ const snapshotAtom = atom(null);
8
+ const setupAtom = atom((get) => {
9
+ const cache = get(rtCacheAtom);
10
+ if (cache) return cache;
11
+ let initializing = true;
12
+ const safeGet = (...args) => {
13
+ if (initializing) return get(...args);
14
+ throw new Error("get not allowed after initialization");
15
+ };
16
+ try {
17
+ return makeRuntime(typeof machine === "function" ? machine(safeGet) : machine, options);
18
+ } finally {
19
+ initializing = false;
20
+ }
21
+ }, (get, set, event) => {
22
+ if (event === FINALIZE_EVENT) {
23
+ const rt = get(setupAtom);
24
+ set(rtCacheAtom, null);
25
+ set(snapshotAtom, null);
26
+ rt.stop();
27
+ } else {
28
+ const rt = get(setupAtom);
29
+ set(rtCacheAtom, rt);
30
+ const sync = () => set(snapshotAtom, rt.getSnapshot());
31
+ const unsubscribe = rt.subscribe(sync, sync);
32
+ options?.onPreStart?.(rt);
33
+ rt.start();
34
+ sync();
35
+ return unsubscribe;
36
+ }
37
+ });
38
+ setupAtom.onMount = (write) => {
39
+ const unsubscribe = write();
40
+ return () => {
41
+ unsubscribe?.();
42
+ write(FINALIZE_EVENT);
43
+ };
44
+ };
45
+ return atom((get) => {
46
+ const rt = get(setupAtom);
47
+ return get(snapshotAtom) ?? rt.getSnapshot();
48
+ }, (get, _, event) => {
49
+ get(setupAtom).send(event);
50
+ });
51
+ }
52
+ export { atomWithRuntimeSnapshot };
package/package.json CHANGED
@@ -1,6 +1,78 @@
1
1
  {
2
2
  "name": "small-state-react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "React and Jotai bindings for small-state, a lightweight state machine library.",
5
+ "author": "qyvvy",
6
+ "license": "MIT",
7
+ "repository": "github:qyvvy/small-state-react",
8
+ "keywords": ["small-state", "react", "jotai"],
9
+ "type": "module",
10
+ "main": "./dist/index.cjs",
11
+ "module": "./dist/index.mjs",
12
+ "types": "./dist/index.d.mts",
13
+ "exports": {
14
+ ".": {
15
+ "import": {
16
+ "types": "./dist/index.d.mts",
17
+ "default": "./dist/index.mjs"
18
+ },
19
+ "require": {
20
+ "types": "./dist/index.d.cts",
21
+ "default": "./dist/index.cjs"
22
+ }
23
+ },
24
+ "./jotai": {
25
+ "import": {
26
+ "types": "./dist/jotai.d.mts",
27
+ "default": "./dist/jotai.mjs"
28
+ },
29
+ "require": {
30
+ "types": "./dist/jotai.d.cts",
31
+ "default": "./dist/jotai.cjs"
32
+ }
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "THIRD_PARTY_LICENSES.md"
39
+ ],
40
+ "engines": {
41
+ "node": ">=18"
42
+ },
43
+ "dependencies": {
44
+ "use-sync-external-store": "^1.7.0"
45
+ },
46
+ "devDependencies": {
47
+ "@biomejs/biome": "^2.5.15",
48
+ "@happy-dom/global-registrator": "^21.0.4",
49
+ "@testing-library/dom": "^10.4.2",
50
+ "@testing-library/jest-dom": "^7.0.1",
51
+ "@testing-library/react": "^16.3.3",
52
+ "@types/bun": "^1.3.14",
53
+ "@types/react": "^19.3.0",
54
+ "@types/use-sync-external-store": "^1.7.0",
55
+ "jotai": "^3.0.1",
56
+ "react": "^19.3.1",
57
+ "small-state": "^0.3.0",
58
+ "tsdown": "^0.23.0",
59
+ "typescript": "~5.8.3"
60
+ },
61
+ "peerDependencies": {
62
+ "small-state": "^0.3.0",
63
+ "react": "^18.0.0 || ^19.0.0",
64
+ "jotai": "^3.0.1"
65
+ },
66
+ "peerDependenciesMeta": {
67
+ "jotai": {
68
+ "optional": true
69
+ }
70
+ },
71
+ "scripts": {
72
+ "build": "tsdown src/index.ts src/jotai.ts --format esm,cjs --dts",
73
+ "compile": "bun run build",
74
+ "typecheck": "tsc --noEmit",
75
+ "prepack": "bun typecheck && bun compile"
76
+ },
77
+ "sideEffects": false
78
+ }