@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/lib/useActor.js DELETED
@@ -1,84 +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.useActor = exports.isActorWithState = void 0;
20
- var react_1 = require("react");
21
- var use_isomorphic_layout_effect_1 = require("use-isomorphic-layout-effect");
22
- var useConstant_1 = require("./useConstant");
23
- function isActorWithState(actorRef) {
24
- return 'state' in actorRef;
25
- }
26
- exports.isActorWithState = isActorWithState;
27
- function isDeferredActor(actorRef) {
28
- return 'deferred' in actorRef;
29
- }
30
- var noop = function () {
31
- /* ... */
32
- };
33
- function defaultGetSnapshot(actorRef) {
34
- return 'getSnapshot' in actorRef
35
- ? actorRef.getSnapshot()
36
- : isActorWithState(actorRef)
37
- ? actorRef.state
38
- : undefined;
39
- }
40
- function useActor(actorRef, getSnapshot) {
41
- if (getSnapshot === void 0) { getSnapshot = defaultGetSnapshot; }
42
- var actorRefRef = (0, react_1.useRef)(actorRef);
43
- var deferredEventsRef = (0, react_1.useRef)([]);
44
- var _a = __read((0, react_1.useState)(function () { return getSnapshot(actorRef); }), 2), current = _a[0], setCurrent = _a[1];
45
- var send = (0, useConstant_1.default)(function () { return function () {
46
- var args = [];
47
- for (var _i = 0; _i < arguments.length; _i++) {
48
- args[_i] = arguments[_i];
49
- }
50
- var event = args[0];
51
- if (process.env.NODE_ENV !== 'production' && args.length > 1) {
52
- console.warn("Unexpected payload: ".concat(JSON.stringify(args[1]), ". Only a single event object can be sent to actor send() functions."));
53
- }
54
- var currentActorRef = actorRefRef.current;
55
- // If the previous actor is a deferred actor,
56
- // queue the events so that they can be replayed
57
- // on the non-deferred actor.
58
- if (isDeferredActor(currentActorRef) && currentActorRef.deferred) {
59
- deferredEventsRef.current.push(event);
60
- }
61
- else {
62
- currentActorRef.send(event);
63
- }
64
- }; });
65
- (0, use_isomorphic_layout_effect_1.default)(function () {
66
- actorRefRef.current = actorRef;
67
- setCurrent(getSnapshot(actorRef));
68
- var subscription = actorRef.subscribe({
69
- next: function (emitted) { return setCurrent(emitted); },
70
- error: noop,
71
- complete: noop
72
- });
73
- // Dequeue deferred events from the previous deferred actorRef
74
- while (deferredEventsRef.current.length > 0) {
75
- var deferredEvent = deferredEventsRef.current.shift();
76
- actorRef.send(deferredEvent);
77
- }
78
- return function () {
79
- subscription.unsubscribe();
80
- };
81
- }, [actorRef]);
82
- return [current, send];
83
- }
84
- exports.useActor = useActor;
@@ -1,2 +0,0 @@
1
- export default function useConstant<T>(fn: () => T): T;
2
- //# sourceMappingURL=useConstant.d.ts.map
@@ -1,11 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- var React = require("react");
4
- function useConstant(fn) {
5
- var ref = React.useRef();
6
- if (!ref.current) {
7
- ref.current = { v: fn() };
8
- }
9
- return ref.current.v;
10
- }
11
- exports.default = useConstant;
@@ -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,120 +0,0 @@
1
- "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __rest = (this && this.__rest) || function (s, e) {
14
- var t = {};
15
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
16
- t[p] = s[p];
17
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
18
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
19
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
20
- t[p[i]] = s[p[i]];
21
- }
22
- return t;
23
- };
24
- var __read = (this && this.__read) || function (o, n) {
25
- var m = typeof Symbol === "function" && o[Symbol.iterator];
26
- if (!m) return o;
27
- var i = m.call(o), r, ar = [], e;
28
- try {
29
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
30
- }
31
- catch (error) { e = { error: error }; }
32
- finally {
33
- try {
34
- if (r && !r.done && (m = i["return"])) m.call(i);
35
- }
36
- finally { if (e) throw e.error; }
37
- }
38
- return ar;
39
- };
40
- Object.defineProperty(exports, "__esModule", { value: true });
41
- exports.useInterpret = void 0;
42
- var react_1 = require("react");
43
- var use_isomorphic_layout_effect_1 = require("use-isomorphic-layout-effect");
44
- var xstate_1 = require("xstate");
45
- var useConstant_1 = require("./useConstant");
46
- var useReactEffectActions_1 = require("./useReactEffectActions");
47
- // copied from core/src/utils.ts
48
- // it avoids a breaking change between this package and XState which is its peer dep
49
- function toObserver(nextHandler, errorHandler, completionHandler) {
50
- if (typeof nextHandler === 'object') {
51
- return nextHandler;
52
- }
53
- var noop = function () { return void 0; };
54
- return {
55
- next: nextHandler,
56
- error: errorHandler || noop,
57
- complete: completionHandler || noop
58
- };
59
- }
60
- function useInterpret(getMachine) {
61
- var _a = [];
62
- for (var _i = 1; _i < arguments.length; _i++) {
63
- _a[_i - 1] = arguments[_i];
64
- }
65
- var _b = __read(_a, 2), _c = _b[0], options = _c === void 0 ? {} : _c, observerOrListener = _b[1];
66
- var machine = (0, useConstant_1.default)(function () {
67
- return typeof getMachine === 'function' ? getMachine() : getMachine;
68
- });
69
- if (process.env.NODE_ENV !== 'production' &&
70
- typeof getMachine !== 'function') {
71
- var _d = __read((0, react_1.useState)(machine), 1), initialMachine = _d[0];
72
- if (getMachine !== initialMachine) {
73
- console.warn('Machine given to `useMachine` has changed between renders. This is not supported and might lead to unexpected results.\n' +
74
- 'Please make sure that you pass the same Machine as argument each time.');
75
- }
76
- }
77
- 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"]);
78
- // it's not defined in `TypegenMachineOptions` so we can't just unpack this property here freely
79
- var activities = options.activities;
80
- var service = (0, useConstant_1.default)(function () {
81
- var machineConfig = {
82
- context: context,
83
- guards: guards,
84
- actions: actions,
85
- activities: activities,
86
- services: services,
87
- delays: delays
88
- };
89
- var machineWithConfig = machine.withConfig(machineConfig, function () { return (__assign(__assign({}, machine.context), context)); });
90
- return (0, xstate_1.interpret)(machineWithConfig, __assign({ deferEvents: true }, interpreterOptions));
91
- });
92
- (0, use_isomorphic_layout_effect_1.default)(function () {
93
- var sub;
94
- if (observerOrListener) {
95
- sub = service.subscribe(toObserver(observerOrListener));
96
- }
97
- return function () {
98
- sub === null || sub === void 0 ? void 0 : sub.unsubscribe();
99
- };
100
- }, [observerOrListener]);
101
- (0, use_isomorphic_layout_effect_1.default)(function () {
102
- service.start(rehydratedState ? xstate_1.State.create(rehydratedState) : undefined);
103
- return function () {
104
- service.stop();
105
- };
106
- }, []);
107
- // Make sure options are kept updated when they change.
108
- // This mutation assignment is safe because the service instance is only used
109
- // in one place -- this hook's caller.
110
- (0, use_isomorphic_layout_effect_1.default)(function () {
111
- Object.assign(service.machine.options.actions, actions);
112
- Object.assign(service.machine.options.guards, guards);
113
- Object.assign(service.machine.options.activities, activities);
114
- Object.assign(service.machine.options.services, services);
115
- Object.assign(service.machine.options.delays, delays);
116
- }, [actions, guards, activities, services, delays]);
117
- (0, useReactEffectActions_1.useReactEffectActions)(service);
118
- return service;
119
- }
120
- exports.useInterpret = useInterpret;
@@ -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/lib/useMachine.js DELETED
@@ -1,84 +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
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
19
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
20
- if (ar || !(i in from)) {
21
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
22
- ar[i] = from[i];
23
- }
24
- }
25
- return to.concat(ar || Array.prototype.slice.call(from));
26
- };
27
- Object.defineProperty(exports, "__esModule", { value: true });
28
- exports.useMachine = exports.asLayoutEffect = exports.asEffect = void 0;
29
- var react_1 = require("react");
30
- var xstate_1 = require("xstate");
31
- var types_1 = require("./types");
32
- var useInterpret_1 = require("./useInterpret");
33
- function createReactActionFunction(exec, tag) {
34
- var effectExec = function () {
35
- var args = [];
36
- for (var _i = 0; _i < arguments.length; _i++) {
37
- args[_i] = arguments[_i];
38
- }
39
- // don't execute; just return
40
- return function () {
41
- return exec.apply(void 0, __spreadArray([], __read(args), false));
42
- };
43
- };
44
- Object.defineProperties(effectExec, {
45
- name: { value: "effect:".concat(exec.name) },
46
- __effect: { value: tag }
47
- });
48
- return effectExec;
49
- }
50
- function asEffect(exec) {
51
- return createReactActionFunction(exec, types_1.ReactEffectType.Effect);
52
- }
53
- exports.asEffect = asEffect;
54
- function asLayoutEffect(exec) {
55
- return createReactActionFunction(exec, types_1.ReactEffectType.LayoutEffect);
56
- }
57
- exports.asLayoutEffect = asLayoutEffect;
58
- function useMachine(getMachine) {
59
- var _a = [];
60
- for (var _i = 1; _i < arguments.length; _i++) {
61
- _a[_i - 1] = arguments[_i];
62
- }
63
- var _b = __read(_a, 1), _c = _b[0], options = _c === void 0 ? {} : _c;
64
- var listener = (0, react_1.useCallback)(function (nextState) {
65
- // Only change the current state if:
66
- // - the incoming state is the "live" initial state (since it might have new actors)
67
- // - OR the incoming state actually changed.
68
- //
69
- // The "live" initial state will have .changed === undefined.
70
- var initialStateChanged = nextState.changed === undefined && Object.keys(nextState.children).length;
71
- if (nextState.changed || initialStateChanged) {
72
- setState(nextState);
73
- }
74
- }, []);
75
- var service = (0, useInterpret_1.useInterpret)(getMachine, options, listener);
76
- var _d = __read((0, react_1.useState)(function () {
77
- var initialState = service.machine.initialState;
78
- return (options.state
79
- ? xstate_1.State.create(options.state)
80
- : initialState);
81
- }), 2), state = _d[0], setState = _d[1];
82
- return [state, service.send, service];
83
- }
84
- exports.useMachine = useMachine;
@@ -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,80 +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
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
19
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
20
- if (ar || !(i in from)) {
21
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
22
- ar[i] = from[i];
23
- }
24
- }
25
- return to.concat(ar || Array.prototype.slice.call(from));
26
- };
27
- Object.defineProperty(exports, "__esModule", { value: true });
28
- exports.useReactEffectActions = void 0;
29
- var react_1 = require("react");
30
- var use_isomorphic_layout_effect_1 = require("use-isomorphic-layout-effect");
31
- var types_1 = require("./types");
32
- var utils_1 = require("./utils");
33
- function executeEffect(action, state) {
34
- var exec = action.exec;
35
- var originalExec = exec(state.context, state._event.data, {
36
- action: action,
37
- state: state,
38
- _event: state._event
39
- });
40
- originalExec();
41
- }
42
- function useReactEffectActions(service) {
43
- var effectActionsRef = (0, react_1.useRef)([]);
44
- var layoutEffectActionsRef = (0, react_1.useRef)([]);
45
- (0, use_isomorphic_layout_effect_1.default)(function () {
46
- var sub = service.subscribe(function (currentState) {
47
- var _a, _b;
48
- if (currentState.actions.length) {
49
- var reactEffectActions = currentState.actions.filter(function (action) {
50
- return (typeof action.exec === 'function' &&
51
- '__effect' in action.exec);
52
- });
53
- var _c = __read((0, utils_1.partition)(reactEffectActions, function (action) {
54
- return action.exec.__effect === types_1.ReactEffectType.Effect;
55
- }), 2), effectActions = _c[0], layoutEffectActions = _c[1];
56
- (_a = effectActionsRef.current).push.apply(_a, __spreadArray([], __read(effectActions.map(function (effectAction) { return [effectAction, currentState]; })), false));
57
- (_b = layoutEffectActionsRef.current).push.apply(_b, __spreadArray([], __read(layoutEffectActions.map(function (layoutEffectAction) { return [layoutEffectAction, currentState]; })), false));
58
- }
59
- });
60
- return function () {
61
- sub.unsubscribe();
62
- };
63
- }, []);
64
- // this is somewhat weird - this should always be flushed within useLayoutEffect
65
- // but we don't want to receive warnings about useLayoutEffect being used on the server
66
- // so we have to use `useIsomorphicLayoutEffect` to silence those warnings
67
- (0, use_isomorphic_layout_effect_1.default)(function () {
68
- while (layoutEffectActionsRef.current.length) {
69
- var _a = __read(layoutEffectActionsRef.current.shift(), 2), layoutEffectAction = _a[0], effectState = _a[1];
70
- executeEffect(layoutEffectAction, effectState);
71
- }
72
- }); // https://github.com/statelyai/xstate/pull/1202#discussion_r429677773
73
- (0, react_1.useEffect)(function () {
74
- while (effectActionsRef.current.length) {
75
- var _a = __read(effectActionsRef.current.shift(), 2), effectAction = _a[0], effectState = _a[1];
76
- executeEffect(effectAction, effectState);
77
- }
78
- });
79
- }
80
- exports.useReactEffectActions = useReactEffectActions;
@@ -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
@@ -1,74 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.useSelector = void 0;
4
- var react_1 = require("react");
5
- var use_subscription_1 = require("use-subscription");
6
- var use_isomorphic_layout_effect_1 = require("use-isomorphic-layout-effect");
7
- var useActor_1 = require("./useActor");
8
- var utils_1 = require("./utils");
9
- function isService(actor) {
10
- return 'state' in actor && 'machine' in actor;
11
- }
12
- var defaultCompare = function (a, b) { return a === b; };
13
- var defaultGetSnapshot = function (a) {
14
- return isService(a)
15
- ? (0, utils_1.getServiceSnapshot)(a)
16
- : (0, useActor_1.isActorWithState)(a)
17
- ? a.state
18
- : undefined;
19
- };
20
- function useSelector(actor, selector, compare, getSnapshot) {
21
- if (compare === void 0) { compare = defaultCompare; }
22
- if (getSnapshot === void 0) { getSnapshot = defaultGetSnapshot; }
23
- var latestSelectorRef = (0, react_1.useRef)(selector);
24
- var subscription = (0, react_1.useMemo)(function () {
25
- var snapshot = getSnapshot(actor);
26
- var current = selector(snapshot);
27
- var notifySubscriber;
28
- return {
29
- getSnapshot: function () { return snapshot; },
30
- getCurrentValue: function () { return current; },
31
- setCurrentValue: function (newCurrent) {
32
- current = newCurrent;
33
- notifySubscriber === null || notifySubscriber === void 0 ? void 0 : notifySubscriber();
34
- },
35
- subscribe: function (callback) {
36
- notifySubscriber = callback;
37
- var sub = actor.subscribe(function (emitted) {
38
- snapshot = emitted;
39
- var next = latestSelectorRef.current(emitted);
40
- if (!compare(current, next)) {
41
- current = next;
42
- callback();
43
- }
44
- });
45
- return function () {
46
- sub.unsubscribe();
47
- };
48
- }
49
- };
50
- // intentionally omit `getSnapshot` and `compare`
51
- // - `getSnapshot`: it is only supposed to read the "initial" snapshot of an actor
52
- // - `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)
53
- }, [actor]);
54
- var currentSelected = (0, use_subscription_1.useSubscription)(subscription);
55
- var currentChanged = false;
56
- if (latestSelectorRef.current !== selector) {
57
- var selected = selector(subscription.getSnapshot());
58
- if (!compare(currentSelected, selected)) {
59
- currentChanged = true;
60
- currentSelected = selected;
61
- }
62
- }
63
- (0, use_isomorphic_layout_effect_1.default)(function () {
64
- latestSelectorRef.current = selector;
65
- // this condition should not be required, but setState bailouts are currently buggy: https://github.com/facebook/react/issues/22654
66
- if (currentChanged) {
67
- // required so we don't cause a rerender by setting state (this could create infinite rerendering loop with inline selectors)
68
- // 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
69
- subscription.setCurrentValue(currentSelected);
70
- }
71
- });
72
- return currentSelected;
73
- }
74
- exports.useSelector = useSelector;
package/lib/useSpawn.d.ts DELETED
@@ -1,10 +0,0 @@
1
- import { ActorRef, Behavior, EventObject } from 'xstate';
2
- /**
3
- * React hook that spawns an `ActorRef` with the specified `behavior`.
4
- * The returned `ActorRef` can be used with the `useActor(actorRef)` hook.
5
- *
6
- * @param behavior The actor behavior to spawn
7
- * @returns An ActorRef with the specified `behavior`
8
- */
9
- export declare function useSpawn<TState, TEvent extends EventObject>(behavior: Behavior<TEvent, TState>): ActorRef<TEvent, TState>;
10
- //# sourceMappingURL=useSpawn.d.ts.map
package/lib/useSpawn.js DELETED
@@ -1,19 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.useSpawn = void 0;
4
- var behaviors_1 = require("xstate/lib/behaviors");
5
- var useConstant_1 = require("./useConstant");
6
- /**
7
- * React hook that spawns an `ActorRef` with the specified `behavior`.
8
- * The returned `ActorRef` can be used with the `useActor(actorRef)` hook.
9
- *
10
- * @param behavior The actor behavior to spawn
11
- * @returns An ActorRef with the specified `behavior`
12
- */
13
- function useSpawn(behavior) {
14
- var actorRef = (0, useConstant_1.default)(function () {
15
- return (0, behaviors_1.spawnBehavior)(behavior);
16
- });
17
- return actorRef;
18
- }
19
- exports.useSpawn = useSpawn;
package/lib/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/lib/utils.js DELETED
@@ -1,58 +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
- var __values = (this && this.__values) || function(o) {
19
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
20
- if (m) return m.call(o);
21
- if (o && typeof o.length === "number") return {
22
- next: function () {
23
- if (o && i >= o.length) o = void 0;
24
- return { value: o && o[i++], done: !o };
25
- }
26
- };
27
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
28
- };
29
- Object.defineProperty(exports, "__esModule", { value: true });
30
- exports.getServiceSnapshot = exports.partition = void 0;
31
- function partition(items, predicate) {
32
- var e_1, _a;
33
- var _b = __read([[], []], 2), truthy = _b[0], falsy = _b[1];
34
- try {
35
- for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
36
- var item = items_1_1.value;
37
- if (predicate(item)) {
38
- truthy.push(item);
39
- }
40
- else {
41
- falsy.push(item);
42
- }
43
- }
44
- }
45
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
46
- finally {
47
- try {
48
- if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
49
- }
50
- finally { if (e_1) throw e_1.error; }
51
- }
52
- return [truthy, falsy];
53
- }
54
- exports.partition = partition;
55
- function getServiceSnapshot(service) {
56
- return service.status !== 0 ? service.state : service.machine.initialState;
57
- }
58
- exports.getServiceSnapshot = getServiceSnapshot;