small-state-react 0.1.3 → 0.2.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/README.ja.md CHANGED
@@ -12,28 +12,45 @@ npm i small-state-react
12
12
 
13
13
  ### Import from "./small-state-react"
14
14
 
15
- #### `useRuntime(machine, options?)`
15
+ #### 型
16
16
 
17
- `<M extends AnyMachine>(machine: M, options?: RuntimeOptions<M> & { onPreStart?: (runtime: Runtime<M>) => void }) => {snapshot, send, runtime}`
17
+ - `type RuntimeHandle<M extends AnyMachine> = { snapshot: Snapshot<M>; send: (event: SendFnEvent<M>) => undefined; runtime: Runtime<M>; useBoundSend: UseBoundSend<M>; }`
18
+ - `type UseBoundSend<M extends AnyMachine> = (event: SendFnEvent<M>) => () => undefined`
18
19
 
19
- - マシンを受け取り、ランタイムとして start させ、 `{snapshot, send, runtime}` のオブジェクトを返す。
20
- - オプション引数は一番最初の呼び出しに与えられた引数のみが使われる。インラインで指定されて参照が変わっても同一の値と見なすためである。
20
+ #### `useRuntimeHandle(machine, options?): RuntimeHandle`
21
+
22
+ `<M extends AnyMachine>(machine: M, options?: RuntimeOptions<M> & { onPreStart?: (runtime: Runtime<M>) => void }) => RuntimeHandle<M>`
23
+
24
+ - マシンを受け取り、ランタイムとして start させ、 `RuntimeHandle<M>: {snapshot, send, runtime, useBoundSend}` のオブジェクトを返す。
25
+ - 引数は初回呼び出しに与えられた引数のみが使われる。後から与える引数を変えてもそれは反映されない。これは引数がインラインで指定されて参照が変わっても同一の値と見なさせるためである。
21
26
  - オプション `onPreStart` はランタイムが start される直前に実行されるフック関数であり、マシンから作られたランタイムを引数に受け取る。
22
27
  - `.onEmitted` や `.subscribe` を実行するのに使うと良い。
23
28
 
29
+ - 戻り値 `RuntimeHandle<M>: {snapshot, send, runtime, useBoundSend}` - ランタイムの現在の状態と操作を行うプロパティが設定されたオブジェクト
30
+ - `snapshot: Snapshot<M>` - ランタイムのスナップショットオブジェクト。context や states や runtimeStatus 等を持つ。詳しくは small-state の Snapshot のドキュメント参照。
31
+ - `send: (event: SendFnEvent<M>) => undefined` - ランタイムにイベントを送る。
32
+ - `onChange={()=>send({type: 'foo'})}` のようにインラインで書くと毎回新しい関数が生成されるので毎回そのオブジェクトが更新されてしまう。送るイベントの値が毎回固定的であり、これを嫌うなら後述する `useBoundSend` でイベントを固定化した関数を生成しそれを代わりにハンドラーとして使うとよい。
33
+ - `runtime: Runtime<M>` - ランタイム自身。
34
+ - `useBoundSend: (event: SendFnEvent<M>) => () => undefined`
35
+ - NOTE: これは試験的機能である。まだ不安定である。
36
+ - 関数であり、イベントオブジェクトを与えるとそのイベントオブジェクトが紐づけられた send 関数を返す。つまり、指定したイベントを send 関数に `.bind` したような関数を返す(ただし関数オブジェクトの参照は毎実行時変わらないのでコンポネントに与えても毎回再描写されるのを抑えられる)。
37
+ - イベントハンドラに直接渡せる関数を得るために使うとよい。
38
+ - 初回呼び出し時に与えた event が使われ、次回呼び出し以降に、event の内容を変更してもそれは無視される。
39
+ - React のフック扱いなので、通常のフックの扱いの制限を受ける。すなわち、条件分岐内などで実行してはいけない。
40
+
24
41
 
25
42
  #### `useSelectedSnapshot(runtime, selector, compare?)`
26
43
 
27
44
  `<M extends AnyMachine, Sel>(runtime: Runtime<M>, selector: (snapshot: Snapshot<M>)=>Sel, compare?: (current: Sel, next: Sel)=>boolean) => Sel`
28
45
 
29
- - ランタイムを受け取り、そのランタイムのスナップショットを `selector` で加工したスナップショットを返す。
46
+ - ランタイムとスナップショット加工関数 `selector` を受け取り、`selector` で加工した結果を返す。
30
47
  - スナップショットの一部の値だけ利用・監視したいときなどに使う。
31
48
  - 引数 compare は selection の旧値と新値を比較する関数である。 true なら同一と見なし再レンダリングを抑制する。 false なら更新を反映する。省略時は `===` による同一性比較である。
32
49
 
33
50
 
34
51
  ### Import from "./small-state-react/jotai"
35
52
 
36
- #### `atomWithRuntimeSnapshot(machine, options?)`
53
+ #### `atomWithRuntimeSnapshot(machine, options?): [snapshot, send]`
37
54
 
38
55
  `<M extends AnyMachine>(machine: M | ((get:Getter)=>M), options?: RuntimeOptions<M> & { onPreStart?: (runtime: Runtime<M>) => void }) => WritableAtom<Snapshot<M>, [event: SendFnEvent<M>], void>`
39
56
 
package/README.md CHANGED
@@ -17,22 +17,39 @@ npm i small-state-react
17
17
 
18
18
  ### Import from "./small-state-react"
19
19
 
20
- #### `useRuntime(machine, options?)`
20
+ #### Types
21
21
 
22
- `<M extends AnyMachine>(machine: M, options?: RuntimeOptions<M> & { onPreStart?: (runtime: Runtime<M>) => void }) => {snapshot, send, runtime}`
22
+ - `type RuntimeHandle<M extends AnyMachine> = { snapshot: Snapshot<M>; send: (event: SendFnEvent<M>) => undefined; runtime: Runtime<M>; useBoundSend: UseBoundSend<M>; }`
23
+ - `type UseBoundSend<M extends AnyMachine> = (event: SendFnEvent<M>) => () => undefined`
23
24
 
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.
25
+ #### `useRuntimeHandle(machine, options?): RuntimeHandle`
26
+
27
+ `<M extends AnyMachine>(machine: M, options?: RuntimeOptions<M> & { onPreStart?: (runtime: Runtime<M>) => void }) => RuntimeHandle<M>`
28
+
29
+ - Takes a machine, starts it as a runtime, and returns a `RuntimeHandle<M>` object containing `{ snapshot, send, runtime, useBoundSend }`.
30
+ - Only the arguments provided on the initial call are used. Subsequent changes to the arguments are ignored. This allows inline arguments to be treated as having the same values even if their references change between renders.
31
+ - The onPreStart option is a callback that is invoked immediately before the runtime is started. It receives the runtime created from the machine.
32
+ - This is useful for registering .onEmitted or .subscribe handlers.
33
+
34
+ - Return value: `RuntimeHandle<M>: {snapshot, send, runtime, useBoundSend}` - An object containing properties for accessing and interacting with the runtime's current state.
35
+ - `snapshot: Snapshot<M>` - The runtime's current snapshot. It contains properties such as context, states, and runtimeStatus. See the small-state Snapshot documentation for details.
36
+ - `send: (event: SendFnEvent<M>) => undefined` - Sends an event to the runtime.
37
+ - Defining an inline callback such as `onChange={() => send({ type: 'foo' })}` creates a new function on every render, which may cause the receiving object to be updated each time. If the event is always the same and you want to avoid this, you can use `useBoundSend` (described below) to create a function with a fixed event and use it as the event handler instead.
38
+ - `runtime: Runtime<M>` - The runtime instance itself.
39
+ - `useBoundSend: (event: SendFnEvent<M>) => () => undefined`
40
+ - **NOTE: This is an experimental feature and may be unstable.**
41
+ - This function takes an event object and returns a send function bound to that event. In other words, it behaves similarly to calling `.bind` on send with the specified event. However, the returned function retains the same reference across renders, helping prevent unnecessary re-renders when passed to components.
42
+ - This is useful when you need a function that can be passed directly to an event handler.
43
+ - The event provided on the first call is used. Any changes to the event object on subsequent calls are ignored.
44
+ - Since this function is treated as a React Hook, it is subject to the Rules of Hooks. In particular, it must not be called inside conditional statements or other conditional branches.
28
45
 
29
46
 
30
47
  #### `useSelectedSnapshot(runtime, selector, compare?)`
31
48
 
32
49
  `<M extends AnyMachine, Sel>(runtime: Runtime<M>, selector: (snapshot: Snapshot<M>)=>Sel, compare?: (current: Sel, next: Sel)=>boolean) => Sel`
33
50
 
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.
51
+ - Takes a runtime and a snapshot transformation function, `selector`, and returns the result of applying `selector` to the snapshot.
52
+ - Useful when you only need to access or subscribe to specific values from the snapshot.
36
53
  - 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
54
 
38
55
 
package/dist/index.cjs CHANGED
@@ -2,30 +2,38 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let react = require("react");
3
3
  let small_state = require("small-state");
4
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);
5
+ // src/react/useRuntimeHandle.ts
6
+ function readyToUseBoundSend(rtRef) {
7
+ return (event) => (0, react.useRef)(() => void rtRef.current.send(event)).current;
8
+ }
9
+ function useRuntimeHandle(machine, options) {
10
+ if (!(0, small_state.isMachine)(machine)) throw new Error(`useRuntimeHandle() expects Machine object.`);
11
+ const rtRef = (0, react.useRef)(null);
12
+ if (!rtRef.current) rtRef.current = (0, small_state.makeRuntime)(machine, options);
15
13
  (0, react.useEffect)(() => {
16
- qOptions?.onPreStart?.(runtime);
17
- runtime.start();
14
+ if (rtRef.current.runtimeStatus === "stopped") rtRef.current = (0, small_state.makeRuntime)(machine, options);
15
+ const crrRt = rtRef.current;
16
+ options?.onPreStart?.(crrRt);
17
+ crrRt.start();
18
18
  return () => {
19
- runtime.stop();
19
+ crrRt.stop();
20
20
  };
21
- }, [runtime, qOptions]);
22
- return {
23
- snapshot,
24
- send: (event) => {
25
- runtime.send.apply(runtime, [event]);
26
- },
27
- runtime
28
- };
21
+ }, []);
22
+ const runtime = rtRef.current;
23
+ let snapshot;
24
+ {
25
+ const subscribe = (0, react.useCallback)((onStoreChange) => {
26
+ return runtime.subscribe(onStoreChange, onStoreChange);
27
+ }, [runtime]);
28
+ const getSnapshot = (0, react.useCallback)(() => runtime.getSnapshot(), [runtime]);
29
+ snapshot = (0, react.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
30
+ }
31
+ const handle = (0, react.useRef)({}).current;
32
+ handle.snapshot = snapshot;
33
+ handle.send = (event) => void runtime.send.apply(runtime, [event]);
34
+ handle.runtime = runtime;
35
+ handle.useBoundSend = readyToUseBoundSend(rtRef);
36
+ return handle;
29
37
  }
30
38
  // src/react/useSelectedSnapshot.ts
31
39
  const DEFAULT_COMPARE = (a, b) => a === b;
@@ -37,5 +45,5 @@ function useSelectedSnapshot(runtime, selector, compare = DEFAULT_COMPARE) {
37
45
  const getSnapshot = (0, react.useCallback)(() => runtime?.getSnapshot(), [runtime]);
38
46
  return (0, use_sync_external_store_with_selector.useSyncExternalStoreWithSelector)(subscribe, getSnapshot, getSnapshot, selector, compare);
39
47
  }
40
- exports.useRuntime = useRuntime;
48
+ exports.useRuntimeHandle = useRuntimeHandle;
41
49
  exports.useSelectedSnapshot = useSelectedSnapshot;
package/dist/index.d.cts CHANGED
@@ -1,9 +1,13 @@
1
1
  import { AnyMachine, Runtime, RuntimeOptions, SendFnEvent, 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>;
2
+ type UseBoundSend<M extends AnyMachine> = (event: SendFnEvent<M>) => () => undefined;
3
+ type RuntimeHandle<M extends AnyMachine> = {
4
+ snapshot: Snapshot<M>;
6
5
  send: (event: SendFnEvent<M>) => undefined;
7
6
  runtime: Runtime<M>;
7
+ useBoundSend: UseBoundSend<M>;
8
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;
9
+ export declare function useRuntimeHandle<M extends AnyMachine>(machine: M, options?: RuntimeOptions<M> & {
10
+ onPreStart?: (runtime: Runtime<M>) => void;
11
+ }): RuntimeHandle<M>;
12
+ export declare function useSelectedSnapshot<M extends AnyMachine, Sel>(runtime: Runtime<M> | undefined, selector: (snapshot: Snapshot<M>) => Sel, compare?: (current: Sel, next: Sel) => boolean): Sel;
13
+ export type { RuntimeHandle, UseBoundSend };
package/dist/index.d.mts CHANGED
@@ -1,9 +1,13 @@
1
1
  import { AnyMachine, Runtime, RuntimeOptions, SendFnEvent, 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>;
2
+ type UseBoundSend<M extends AnyMachine> = (event: SendFnEvent<M>) => () => undefined;
3
+ type RuntimeHandle<M extends AnyMachine> = {
4
+ snapshot: Snapshot<M>;
6
5
  send: (event: SendFnEvent<M>) => undefined;
7
6
  runtime: Runtime<M>;
7
+ useBoundSend: UseBoundSend<M>;
8
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;
9
+ export declare function useRuntimeHandle<M extends AnyMachine>(machine: M, options?: RuntimeOptions<M> & {
10
+ onPreStart?: (runtime: Runtime<M>) => void;
11
+ }): RuntimeHandle<M>;
12
+ export declare function useSelectedSnapshot<M extends AnyMachine, Sel>(runtime: Runtime<M> | undefined, selector: (snapshot: Snapshot<M>) => Sel, compare?: (current: Sel, next: Sel) => boolean): Sel;
13
+ export type { RuntimeHandle, UseBoundSend };
package/dist/index.mjs CHANGED
@@ -1,30 +1,38 @@
1
- import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
1
+ import { useCallback, useEffect, useRef, useSyncExternalStore } from "react";
2
2
  import { isMachine, makeRuntime } from "small-state";
3
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);
4
+ // src/react/useRuntimeHandle.ts
5
+ function readyToUseBoundSend(rtRef) {
6
+ return (event) => useRef(() => void rtRef.current.send(event)).current;
7
+ }
8
+ function useRuntimeHandle(machine, options) {
9
+ if (!isMachine(machine)) throw new Error(`useRuntimeHandle() expects Machine object.`);
10
+ const rtRef = useRef(null);
11
+ if (!rtRef.current) rtRef.current = makeRuntime(machine, options);
14
12
  useEffect(() => {
15
- qOptions?.onPreStart?.(runtime);
16
- runtime.start();
13
+ if (rtRef.current.runtimeStatus === "stopped") rtRef.current = makeRuntime(machine, options);
14
+ const crrRt = rtRef.current;
15
+ options?.onPreStart?.(crrRt);
16
+ crrRt.start();
17
17
  return () => {
18
- runtime.stop();
18
+ crrRt.stop();
19
19
  };
20
- }, [runtime, qOptions]);
21
- return {
22
- snapshot,
23
- send: (event) => {
24
- runtime.send.apply(runtime, [event]);
25
- },
26
- runtime
27
- };
20
+ }, []);
21
+ const runtime = rtRef.current;
22
+ let snapshot;
23
+ {
24
+ const subscribe = useCallback((onStoreChange) => {
25
+ return runtime.subscribe(onStoreChange, onStoreChange);
26
+ }, [runtime]);
27
+ const getSnapshot = useCallback(() => runtime.getSnapshot(), [runtime]);
28
+ snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
29
+ }
30
+ const handle = useRef({}).current;
31
+ handle.snapshot = snapshot;
32
+ handle.send = (event) => void runtime.send.apply(runtime, [event]);
33
+ handle.runtime = runtime;
34
+ handle.useBoundSend = readyToUseBoundSend(rtRef);
35
+ return handle;
28
36
  }
29
37
  // src/react/useSelectedSnapshot.ts
30
38
  const DEFAULT_COMPARE = (a, b) => a === b;
@@ -36,4 +44,4 @@ function useSelectedSnapshot(runtime, selector, compare = DEFAULT_COMPARE) {
36
44
  const getSnapshot = useCallback(() => runtime?.getSnapshot(), [runtime]);
37
45
  return useSyncExternalStoreWithSelector(subscribe, getSnapshot, getSnapshot, selector, compare);
38
46
  }
39
- export { useRuntime, useSelectedSnapshot };
47
+ export { useRuntimeHandle, useSelectedSnapshot };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "small-state-react",
3
- "version": "0.1.3",
3
+ "version": "0.2.1",
4
4
  "description": "React and Jotai bindings for small-state, a lightweight state machine library.",
5
5
  "author": "qyvvy",
6
6
  "license": "MIT",