@xstate/react 2.0.0 → 4.0.0-alpha.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 (68) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/declarations/src/fsm.d.ts +3 -0
  3. package/{es/index.js → dist/declarations/src/index.d.ts} +5 -5
  4. package/dist/declarations/src/types.d.ts +15 -0
  5. package/dist/declarations/src/useActor.d.ts +3 -0
  6. package/{es → dist/declarations/src}/useConstant.d.ts +1 -2
  7. package/dist/declarations/src/useInterpret.d.ts +13 -0
  8. package/dist/declarations/src/useMachine.d.ts +21 -0
  9. package/dist/declarations/src/useSelector.d.ts +2 -0
  10. package/{es → dist/declarations/src}/useSpawn.d.ts +9 -10
  11. package/dist/useConstant-644f0e11.cjs.dev.js +74 -0
  12. package/dist/useConstant-94bfdbb5.esm.js +71 -0
  13. package/dist/useConstant-eeb49d3f.cjs.prod.js +17 -0
  14. package/dist/xstate-react.cjs.d.ts +1 -0
  15. package/dist/xstate-react.cjs.dev.js +241 -0
  16. package/dist/xstate-react.cjs.js +7 -0
  17. package/dist/xstate-react.cjs.prod.js +231 -0
  18. package/dist/xstate-react.esm.js +229 -0
  19. package/fsm/dist/xstate-react-fsm.cjs.d.ts +1 -0
  20. package/fsm/dist/xstate-react-fsm.cjs.dev.js +98 -0
  21. package/fsm/dist/xstate-react-fsm.cjs.js +7 -0
  22. package/fsm/dist/xstate-react-fsm.cjs.prod.js +144 -0
  23. package/fsm/dist/xstate-react-fsm.esm.js +89 -0
  24. package/fsm/package.json +3 -5
  25. package/package.json +25 -48
  26. package/dist/xstate-react-fsm.umd.min.js +0 -28
  27. package/dist/xstate-react.umd.min.js +0 -28
  28. package/es/fsm.d.ts +0 -20
  29. package/es/fsm.js +0 -73
  30. package/es/index.d.ts +0 -6
  31. package/es/types.d.ts +0 -31
  32. package/es/types.js +0 -5
  33. package/es/useActor.d.ts +0 -9
  34. package/es/useActor.js +0 -79
  35. package/es/useConstant.js +0 -8
  36. package/es/useInterpret.d.ts +0 -13
  37. package/es/useInterpret.js +0 -116
  38. package/es/useMachine.d.ts +0 -24
  39. package/es/useMachine.js +0 -78
  40. package/es/useReactEffectActions.d.ts +0 -3
  41. package/es/useReactEffectActions.js +0 -76
  42. package/es/useSelector.d.ts +0 -3
  43. package/es/useSelector.js +0 -70
  44. package/es/useSpawn.js +0 -15
  45. package/es/utils.d.ts +0 -4
  46. package/es/utils.js +0 -53
  47. package/lib/fsm.d.ts +0 -20
  48. package/lib/fsm.js +0 -78
  49. package/lib/index.d.ts +0 -6
  50. package/lib/index.js +0 -15
  51. package/lib/types.d.ts +0 -31
  52. package/lib/types.js +0 -8
  53. package/lib/useActor.d.ts +0 -9
  54. package/lib/useActor.js +0 -84
  55. package/lib/useConstant.d.ts +0 -2
  56. package/lib/useConstant.js +0 -11
  57. package/lib/useInterpret.d.ts +0 -13
  58. package/lib/useInterpret.js +0 -120
  59. package/lib/useMachine.d.ts +0 -24
  60. package/lib/useMachine.js +0 -84
  61. package/lib/useReactEffectActions.d.ts +0 -3
  62. package/lib/useReactEffectActions.js +0 -80
  63. package/lib/useSelector.d.ts +0 -3
  64. package/lib/useSelector.js +0 -74
  65. package/lib/useSpawn.d.ts +0 -10
  66. package/lib/useSpawn.js +0 -19
  67. package/lib/utils.d.ts +0 -4
  68. package/lib/utils.js +0 -58
package/es/useConstant.js DELETED
@@ -1,8 +0,0 @@
1
- import * as React from 'react';
2
- export default function useConstant(fn) {
3
- var ref = React.useRef();
4
- if (!ref.current) {
5
- ref.current = { v: fn() };
6
- }
7
- return ref.current.v;
8
- }
@@ -1,13 +0,0 @@
1
- import { AreAllImplementationsAssumedToBeProvided, InternalMachineOptions, InterpreterFrom, InterpreterOptions, Observer, State, StateMachine } from 'xstate';
2
- import { MaybeLazy } from './types';
3
- import { UseMachineOptions } from './useMachine';
4
- declare type RestParams<TMachine extends StateMachine<any, any, any, any, any, any, any>> = AreAllImplementationsAssumedToBeProvided<TMachine['__TResolvedTypesMeta']> extends false ? [
5
- options: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta'], true>,
6
- observerOrListener?: Observer<State<TMachine['__TContext'], TMachine['__TEvent'], any, TMachine['__TTypestate'], TMachine['__TResolvedTypesMeta']>> | ((value: State<TMachine['__TContext'], TMachine['__TEvent'], any, TMachine['__TTypestate'], TMachine['__TResolvedTypesMeta']>) => void)
7
- ] : [
8
- options?: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta']>,
9
- observerOrListener?: Observer<State<TMachine['__TContext'], TMachine['__TEvent'], any, TMachine['__TTypestate'], TMachine['__TResolvedTypesMeta']>> | ((value: State<TMachine['__TContext'], TMachine['__TEvent'], any, TMachine['__TTypestate'], TMachine['__TResolvedTypesMeta']>) => void)
10
- ];
11
- export declare function useInterpret<TMachine extends StateMachine<any, any, any, any, any, any, any>>(getMachine: MaybeLazy<TMachine>, ...[options, observerOrListener]: RestParams<TMachine>): InterpreterFrom<TMachine>;
12
- export {};
13
- //# sourceMappingURL=useInterpret.d.ts.map
@@ -1,116 +0,0 @@
1
- var __assign = (this && this.__assign) || function () {
2
- __assign = Object.assign || function(t) {
3
- for (var s, i = 1, n = arguments.length; i < n; i++) {
4
- s = arguments[i];
5
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
- t[p] = s[p];
7
- }
8
- return t;
9
- };
10
- return __assign.apply(this, arguments);
11
- };
12
- var __rest = (this && this.__rest) || function (s, e) {
13
- var t = {};
14
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
15
- t[p] = s[p];
16
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
17
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
18
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
19
- t[p[i]] = s[p[i]];
20
- }
21
- return t;
22
- };
23
- var __read = (this && this.__read) || function (o, n) {
24
- var m = typeof Symbol === "function" && o[Symbol.iterator];
25
- if (!m) return o;
26
- var i = m.call(o), r, ar = [], e;
27
- try {
28
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
29
- }
30
- catch (error) { e = { error: error }; }
31
- finally {
32
- try {
33
- if (r && !r.done && (m = i["return"])) m.call(i);
34
- }
35
- finally { if (e) throw e.error; }
36
- }
37
- return ar;
38
- };
39
- import { useState } from 'react';
40
- import useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';
41
- import { interpret, State } from 'xstate';
42
- import useConstant from './useConstant';
43
- import { useReactEffectActions } from './useReactEffectActions';
44
- // copied from core/src/utils.ts
45
- // it avoids a breaking change between this package and XState which is its peer dep
46
- function toObserver(nextHandler, errorHandler, completionHandler) {
47
- if (typeof nextHandler === 'object') {
48
- return nextHandler;
49
- }
50
- var noop = function () { return void 0; };
51
- return {
52
- next: nextHandler,
53
- error: errorHandler || noop,
54
- complete: completionHandler || noop
55
- };
56
- }
57
- export function useInterpret(getMachine) {
58
- var _a = [];
59
- for (var _i = 1; _i < arguments.length; _i++) {
60
- _a[_i - 1] = arguments[_i];
61
- }
62
- var _b = __read(_a, 2), _c = _b[0], options = _c === void 0 ? {} : _c, observerOrListener = _b[1];
63
- var machine = useConstant(function () {
64
- return typeof getMachine === 'function' ? getMachine() : getMachine;
65
- });
66
- if (process.env.NODE_ENV !== 'production' &&
67
- typeof getMachine !== 'function') {
68
- var _d = __read(useState(machine), 1), initialMachine = _d[0];
69
- if (getMachine !== initialMachine) {
70
- console.warn('Machine given to `useMachine` has changed between renders. This is not supported and might lead to unexpected results.\n' +
71
- 'Please make sure that you pass the same Machine as argument each time.');
72
- }
73
- }
74
- var context = options.context, guards = options.guards, actions = options.actions, services = options.services, delays = options.delays, rehydratedState = options.state, interpreterOptions = __rest(options, ["context", "guards", "actions", "services", "delays", "state"]);
75
- // it's not defined in `TypegenMachineOptions` so we can't just unpack this property here freely
76
- var activities = options.activities;
77
- var service = useConstant(function () {
78
- var machineConfig = {
79
- context: context,
80
- guards: guards,
81
- actions: actions,
82
- activities: activities,
83
- services: services,
84
- delays: delays
85
- };
86
- var machineWithConfig = machine.withConfig(machineConfig, function () { return (__assign(__assign({}, machine.context), context)); });
87
- return interpret(machineWithConfig, __assign({ deferEvents: true }, interpreterOptions));
88
- });
89
- useIsomorphicLayoutEffect(function () {
90
- var sub;
91
- if (observerOrListener) {
92
- sub = service.subscribe(toObserver(observerOrListener));
93
- }
94
- return function () {
95
- sub === null || sub === void 0 ? void 0 : sub.unsubscribe();
96
- };
97
- }, [observerOrListener]);
98
- useIsomorphicLayoutEffect(function () {
99
- service.start(rehydratedState ? State.create(rehydratedState) : undefined);
100
- return function () {
101
- service.stop();
102
- };
103
- }, []);
104
- // Make sure options are kept updated when they change.
105
- // This mutation assignment is safe because the service instance is only used
106
- // in one place -- this hook's caller.
107
- useIsomorphicLayoutEffect(function () {
108
- Object.assign(service.machine.options.actions, actions);
109
- Object.assign(service.machine.options.guards, guards);
110
- Object.assign(service.machine.options.activities, activities);
111
- Object.assign(service.machine.options.services, services);
112
- Object.assign(service.machine.options.delays, delays);
113
- }, [actions, guards, activities, services, delays]);
114
- useReactEffectActions(service);
115
- return service;
116
- }
@@ -1,24 +0,0 @@
1
- import { ActionFunction, AreAllImplementationsAssumedToBeProvided, EventObject, InternalMachineOptions, InterpreterFrom, InterpreterOptions, StateConfig, StateFrom, StateMachine } from 'xstate';
2
- import { MaybeLazy, Prop, ReactActionFunction } from './types';
3
- export declare function asEffect<TContext, TEvent extends EventObject>(exec: ActionFunction<TContext, TEvent>): ReactActionFunction<TContext, TEvent>;
4
- export declare function asLayoutEffect<TContext, TEvent extends EventObject>(exec: ActionFunction<TContext, TEvent>): ReactActionFunction<TContext, TEvent>;
5
- export interface UseMachineOptions<TContext, TEvent extends EventObject> {
6
- /**
7
- * If provided, will be merged with machine's `context`.
8
- */
9
- context?: Partial<TContext>;
10
- /**
11
- * The state to rehydrate the machine to. The machine will
12
- * start at this state instead of its `initialState`.
13
- */
14
- state?: StateConfig<TContext, TEvent>;
15
- }
16
- declare type RestParams<TMachine extends StateMachine<any, any, any, any, any, any, any>> = AreAllImplementationsAssumedToBeProvided<TMachine['__TResolvedTypesMeta']> extends false ? [
17
- options: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta'], true>
18
- ] : [
19
- options?: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta']>
20
- ];
21
- declare type UseMachineReturn<TMachine extends StateMachine<any, any, any, any, any, any, any>, TInterpreter = InterpreterFrom<TMachine>> = [StateFrom<TMachine>, Prop<TInterpreter, 'send'>, TInterpreter];
22
- export declare function useMachine<TMachine extends StateMachine<any, any, any, any, any, any, any>>(getMachine: MaybeLazy<TMachine>, ...[options]: RestParams<TMachine>): UseMachineReturn<TMachine>;
23
- export {};
24
- //# sourceMappingURL=useMachine.d.ts.map
package/es/useMachine.js DELETED
@@ -1,78 +0,0 @@
1
- var __read = (this && this.__read) || function (o, n) {
2
- var m = typeof Symbol === "function" && o[Symbol.iterator];
3
- if (!m) return o;
4
- var i = m.call(o), r, ar = [], e;
5
- try {
6
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
7
- }
8
- catch (error) { e = { error: error }; }
9
- finally {
10
- try {
11
- if (r && !r.done && (m = i["return"])) m.call(i);
12
- }
13
- finally { if (e) throw e.error; }
14
- }
15
- return ar;
16
- };
17
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
18
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
19
- if (ar || !(i in from)) {
20
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
21
- ar[i] = from[i];
22
- }
23
- }
24
- return to.concat(ar || Array.prototype.slice.call(from));
25
- };
26
- import { useCallback, useState } from 'react';
27
- import { State } from 'xstate';
28
- import { ReactEffectType } from './types';
29
- import { useInterpret } from './useInterpret';
30
- function createReactActionFunction(exec, tag) {
31
- var effectExec = function () {
32
- var args = [];
33
- for (var _i = 0; _i < arguments.length; _i++) {
34
- args[_i] = arguments[_i];
35
- }
36
- // don't execute; just return
37
- return function () {
38
- return exec.apply(void 0, __spreadArray([], __read(args), false));
39
- };
40
- };
41
- Object.defineProperties(effectExec, {
42
- name: { value: "effect:".concat(exec.name) },
43
- __effect: { value: tag }
44
- });
45
- return effectExec;
46
- }
47
- export function asEffect(exec) {
48
- return createReactActionFunction(exec, ReactEffectType.Effect);
49
- }
50
- export function asLayoutEffect(exec) {
51
- return createReactActionFunction(exec, ReactEffectType.LayoutEffect);
52
- }
53
- export function useMachine(getMachine) {
54
- var _a = [];
55
- for (var _i = 1; _i < arguments.length; _i++) {
56
- _a[_i - 1] = arguments[_i];
57
- }
58
- var _b = __read(_a, 1), _c = _b[0], options = _c === void 0 ? {} : _c;
59
- var listener = useCallback(function (nextState) {
60
- // Only change the current state if:
61
- // - the incoming state is the "live" initial state (since it might have new actors)
62
- // - OR the incoming state actually changed.
63
- //
64
- // The "live" initial state will have .changed === undefined.
65
- var initialStateChanged = nextState.changed === undefined && Object.keys(nextState.children).length;
66
- if (nextState.changed || initialStateChanged) {
67
- setState(nextState);
68
- }
69
- }, []);
70
- var service = useInterpret(getMachine, options, listener);
71
- var _d = __read(useState(function () {
72
- var initialState = service.machine.initialState;
73
- return (options.state
74
- ? State.create(options.state)
75
- : initialState);
76
- }), 2), state = _d[0], setState = _d[1];
77
- return [state, service.send, service];
78
- }
@@ -1,3 +0,0 @@
1
- import { EventObject, Interpreter } from 'xstate';
2
- export declare function useReactEffectActions<TContext, TEvent extends EventObject>(service: Interpreter<TContext, any, TEvent, any>): void;
3
- //# sourceMappingURL=useReactEffectActions.d.ts.map
@@ -1,76 +0,0 @@
1
- var __read = (this && this.__read) || function (o, n) {
2
- var m = typeof Symbol === "function" && o[Symbol.iterator];
3
- if (!m) return o;
4
- var i = m.call(o), r, ar = [], e;
5
- try {
6
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
7
- }
8
- catch (error) { e = { error: error }; }
9
- finally {
10
- try {
11
- if (r && !r.done && (m = i["return"])) m.call(i);
12
- }
13
- finally { if (e) throw e.error; }
14
- }
15
- return ar;
16
- };
17
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
18
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
19
- if (ar || !(i in from)) {
20
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
21
- ar[i] = from[i];
22
- }
23
- }
24
- return to.concat(ar || Array.prototype.slice.call(from));
25
- };
26
- import { useEffect, useRef } from 'react';
27
- import useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';
28
- import { ReactEffectType } from './types';
29
- import { partition } from './utils';
30
- function executeEffect(action, state) {
31
- var exec = action.exec;
32
- var originalExec = exec(state.context, state._event.data, {
33
- action: action,
34
- state: state,
35
- _event: state._event
36
- });
37
- originalExec();
38
- }
39
- export function useReactEffectActions(service) {
40
- var effectActionsRef = useRef([]);
41
- var layoutEffectActionsRef = useRef([]);
42
- useIsomorphicLayoutEffect(function () {
43
- var sub = service.subscribe(function (currentState) {
44
- var _a, _b;
45
- if (currentState.actions.length) {
46
- var reactEffectActions = currentState.actions.filter(function (action) {
47
- return (typeof action.exec === 'function' &&
48
- '__effect' in action.exec);
49
- });
50
- var _c = __read(partition(reactEffectActions, function (action) {
51
- return action.exec.__effect === ReactEffectType.Effect;
52
- }), 2), effectActions = _c[0], layoutEffectActions = _c[1];
53
- (_a = effectActionsRef.current).push.apply(_a, __spreadArray([], __read(effectActions.map(function (effectAction) { return [effectAction, currentState]; })), false));
54
- (_b = layoutEffectActionsRef.current).push.apply(_b, __spreadArray([], __read(layoutEffectActions.map(function (layoutEffectAction) { return [layoutEffectAction, currentState]; })), false));
55
- }
56
- });
57
- return function () {
58
- sub.unsubscribe();
59
- };
60
- }, []);
61
- // this is somewhat weird - this should always be flushed within useLayoutEffect
62
- // but we don't want to receive warnings about useLayoutEffect being used on the server
63
- // so we have to use `useIsomorphicLayoutEffect` to silence those warnings
64
- useIsomorphicLayoutEffect(function () {
65
- while (layoutEffectActionsRef.current.length) {
66
- var _a = __read(layoutEffectActionsRef.current.shift(), 2), layoutEffectAction = _a[0], effectState = _a[1];
67
- executeEffect(layoutEffectAction, effectState);
68
- }
69
- }); // https://github.com/statelyai/xstate/pull/1202#discussion_r429677773
70
- useEffect(function () {
71
- while (effectActionsRef.current.length) {
72
- var _a = __read(effectActionsRef.current.shift(), 2), effectAction = _a[0], effectState = _a[1];
73
- executeEffect(effectAction, effectState);
74
- }
75
- });
76
- }
@@ -1,3 +0,0 @@
1
- import { ActorRef, Subscribable } from 'xstate';
2
- export declare function useSelector<TActor extends ActorRef<any, any>, T, TEmitted = TActor extends Subscribable<infer Emitted> ? Emitted : never>(actor: TActor, selector: (emitted: TEmitted) => T, compare?: (a: T, b: T) => boolean, getSnapshot?: (a: TActor) => TEmitted): T;
3
- //# sourceMappingURL=useSelector.d.ts.map
package/es/useSelector.js DELETED
@@ -1,70 +0,0 @@
1
- import { useMemo, useRef } from 'react';
2
- import { useSubscription } from 'use-subscription';
3
- import useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';
4
- import { isActorWithState } from './useActor';
5
- import { getServiceSnapshot } from './utils';
6
- function isService(actor) {
7
- return 'state' in actor && 'machine' in actor;
8
- }
9
- var defaultCompare = function (a, b) { return a === b; };
10
- var defaultGetSnapshot = function (a) {
11
- return isService(a)
12
- ? getServiceSnapshot(a)
13
- : isActorWithState(a)
14
- ? a.state
15
- : undefined;
16
- };
17
- export function useSelector(actor, selector, compare, getSnapshot) {
18
- if (compare === void 0) { compare = defaultCompare; }
19
- if (getSnapshot === void 0) { getSnapshot = defaultGetSnapshot; }
20
- var latestSelectorRef = useRef(selector);
21
- var subscription = useMemo(function () {
22
- var snapshot = getSnapshot(actor);
23
- var current = selector(snapshot);
24
- var notifySubscriber;
25
- return {
26
- getSnapshot: function () { return snapshot; },
27
- getCurrentValue: function () { return current; },
28
- setCurrentValue: function (newCurrent) {
29
- current = newCurrent;
30
- notifySubscriber === null || notifySubscriber === void 0 ? void 0 : notifySubscriber();
31
- },
32
- subscribe: function (callback) {
33
- notifySubscriber = callback;
34
- var sub = actor.subscribe(function (emitted) {
35
- snapshot = emitted;
36
- var next = latestSelectorRef.current(emitted);
37
- if (!compare(current, next)) {
38
- current = next;
39
- callback();
40
- }
41
- });
42
- return function () {
43
- sub.unsubscribe();
44
- };
45
- }
46
- };
47
- // intentionally omit `getSnapshot` and `compare`
48
- // - `getSnapshot`: it is only supposed to read the "initial" snapshot of an actor
49
- // - `compare`: is really supposed to be idempotent and the same throughout the lifetime of this hook (the same assumption is made in React Redux v7)
50
- }, [actor]);
51
- var currentSelected = useSubscription(subscription);
52
- var currentChanged = false;
53
- if (latestSelectorRef.current !== selector) {
54
- var selected = selector(subscription.getSnapshot());
55
- if (!compare(currentSelected, selected)) {
56
- currentChanged = true;
57
- currentSelected = selected;
58
- }
59
- }
60
- useIsomorphicLayoutEffect(function () {
61
- latestSelectorRef.current = selector;
62
- // this condition should not be required, but setState bailouts are currently buggy: https://github.com/facebook/react/issues/22654
63
- if (currentChanged) {
64
- // required so we don't cause a rerender by setting state (this could create infinite rerendering loop with inline selectors)
65
- // at the same time we need to update the value within the subscription so new emits can compare against what has been returned to the user as current value
66
- subscription.setCurrentValue(currentSelected);
67
- }
68
- });
69
- return currentSelected;
70
- }
package/es/useSpawn.js DELETED
@@ -1,15 +0,0 @@
1
- import { spawnBehavior } from 'xstate/lib/behaviors';
2
- import useConstant from './useConstant';
3
- /**
4
- * React hook that spawns an `ActorRef` with the specified `behavior`.
5
- * The returned `ActorRef` can be used with the `useActor(actorRef)` hook.
6
- *
7
- * @param behavior The actor behavior to spawn
8
- * @returns An ActorRef with the specified `behavior`
9
- */
10
- export function useSpawn(behavior) {
11
- var actorRef = useConstant(function () {
12
- return spawnBehavior(behavior);
13
- });
14
- return actorRef;
15
- }
package/es/utils.d.ts DELETED
@@ -1,4 +0,0 @@
1
- import { Interpreter } from 'xstate';
2
- export declare function partition<T, A extends T, B extends T>(items: T[], predicate: (item: T) => item is A): [A[], B[]];
3
- export declare function getServiceSnapshot<TService extends Interpreter<any, any, any, any>>(service: TService): TService['state'];
4
- //# sourceMappingURL=utils.d.ts.map
package/es/utils.js DELETED
@@ -1,53 +0,0 @@
1
- var __read = (this && this.__read) || function (o, n) {
2
- var m = typeof Symbol === "function" && o[Symbol.iterator];
3
- if (!m) return o;
4
- var i = m.call(o), r, ar = [], e;
5
- try {
6
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
7
- }
8
- catch (error) { e = { error: error }; }
9
- finally {
10
- try {
11
- if (r && !r.done && (m = i["return"])) m.call(i);
12
- }
13
- finally { if (e) throw e.error; }
14
- }
15
- return ar;
16
- };
17
- var __values = (this && this.__values) || function(o) {
18
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
19
- if (m) return m.call(o);
20
- if (o && typeof o.length === "number") return {
21
- next: function () {
22
- if (o && i >= o.length) o = void 0;
23
- return { value: o && o[i++], done: !o };
24
- }
25
- };
26
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
27
- };
28
- export function partition(items, predicate) {
29
- var e_1, _a;
30
- var _b = __read([[], []], 2), truthy = _b[0], falsy = _b[1];
31
- try {
32
- for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
33
- var item = items_1_1.value;
34
- if (predicate(item)) {
35
- truthy.push(item);
36
- }
37
- else {
38
- falsy.push(item);
39
- }
40
- }
41
- }
42
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
43
- finally {
44
- try {
45
- if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
46
- }
47
- finally { if (e_1) throw e_1.error; }
48
- }
49
- return [truthy, falsy];
50
- }
51
- export function getServiceSnapshot(service) {
52
- return service.status !== 0 ? service.state : service.machine.initialState;
53
- }
package/lib/fsm.d.ts DELETED
@@ -1,20 +0,0 @@
1
- import { StateMachine, EventObject, Typestate } from '@xstate/fsm';
2
- export declare function useMachine<TContext extends object, TEvent extends EventObject = EventObject, TState extends Typestate<TContext> = {
3
- value: any;
4
- context: TContext;
5
- }>(stateMachine: StateMachine.Machine<TContext, TEvent, TState>, options?: {
6
- actions?: StateMachine.ActionMap<TContext, TEvent>;
7
- }): [
8
- StateMachine.State<TContext, TEvent, TState>,
9
- StateMachine.Service<TContext, TEvent, TState>['send'],
10
- StateMachine.Service<TContext, TEvent, TState>
11
- ];
12
- export declare function useService<TContext extends object, TEvent extends EventObject = EventObject, TState extends Typestate<TContext> = {
13
- value: any;
14
- context: TContext;
15
- }>(service: StateMachine.Service<TContext, TEvent, TState>): [
16
- StateMachine.State<TContext, TEvent, TState>,
17
- StateMachine.Service<TContext, TEvent, TState>['send'],
18
- StateMachine.Service<TContext, TEvent, TState>
19
- ];
20
- //# sourceMappingURL=fsm.d.ts.map
package/lib/fsm.js DELETED
@@ -1,78 +0,0 @@
1
- "use strict";
2
- var __read = (this && this.__read) || function (o, n) {
3
- var m = typeof Symbol === "function" && o[Symbol.iterator];
4
- if (!m) return o;
5
- var i = m.call(o), r, ar = [], e;
6
- try {
7
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
8
- }
9
- catch (error) { e = { error: error }; }
10
- finally {
11
- try {
12
- if (r && !r.done && (m = i["return"])) m.call(i);
13
- }
14
- finally { if (e) throw e.error; }
15
- }
16
- return ar;
17
- };
18
- Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.useService = exports.useMachine = void 0;
20
- var react_1 = require("react");
21
- var fsm_1 = require("@xstate/fsm");
22
- var use_subscription_1 = require("use-subscription");
23
- var useConstant_1 = require("./useConstant");
24
- var getServiceState = function (service) {
25
- var currentValue;
26
- service
27
- .subscribe(function (state) {
28
- currentValue = state;
29
- })
30
- .unsubscribe();
31
- return currentValue;
32
- };
33
- function useMachine(stateMachine, options) {
34
- if (process.env.NODE_ENV !== 'production') {
35
- var _a = __read((0, react_1.useState)(stateMachine), 1), initialMachine = _a[0];
36
- if (stateMachine !== initialMachine) {
37
- console.warn('Machine given to `useMachine` has changed between renders. This is not supported and might lead to unexpected results.\n' +
38
- 'Please make sure that you pass the same Machine as argument each time.');
39
- }
40
- }
41
- var service = (0, useConstant_1.default)(function () {
42
- return (0, fsm_1.interpret)((0, fsm_1.createMachine)(stateMachine.config, options ? options : stateMachine._options)).start();
43
- });
44
- var _b = __read((0, react_1.useState)(function () { return getServiceState(service); }), 2), state = _b[0], setState = _b[1];
45
- (0, react_1.useEffect)(function () {
46
- if (options) {
47
- service._machine._options = options;
48
- }
49
- });
50
- (0, react_1.useEffect)(function () {
51
- service.subscribe(setState);
52
- return function () {
53
- service.stop();
54
- };
55
- }, []);
56
- return [state, service.send, service];
57
- }
58
- exports.useMachine = useMachine;
59
- function useService(service) {
60
- var subscription = (0, react_1.useMemo)(function () {
61
- var currentState = getServiceState(service);
62
- return {
63
- getCurrentValue: function () { return currentState; },
64
- subscribe: function (callback) {
65
- var unsubscribe = service.subscribe(function (state) {
66
- if (state.changed !== false) {
67
- currentState = state;
68
- callback();
69
- }
70
- }).unsubscribe;
71
- return unsubscribe;
72
- }
73
- };
74
- }, [service]);
75
- var state = (0, use_subscription_1.useSubscription)(subscription);
76
- return [state, service.send, service];
77
- }
78
- exports.useService = useService;
package/lib/index.d.ts DELETED
@@ -1,6 +0,0 @@
1
- export { useMachine, asEffect, asLayoutEffect } from './useMachine';
2
- export { useActor } from './useActor';
3
- export { useInterpret } from './useInterpret';
4
- export { useSelector } from './useSelector';
5
- export { useSpawn } from './useSpawn';
6
- //# sourceMappingURL=index.d.ts.map
package/lib/index.js DELETED
@@ -1,15 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.useSpawn = exports.useSelector = exports.useInterpret = exports.useActor = exports.asLayoutEffect = exports.asEffect = exports.useMachine = void 0;
4
- var useMachine_1 = require("./useMachine");
5
- Object.defineProperty(exports, "useMachine", { enumerable: true, get: function () { return useMachine_1.useMachine; } });
6
- Object.defineProperty(exports, "asEffect", { enumerable: true, get: function () { return useMachine_1.asEffect; } });
7
- Object.defineProperty(exports, "asLayoutEffect", { enumerable: true, get: function () { return useMachine_1.asLayoutEffect; } });
8
- var useActor_1 = require("./useActor");
9
- Object.defineProperty(exports, "useActor", { enumerable: true, get: function () { return useActor_1.useActor; } });
10
- var useInterpret_1 = require("./useInterpret");
11
- Object.defineProperty(exports, "useInterpret", { enumerable: true, get: function () { return useInterpret_1.useInterpret; } });
12
- var useSelector_1 = require("./useSelector");
13
- Object.defineProperty(exports, "useSelector", { enumerable: true, get: function () { return useSelector_1.useSelector; } });
14
- var useSpawn_1 = require("./useSpawn");
15
- Object.defineProperty(exports, "useSpawn", { enumerable: true, get: function () { return useSpawn_1.useSpawn; } });
package/lib/types.d.ts DELETED
@@ -1,31 +0,0 @@
1
- import { ActionMeta, ActionObject, EventObject, State, StateConfig } from 'xstate';
2
- export declare type MaybeLazy<T> = T | (() => T);
3
- export declare type NoInfer<T> = [T][T extends any ? 0 : any];
4
- export declare type Prop<T, K> = K extends keyof T ? T[K] : never;
5
- export declare enum ReactEffectType {
6
- Effect = 1,
7
- LayoutEffect = 2
8
- }
9
- export interface ReactActionFunction<TContext, TEvent extends EventObject> {
10
- (context: TContext, event: TEvent, meta: ActionMeta<TContext, TEvent>): () => void;
11
- __effect: ReactEffectType;
12
- }
13
- export interface ReactActionObject<TContext, TEvent extends EventObject> extends ActionObject<TContext, TEvent> {
14
- exec: ReactActionFunction<TContext, TEvent>;
15
- }
16
- export interface UseMachineOptions<TContext, TEvent extends EventObject> {
17
- /**
18
- * If provided, will be merged with machine's `context`.
19
- */
20
- context?: Partial<TContext>;
21
- /**
22
- * The state to rehydrate the machine to. The machine will
23
- * start at this state instead of its `initialState`.
24
- */
25
- state?: StateConfig<TContext, TEvent>;
26
- }
27
- export declare type ActionStateTuple<TContext, TEvent extends EventObject> = [
28
- ReactActionObject<TContext, TEvent>,
29
- State<TContext, TEvent>
30
- ];
31
- //# sourceMappingURL=types.d.ts.map
package/lib/types.js DELETED
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ReactEffectType = void 0;
4
- var ReactEffectType;
5
- (function (ReactEffectType) {
6
- ReactEffectType[ReactEffectType["Effect"] = 1] = "Effect";
7
- ReactEffectType[ReactEffectType["LayoutEffect"] = 2] = "LayoutEffect";
8
- })(ReactEffectType = exports.ReactEffectType || (exports.ReactEffectType = {}));
package/lib/useActor.d.ts DELETED
@@ -1,9 +0,0 @@
1
- import { ActorRef, EventObject, Sender } from 'xstate';
2
- export declare function isActorWithState<T extends ActorRef<any>>(actorRef: T): actorRef is T & {
3
- state: any;
4
- };
5
- declare type EmittedFromActorRef<TActor extends ActorRef<any, any>> = TActor extends ActorRef<any, infer TEmitted> ? TEmitted : never;
6
- export declare function useActor<TActor extends ActorRef<any, any>>(actorRef: TActor, getSnapshot?: (actor: TActor) => EmittedFromActorRef<TActor>): [EmittedFromActorRef<TActor>, TActor['send']];
7
- export declare function useActor<TEvent extends EventObject, TEmitted>(actorRef: ActorRef<TEvent, TEmitted>, getSnapshot?: (actor: ActorRef<TEvent, TEmitted>) => TEmitted): [TEmitted, Sender<TEvent>];
8
- export {};
9
- //# sourceMappingURL=useActor.d.ts.map