Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@xstate/react

Package Overview
Dependencies
Maintainers
3
Versions
79
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@xstate/react - npm Package Compare versions

Comparing version 2.0.1 to 3.0.0

25

CHANGELOG.md
# Changelog
## 3.0.0
### Major Changes
- [#2939](https://github.com/statelyai/xstate/pull/2939) [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf) Thanks [@Andarist](https://github.com/Andarist)! - This package now accepts React 18 as a peer dep and the implementation has been rewritten to use [`use-sync-external-store`](https://www.npmjs.com/package/use-sync-external-store) package. This doesn't break compatibility with older versions of React since we are using the shim to keep compatibility with those older versions.
* [#2939](https://github.com/statelyai/xstate/pull/2939) [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf) Thanks [@Andarist](https://github.com/Andarist)! - `asEffect` and `asLayoutEffect` action creators were removed. They were not fitting the React model that well and could lead to issues as their existence suggested that they are easy to use.
To execute actions at those exact times you can always either just call your stuff directly from those effects or send events to the machine from those effects and execute explicit actions in response to said events.
- [#2939](https://github.com/statelyai/xstate/pull/2939) [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf) Thanks [@Andarist](https://github.com/Andarist)! - The signatures of `useMachine` and `useService` integrating with `@xstate/fsm` were changed. They now only accept a single generic each (`TMachine` and `TService` respectively). This has been done to match their signatures with the related hooks that integrate with `xstate` itself.
### Patch Changes
- [#2939](https://github.com/statelyai/xstate/pull/2939) [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf) Thanks [@Andarist](https://github.com/Andarist)! - In v2 we have changed signatures of `useMachine` and `useInterpret`. Instead of accepting a list of generics they now only support a single generic: `TMachine`. This change, erroneously, was only introduced to types targeting TS@4.x but the types targeting previous TS releases were still using the older signatures. This has now been fixed and users of older TS versions should now be able to leverage typegen with `@xstate/react`.
* [#2939](https://github.com/statelyai/xstate/pull/2939) [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf) Thanks [@Andarist](https://github.com/Andarist)! - `useMachine` for `xstate` now correctly rerenders with the initial state when the internal service is being restarted. This might happen during Fast Refresh and now you shouldn't be able to observe this stale state that didn't match the actual state of the service.
- [#2939](https://github.com/statelyai/xstate/pull/2939) [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf) Thanks [@Andarist](https://github.com/Andarist)! - `useMachine` for `@xstate/fsm` now starts the service in an effect. This avoids side-effects in render and improves the compatibility with `StrictMode`.
* [#2939](https://github.com/statelyai/xstate/pull/2939) [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf) Thanks [@Andarist](https://github.com/Andarist)! - Implementations given to `useMachine` targeting `@xstate/fsm` are now updated in a layout effect. This avoid some stale closure problems for actions that are executed in response to events sent from layout effects.
* Updated dependencies [[`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf), [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf)]:
- @xstate/fsm@2.0.0
## 2.0.1

@@ -4,0 +29,0 @@

56

dist/xstate-react-fsm.umd.min.js

@@ -1,2 +0,40 @@

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("@xstate/fsm")):"function"==typeof define&&define.amd?define(["exports","react","@xstate/fsm"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).XStateReactFSM={},e.React,e.XStateFSM)}(this,(function(e,t,r){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var u=n(t);
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@xstate/fsm"),require("react")):"function"==typeof define&&define.amd?define(["exports","@xstate/fsm","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).XStateReactFSM={},e.XStateFSM,e.React)}(this,(function(e,t,n){"use strict";function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function u(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var o=r(n),c=u(n);var a=n.useLayoutEffect;function f(e){var t={exports:{}};return e(t,t.exports),t.exports
/**
* @license React
* use-sync-external-store-shim.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/}var i="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},s=o.default.useState,l=o.default.useEffect,d=o.default.useLayoutEffect,v=o.default.useDebugValue;function p(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!i(e,n)}catch(e){return!0}}var b="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(e,t){var n=t(),r=s({inst:{value:n,getSnapshot:t}}),u=r[0].inst,o=r[1];return d((function(){u.value=n,u.getSnapshot=t,p(u)&&o({inst:u})}),[e,n,t]),l((function(){return p(u)&&o({inst:u}),e((function(){p(u)&&o({inst:u})}))}),[e]),v(n),n},y={useSyncExternalStore:void 0!==o.default.useSyncExternalStore?o.default.useSyncExternalStore:b};
/**
* @license React
* use-sync-external-store-shim.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
f((function(e,t){}));var S=f((function(e){e.exports=y}));
/**
* @license React
* use-sync-external-store-shim/with-selector.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var h="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},x=S.useSyncExternalStore,E=o.default.useRef,g=o.default.useEffect,j=o.default.useMemo,m=o.default.useDebugValue,O={useSyncExternalStoreWithSelector:function(e,t,n,r,u){var o=E(null);if(null===o.current){var c={hasValue:!1,value:null};o.current=c}else c=o.current;o=j((function(){function e(e){if(!f){if(f=!0,o=e,e=r(e),void 0!==u&&c.hasValue){var t=c.value;if(u(t,e))return a=t}return a=e}if(t=a,h(o,e))return t;var n=r(e);return void 0!==u&&u(t,n)?t:(o=e,a=n)}var o,a,f=!1,i=void 0===n?null:n;return[function(){return e(t())},null===i?void 0:function(){return e(i())}]}),[t,n,r,u]);var a=x(e,o[0],o[1]);return g((function(){c.hasValue=!0,c.value=a}),[a]),m(a),a}};
/**
* @license React
* use-sync-external-store-shim/with-selector.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
f((function(e,t){}));var w=f((function(e){e.exports=O}));function M(e){return e}var _=function(e,t){return!1===t.changed};function R(e){var t=n.useCallback((function(){return function(e){var t;return e.subscribe((function(e){t=e})).unsubscribe(),t}(e)}),[e]),r=n.useCallback((function(t){return e.subscribe(t).unsubscribe}),[e]);return[w.useSyncExternalStoreWithSelector(r,t,t,M,_),e.send,e]}e.useMachine=function(e,r){var u,o,f=n.useRef(),i=
/*! *****************************************************************************

@@ -15,15 +53,3 @@ Copyright (c) Microsoft Corporation.

PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */function o(e){var t={exports:{}};return e(t,t.exports),t.exports
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/}var i=Object.getOwnPropertySymbols,c=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;function f(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}var s=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(t).map((function(e){return t[e]})).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach((function(e){n[e]=e})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var r,n,u=f(e),o=1;o<arguments.length;o++){for(var s in r=Object(arguments[o]))c.call(r,s)&&(u[s]=r[s]);if(i){n=i(r);for(var l=0;l<n.length;l++)a.call(r,n[l])&&(u[n[l]]=r[n[l]])}}return u},l={useSubscription:function(e){var t=e.getCurrentValue,r=e.subscribe,n=u.default.useState((function(){return{getCurrentValue:t,subscribe:r,value:t()}}));e=n[0];var o=n[1];return n=e.value,e.getCurrentValue===t&&e.subscribe===r||(n=t(),o({getCurrentValue:t,subscribe:r,value:n})),u.default.useDebugValue(n),u.default.useEffect((function(){function e(){if(!n){var e=t();o((function(n){return n.getCurrentValue!==t||n.subscribe!==r||n.value===e?n:s({},n,{value:e})}))}}var n=!1,u=r(e);return e(),function(){n=!0,u()}}),[t,r]),n}},b=(o((function(e,t){})),o((function(e){e.exports=l})));
/** @license React vundefined
* use-subscription.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var p=function(e){var t;return e.subscribe((function(e){t=e})).unsubscribe(),t};e.useMachine=function(e,n){var u,o,i=(u=function(){return r.interpret(r.createMachine(e.config,n||e._options)).start()},(o=t.useRef()).current||(o.current={v:u()}),o.current.v),c=function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,u,o=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)i.push(n.value)}catch(e){u={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(u)throw u.error}}return i}(t.useState((function(){return p(i)})),2),a=c[0],f=c[1];return t.useEffect((function(){n&&(i._machine._options=n)})),t.useEffect((function(){return i.subscribe(f),function(){i.stop()}}),[]),[a,i.send,i]},e.useService=function(e){var r=t.useMemo((function(){var t=p(e);return{getCurrentValue:function(){return t},subscribe:function(r){return e.subscribe((function(e){!1!==e.changed&&(t=e,r())})).unsubscribe}}}),[e]);return[b.useSubscription(r),e.send,e]},Object.defineProperty(e,"__esModule",{value:!0})}));
***************************************************************************** */
function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,u,o=n.call(e),c=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)c.push(r.value)}catch(e){u={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(u)throw u.error}}return c}((u=function(){var n=[],u=t.interpret(t.createMachine(e.config,r||e._options)),o=u.send;return u.send=function(e){u.status!==t.InterpreterStatus.NotStarted?(o(e),f.current=u.state):n.push(e)},[u,n]},(o=c.useRef()).current||(o.current={v:u()}),o.current.v),2),s=i[0],l=i[1];a((function(){r&&(s._machine._options=r)}));var d=R(s);return n.useEffect((function(){return s.start(f.current),l.forEach(s.send),f.current=s.state,function(){s.stop()}}),[]),d},e.useService=R,Object.defineProperty(e,"__esModule",{value:!0})}));

@@ -1,23 +0,5 @@

!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react"),require("xstate")):"function"==typeof define&&define.amd?define(["exports","react","xstate"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateReact={},t.React,t.XState)}(this,(function(t,e,n){"use strict";function r(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var u,o=r(e),c=function(){return(c=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var u in e=arguments[n])Object.prototype.hasOwnProperty.call(e,u)&&(t[u]=e[u]);return t}).apply(this,arguments)};
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */function i(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var u=0;for(r=Object.getOwnPropertySymbols(t);u<r.length;u++)e.indexOf(r[u])<0&&Object.prototype.propertyIsEnumerable.call(t,r[u])&&(n[r[u]]=t[r[u]])}return n}function a(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,u,o=n.call(t),c=[];try{for(;(void 0===e||e-- >0)&&!(r=o.next()).done;)c.push(r.value)}catch(t){u={error:t}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(u)throw u.error}}return c}function f(t,e,n){if(n||2===arguments.length)for(var r,u=0,o=e.length;u<o;u++)!r&&u in e||(r||(r=Array.prototype.slice.call(e,0,u)),r[u]=e[u]);return t.concat(r||Array.prototype.slice.call(e))}!function(t){t[t.Effect=1]="Effect",t[t.LayoutEffect=2]="LayoutEffect"}(u||(u={}));var s=e.useLayoutEffect;function l(t){var n=e.useRef();return n.current||(n.current={v:t()}),n.current.v}function v(t,e){var n,r,u=a([[],[]],2),o=u[0],c=u[1];try{for(var i=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}(t),f=i.next();!f.done;f=i.next()){var s=f.value;e(s)?o.push(s):c.push(s)}}catch(t){n={error:t}}finally{try{f&&!f.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return[o,c]}function p(t,e){(0,t.exec)(e.context,e._event.data,{action:t,state:e,_event:e._event})()}function b(t){var n=e.useRef([]),r=e.useRef([]);s((function(){var e=t.subscribe((function(t){var e,o;if(t.actions.length){var c=a(v(t.actions.filter((function(t){return"function"==typeof t.exec&&"__effect"in t.exec})),(function(t){return t.exec.__effect===u.Effect})),2),i=c[0],s=c[1];(e=n.current).push.apply(e,f([],a(i.map((function(e){return[e,t]}))),!1)),(o=r.current).push.apply(o,f([],a(s.map((function(e){return[e,t]}))),!1))}}));return function(){e.unsubscribe()}}),[]),s((function(){for(;r.current.length;){var t=a(r.current.shift(),2);p(t[0],t[1])}})),e.useEffect((function(){for(;n.current.length;){var t=a(n.current.shift(),2);p(t[0],t[1])}}))}function y(t,e,n){if("object"==typeof t)return t;var r=function(){};return{next:t,error:e||r,complete:n||r}}function d(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];var u=a(e,2),o=u[0],f=void 0===o?{}:o,v=u[1],p=l((function(){return"function"==typeof t?t():t})),d=f.context,h=f.guards,g=f.actions,O=f.services,j=f.delays,m=f.state,S=i(f,["context","guards","actions","services","delays","state"]),x=f.activities,w=l((function(){var t={context:d,guards:h,actions:g,activities:x,services:O,delays:j},e=p.withConfig(t,(function(){return c(c({},p.context),d)}));return n.interpret(e,c({deferEvents:!0},S))}));return s((function(){var t;return v&&(t=w.subscribe(y(v))),function(){null==t||t.unsubscribe()}}),[v]),s((function(){return w.start(m?n.State.create(m):void 0),function(){w.stop()}}),[]),s((function(){Object.assign(w.machine.options.actions,g),Object.assign(w.machine.options.guards,h),Object.assign(w.machine.options.activities,x),Object.assign(w.machine.options.services,O),Object.assign(w.machine.options.delays,j)}),[g,h,x,O,j]),b(w),w}function h(t,e){var n=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return function(){return t.apply(void 0,f([],a(e),!1))}};return Object.defineProperties(n,{name:{value:"effect:".concat(t.name)},__effect:{value:e}}),n}function g(t){return"state"in t}function O(t){return"deferred"in t}var j=function(){};function m(t){return"getSnapshot"in t?t.getSnapshot():g(t)?t.state:void 0}function S(t){var e={exports:{}};return t(e,e.exports),e.exports
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/}var x=Object.getOwnPropertySymbols,w=Object.prototype.hasOwnProperty,E=Object.prototype.propertyIsEnumerable;function C(t){if(null==t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}var _=function(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de","5"===Object.getOwnPropertyNames(t)[0])return!1;for(var e={},n=0;n<10;n++)e["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(e).map((function(t){return e[t]})).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach((function(t){r[t]=t})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(t){return!1}}()?Object.assign:function(t,e){for(var n,r,u=C(t),o=1;o<arguments.length;o++){for(var c in n=Object(arguments[o]))w.call(n,c)&&(u[c]=n[c]);if(x){r=x(n);for(var i=0;i<r.length;i++)E.call(n,r[i])&&(u[r[i]]=n[r[i]])}}return u},P={useSubscription:function(t){var e=t.getCurrentValue,n=t.subscribe,r=o.default.useState((function(){return{getCurrentValue:e,subscribe:n,value:e()}}));t=r[0];var u=r[1];return r=t.value,t.getCurrentValue===e&&t.subscribe===n||(r=e(),u({getCurrentValue:e,subscribe:n,value:r})),o.default.useDebugValue(r),o.default.useEffect((function(){function t(){if(!r){var t=e();u((function(r){return r.getCurrentValue!==e||r.subscribe!==n||r.value===t?r:_({},r,{value:t})}))}}var r=!1,o=n(t);return t(),function(){r=!0,o()}}),[e,n]),r}},V=(S((function(t,e){})),S((function(t){t.exports=P})));
/** @license React vundefined
* use-subscription.production.min.js
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react"),require("xstate")):"function"==typeof define&&define.amd?define(["exports","react","xstate"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateReact={},t.React,t.XState)}(this,(function(t,e,n){"use strict";function r(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}function u(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach((function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})),e.default=t,Object.freeze(e)}var a=r(e),o=u(e),i=function(){return(i=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var u in e=arguments[n])Object.prototype.hasOwnProperty.call(e,u)&&(t[u]=e[u]);return t}).apply(this,arguments)};function c(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,u,a=n.call(t),o=[];try{for(;(void 0===e||e-- >0)&&!(r=a.next()).done;)o.push(r.value)}catch(t){u={error:t}}finally{try{r&&!r.done&&(n=a.return)&&n.call(a)}finally{if(u)throw u.error}}return o}function s(t){var e={exports:{}};return t(e,e.exports),e.exports
/**
* @license React
* use-sync-external-store-shim.production.min.js
*

@@ -28,2 +10,31 @@ * Copyright (c) Facebook, Inc. and its affiliates.

* LICENSE file in the root directory of this source tree.
*/var R=function(t,e){return t===e},k=function(t){return"state"in(n=t)&&"machine"in n?0!==(e=t).status?e.state:e.machine.initialState:g(t)?t.state:void 0;var e,n};t.asEffect=function(t){return h(t,u.Effect)},t.asLayoutEffect=function(t){return h(t,u.LayoutEffect)},t.useActor=function(t,n){void 0===n&&(n=m);var r=e.useRef(t),u=e.useRef([]),o=a(e.useState((function(){return n(t)})),2),c=o[0],i=o[1],f=l((function(){return function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=t[0],o=r.current;O(o)&&o.deferred?u.current.push(n):o.send(n)}}));return s((function(){r.current=t,i(n(t));for(var e=t.subscribe({next:function(t){return i(t)},error:j,complete:j});u.current.length>0;){var o=u.current.shift();t.send(o)}return function(){e.unsubscribe()}}),[t]),[c,f]},t.useInterpret=d,t.useMachine=function(t){for(var r=[],u=1;u<arguments.length;u++)r[u-1]=arguments[u];var o=a(r,1),c=o[0],i=void 0===c?{}:c,f=e.useCallback((function(t){var e=void 0===t.changed&&Object.keys(t.children).length;(t.changed||e)&&p(t)}),[]),s=d(t,i,f),l=a(e.useState((function(){var t=s.machine.initialState;return i.state?n.State.create(i.state):t})),2),v=l[0],p=l[1];return[v,s.send,s]},t.useSelector=function(t,n,r,u){void 0===r&&(r=R),void 0===u&&(u=k);var o=e.useRef(n),c=e.useMemo((function(){var e,c=u(t),i=n(c);return{getSnapshot:function(){return c},getCurrentValue:function(){return i},setCurrentValue:function(t){i=t,null==e||e()},subscribe:function(n){e=n;var u=t.subscribe((function(t){c=t;var e=o.current(t);r(i,e)||(i=e,n())}));return function(){u.unsubscribe()}}}}),[t]),i=V.useSubscription(c),a=!1;if(o.current!==n){var f=n(c.getSnapshot());r(i,f)||(a=!0,i=f)}return s((function(){o.current=n,a&&c.setCurrentValue(i)})),i},t.useSpawn=function(t){return l((function(){return n.spawnBehavior(t)}))},Object.defineProperty(t,"__esModule",{value:!0})}));
*/}var f="function"==typeof Object.is?Object.is:function(t,e){return t===e&&(0!==t||1/t==1/e)||t!=t&&e!=e},l=a.default.useState,v=a.default.useEffect,d=a.default.useLayoutEffect,p=a.default.useDebugValue;function b(t){var e=t.getSnapshot;t=t.value;try{var n=e();return!f(t,n)}catch(t){return!0}}var y="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(t,e){return e()}:function(t,e){var n=e(),r=l({inst:{value:n,getSnapshot:e}}),u=r[0].inst,a=r[1];return d((function(){u.value=n,u.getSnapshot=e,b(u)&&a({inst:u})}),[t,n,e]),v((function(){return b(u)&&a({inst:u}),t((function(){b(u)&&a({inst:u})}))}),[t]),p(n),n},h={useSyncExternalStore:void 0!==a.default.useSyncExternalStore?a.default.useSyncExternalStore:y};
/**
* @license React
* use-sync-external-store-shim.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
s((function(t,e){}));var S=s((function(t){t.exports=h}));
/**
* @license React
* use-sync-external-store-shim/with-selector.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var g="function"==typeof Object.is?Object.is:function(t,e){return t===e&&(0!==t||1/t==1/e)||t!=t&&e!=e},O=S.useSyncExternalStore,x=a.default.useRef,j=a.default.useEffect,m=a.default.useMemo,E=a.default.useDebugValue,w={useSyncExternalStoreWithSelector:function(t,e,n,r,u){var a=x(null);if(null===a.current){var o={hasValue:!1,value:null};a.current=o}else o=a.current;a=m((function(){function t(t){if(!c){if(c=!0,a=t,t=r(t),void 0!==u&&o.hasValue){var e=o.value;if(u(e,t))return i=e}return i=t}if(e=i,g(a,t))return e;var n=r(t);return void 0!==u&&u(e,n)?e:(a=t,i=n)}var a,i,c=!1,s=void 0===n?null:n;return[function(){return t(e())},null===s?void 0:function(){return t(s())}]}),[e,n,r,u]);var i=O(t,a[0],a[1]);return j((function(){o.hasValue=!0,o.value=i}),[i]),E(i),i}};
/**
* @license React
* use-sync-external-store-shim/with-selector.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
s((function(t,e){}));var k=s((function(t){t.exports=w})),C=e.useLayoutEffect;function P(t){var e=o.useRef();return e.current||(e.current={v:t()}),e.current.v}function I(t,e){var r=P((function(){return"function"==typeof t?t():t})),u=e.context,a=e.guards,o=e.actions,c=e.activities,s=e.services,f=e.delays;e.state;var l=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var u=0;for(r=Object.getOwnPropertySymbols(t);u<r.length;u++)e.indexOf(r[u])<0&&Object.prototype.propertyIsEnumerable.call(t,r[u])&&(n[r[u]]=t[r[u]])}return n}(e,["context","guards","actions","activities","services","delays","state"]),v=P((function(){var t={context:u,guards:a,actions:o,activities:c,services:s,delays:f},e=r.withConfig(t,(function(){return i(i({},r.context),u)}));return n.interpret(e,l)}));return C((function(){Object.assign(v.machine.options.actions,o),Object.assign(v.machine.options.guards,a),Object.assign(v.machine.options.activities,c),Object.assign(v.machine.options.services,s),Object.assign(v.machine.options.delays,f)}),[o,a,c,s,f]),v}function R(t){return t}function V(t){return"state"in t}function M(t){return"deferred"in t}function N(t){return"getSnapshot"in t?t.getSnapshot():V(t)?t.state:void 0}var _=function(t,e){return t===e},D=function(t){return"state"in(n=t)&&"machine"in n?0!==(e=t).status?e.state:e.machine.initialState:V(t)?t.state:void 0;var e,n};t.useActor=function(t,n){void 0===n&&(n=N);var r=e.useRef(t),u=e.useRef([]),a=e.useCallback((function(e){return t.subscribe(e).unsubscribe}),[t]),o=e.useCallback((function(){return n(t)}),[t,n]),i=S.useSyncExternalStore(a,o,o),c=P((function(){return function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=t[0],a=r.current;M(a)&&a.deferred?u.current.push(n):a.send(n)}}));return C((function(){for(r.current=t;u.current.length>0;){var e=u.current.shift();t.send(e)}}),[t]),[i,c]},t.useInterpret=function(t){for(var r=[],u=1;u<arguments.length;u++)r[u-1]=arguments[u];var a=c(r,2),o=a[0],i=void 0===o?{}:o,s=a[1],f=I(t,i);return e.useEffect((function(){if(s){var t=f.subscribe(n.toObserver(s));return function(){t.unsubscribe()}}}),[s]),e.useEffect((function(){var t=i.state;return f.start(t?n.State.create(t):void 0),function(){f.stop(),f.status=n.InterpreterStatus.NotStarted}}),[]),f},t.useMachine=function(t){for(var r=[],u=1;u<arguments.length;u++)r[u-1]=arguments[u];var a=c(r,1),o=a[0],i=void 0===o?{}:o,s=I(t,i),f=e.useCallback((function(){return s.status===n.InterpreterStatus.NotStarted?i.state?n.State.create(i.state):s.machine.initialState:s.state}),[s]),l=e.useCallback((function(t,e){if(s.status===n.InterpreterStatus.NotStarted)return!0;var r=void 0===e.changed&&(Object.keys(e.children).length>0||"boolean"==typeof t.changed);return!(e.changed||r)}),[s]),v=e.useCallback((function(t){return s.subscribe(t).unsubscribe}),[s]),d=k.useSyncExternalStoreWithSelector(v,f,f,R,l);return e.useEffect((function(){var t=i.state;return s.start(t?n.State.create(t):void 0),function(){s.stop(),s.status=n.InterpreterStatus.NotStarted}}),[]),[d,s.send,s]},t.useSelector=function(t,n,r,u){void 0===r&&(r=_),void 0===u&&(u=D);var a=e.useCallback((function(e){return t.subscribe(e).unsubscribe}),[t]),o=e.useCallback((function(){return u(t)}),[t,u]);return k.useSyncExternalStoreWithSelector(a,o,o,n,r)},t.useSpawn=function(t){return P((function(){return n.spawnBehavior(t)}))},Object.defineProperty(t,"__esModule",{value:!0})}));

@@ -1,20 +0,4 @@

import { StateMachine, EventObject, Typestate } from '@xstate/fsm';
export declare function useMachine<TContext extends object, TEvent extends EventObject = EventObject, TState extends Typestate<TContext> = {
value: any;
context: TContext;
}>(stateMachine: StateMachine.Machine<TContext, TEvent, TState>, options?: {
actions?: StateMachine.ActionMap<TContext, TEvent>;
}): [
StateMachine.State<TContext, TEvent, TState>,
StateMachine.Service<TContext, TEvent, TState>['send'],
StateMachine.Service<TContext, TEvent, TState>
];
export declare function useService<TContext extends object, TEvent extends EventObject = EventObject, TState extends Typestate<TContext> = {
value: any;
context: TContext;
}>(service: StateMachine.Service<TContext, TEvent, TState>): [
StateMachine.State<TContext, TEvent, TState>,
StateMachine.Service<TContext, TEvent, TState>['send'],
StateMachine.Service<TContext, TEvent, TState>
];
import { MachineImplementationsFrom, ServiceFrom, StateFrom, StateMachine } from '@xstate/fsm';
export declare function useMachine<TMachine extends StateMachine.AnyMachine>(stateMachine: TMachine, options?: MachineImplementationsFrom<TMachine>): [StateFrom<TMachine>, ServiceFrom<TMachine>['send'], ServiceFrom<TMachine>];
export declare function useService<TService extends StateMachine.AnyService>(service: TService): [StateFrom<TService>, TService['send'], TService];
//# sourceMappingURL=fsm.d.ts.map

@@ -17,6 +17,10 @@ var __read = (this && this.__read) || function (o, n) {

};
import { useState, useEffect, useMemo } from 'react';
import { interpret, createMachine } from '@xstate/fsm';
import { useSubscription } from 'use-subscription';
import { createMachine, interpret, InterpreterStatus } from '@xstate/fsm';
import { useCallback, useEffect, useRef, useState } from 'react';
import useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';
import useConstant from './useConstant';
function identity(a) {
return a;
}
var getServiceState = function (service) {

@@ -32,2 +36,3 @@ var currentValue;

export function useMachine(stateMachine, options) {
var persistedStateRef = useRef();
if (process.env.NODE_ENV !== 'production') {

@@ -40,7 +45,17 @@ var _a = __read(useState(stateMachine), 1), initialMachine = _a[0];

}
var service = useConstant(function () {
return interpret(createMachine(stateMachine.config, options ? options : stateMachine._options)).start();
});
var _b = __read(useState(function () { return getServiceState(service); }), 2), state = _b[0], setState = _b[1];
useEffect(function () {
var _b = __read(useConstant(function () {
var queue = [];
var service = interpret(createMachine(stateMachine.config, options ? options : stateMachine._options));
var send = service.send;
service.send = function (event) {
if (service.status === InterpreterStatus.NotStarted) {
queue.push(event);
return;
}
send(event);
persistedStateRef.current = service.state;
};
return [service, queue];
}), 2), service = _b[0], queue = _b[1];
useIsomorphicLayoutEffect(function () {
if (options) {

@@ -50,4 +65,7 @@ service._machine._options = options;

});
var useServiceResult = useService(service);
useEffect(function () {
service.subscribe(setState);
service.start(persistedStateRef.current);
queue.forEach(service.send);
persistedStateRef.current = service.state;
return function () {

@@ -57,22 +75,13 @@ service.stop();

}, []);
return [state, service.send, service];
return useServiceResult;
}
var isEqual = function (_prevState, nextState) { return nextState.changed === false; };
export function useService(service) {
var subscription = useMemo(function () {
var currentState = getServiceState(service);
return {
getCurrentValue: function () { return currentState; },
subscribe: function (callback) {
var unsubscribe = service.subscribe(function (state) {
if (state.changed !== false) {
currentState = state;
callback();
}
}).unsubscribe;
return unsubscribe;
}
};
var getSnapshot = useCallback(function () { return getServiceState(service); }, [service]);
var subscribe = useCallback(function (handleStoreChange) {
var unsubscribe = service.subscribe(handleStoreChange).unsubscribe;
return unsubscribe;
}, [service]);
var state = useSubscription(subscription);
return [state, service.send, service];
var storeSnapshot = useSyncExternalStoreWithSelector(subscribe, getSnapshot, getSnapshot, identity, isEqual);
return [storeSnapshot, service.send, service];
}

@@ -1,2 +0,2 @@

export { useMachine, asEffect, asLayoutEffect } from './useMachine';
export { useMachine } from './useMachine';
export { useActor } from './useActor';

@@ -3,0 +3,0 @@ export { useInterpret } from './useInterpret';

@@ -1,2 +0,2 @@

export { useMachine, asEffect, asLayoutEffect } from './useMachine';
export { useMachine } from './useMachine';
export { useActor } from './useActor';

@@ -3,0 +3,0 @@ export { useInterpret } from './useInterpret';

@@ -1,16 +0,5 @@

import { ActionMeta, ActionObject, EventObject, State, StateConfig } from 'xstate';
import { EventObject, StateConfig } from 'xstate';
export declare type MaybeLazy<T> = T | (() => T);
export declare type NoInfer<T> = [T][T extends any ? 0 : any];
export declare type Prop<T, K> = K extends keyof T ? T[K] : never;
export declare enum ReactEffectType {
Effect = 1,
LayoutEffect = 2
}
export interface ReactActionFunction<TContext, TEvent extends EventObject> {
(context: TContext, event: TEvent, meta: ActionMeta<TContext, TEvent>): () => void;
__effect: ReactEffectType;
}
export interface ReactActionObject<TContext, TEvent extends EventObject> extends ActionObject<TContext, TEvent> {
exec: ReactActionFunction<TContext, TEvent>;
}
export interface UseMachineOptions<TContext, TEvent extends EventObject> {

@@ -27,6 +16,2 @@ /**

}
export declare type ActionStateTuple<TContext, TEvent extends EventObject> = [
ReactActionObject<TContext, TEvent>,
State<TContext, TEvent>
];
//# sourceMappingURL=types.d.ts.map

@@ -1,5 +0,1 @@

export var ReactEffectType;
(function (ReactEffectType) {
ReactEffectType[ReactEffectType["Effect"] = 1] = "Effect";
ReactEffectType[ReactEffectType["LayoutEffect"] = 2] = "LayoutEffect";
})(ReactEffectType || (ReactEffectType = {}));
export {};

@@ -1,20 +0,5 @@

var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
import { useState, useRef } from 'react';
import { useRef, useCallback } from 'react';
import useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';
import useConstant from './useConstant';
import { useSyncExternalStore } from 'use-sync-external-store/shim';
export function isActorWithState(actorRef) {

@@ -26,5 +11,2 @@ return 'state' in actorRef;

}
var noop = function () {
/* ... */
};
function defaultGetSnapshot(actorRef) {

@@ -41,3 +23,11 @@ return 'getSnapshot' in actorRef

var deferredEventsRef = useRef([]);
var _a = __read(useState(function () { return getSnapshot(actorRef); }), 2), current = _a[0], setCurrent = _a[1];
var subscribe = useCallback(function (handleStoreChange) {
var unsubscribe = actorRef.subscribe(handleStoreChange).unsubscribe;
return unsubscribe;
}, [actorRef]);
var boundGetSnapshot = useCallback(function () { return getSnapshot(actorRef); }, [
actorRef,
getSnapshot
]);
var storeSnapshot = useSyncExternalStore(subscribe, boundGetSnapshot, boundGetSnapshot);
var send = useConstant(function () { return function () {

@@ -65,8 +55,2 @@ var args = [];

actorRefRef.current = actorRef;
setCurrent(getSnapshot(actorRef));
var subscription = actorRef.subscribe({
next: function (emitted) { return setCurrent(emitted); },
error: noop,
complete: noop
});
// Dequeue deferred events from the previous deferred actorRef

@@ -77,7 +61,4 @@ while (deferredEventsRef.current.length > 0) {

}
return function () {
subscription.unsubscribe();
};
}, [actorRef]);
return [current, send];
return [storeSnapshot, send];
}

@@ -1,4 +0,5 @@

import { AnyStateMachine, AreAllImplementationsAssumedToBeProvided, InternalMachineOptions, InterpreterFrom, InterpreterOptions, Observer, StateFrom } from 'xstate';
import { AnyInterpreter, AnyStateMachine, AreAllImplementationsAssumedToBeProvided, InternalMachineOptions, InterpreterFrom, InterpreterOptions, MachineOptions, Observer, StateFrom } from 'xstate';
import { MaybeLazy } from './types';
import { UseMachineOptions } from './useMachine';
export declare function useIdleInterpreter(getMachine: MaybeLazy<AnyStateMachine>, options: Partial<InterpreterOptions> & Partial<UseMachineOptions<unknown, never>> & Partial<MachineOptions<unknown, never>>): AnyInterpreter;
declare type RestParams<TMachine extends AnyStateMachine> = AreAllImplementationsAssumedToBeProvided<TMachine['__TResolvedTypesMeta']> extends false ? [

@@ -5,0 +6,0 @@ options: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta'], true>,

@@ -39,26 +39,7 @@ var __assign = (this && this.__assign) || function () {

};
import { useState } from 'react';
import { useEffect, useState } from 'react';
import useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';
import { interpret, State } from 'xstate';
import { interpret, InterpreterStatus, State, toObserver } from 'xstate';
import useConstant from './useConstant';
import { useReactEffectActions } from './useReactEffectActions';
// copied from core/src/utils.ts
// it avoids a breaking change between this package and XState which is its peer dep
function toObserver(nextHandler, errorHandler, completionHandler) {
if (typeof nextHandler === 'object') {
return nextHandler;
}
var noop = function () { return void 0; };
return {
next: nextHandler,
error: errorHandler || noop,
complete: completionHandler || noop
};
}
export function useInterpret(getMachine) {
var _a = [];
for (var _i = 1; _i < arguments.length; _i++) {
_a[_i - 1] = arguments[_i];
}
var _b = __read(_a, 2), _c = _b[0], options = _c === void 0 ? {} : _c, observerOrListener = _b[1];
export function useIdleInterpreter(getMachine, options) {
var machine = useConstant(function () {

@@ -69,3 +50,3 @@ return typeof getMachine === 'function' ? getMachine() : getMachine;

typeof getMachine !== 'function') {
var _d = __read(useState(machine), 1), initialMachine = _d[0];
var _a = __read(useState(machine), 1), initialMachine = _a[0];
if (getMachine !== initialMachine) {

@@ -76,5 +57,3 @@ console.warn('Machine given to `useMachine` has changed between renders. This is not supported and might lead to unexpected results.\n' +

}
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"]);
// it's not defined in `TypegenMachineOptions` so we can't just unpack this property here freely
var activities = options.activities;
var context = options.context, guards = options.guards, actions = options.actions, activities = options.activities, services = options.services, delays = options.delays, rehydratedState = options.state, interpreterOptions = __rest(options, ["context", "guards", "actions", "activities", "services", "delays", "state"]);
var service = useConstant(function () {

@@ -90,19 +69,4 @@ var machineConfig = {

var machineWithConfig = machine.withConfig(machineConfig, function () { return (__assign(__assign({}, machine.context), context)); });
return interpret(machineWithConfig, __assign({ deferEvents: true }, interpreterOptions));
return interpret(machineWithConfig, interpreterOptions);
});
useIsomorphicLayoutEffect(function () {
var sub;
if (observerOrListener) {
sub = service.subscribe(toObserver(observerOrListener));
}
return function () {
sub === null || sub === void 0 ? void 0 : sub.unsubscribe();
};
}, [observerOrListener]);
useIsomorphicLayoutEffect(function () {
service.start(rehydratedState ? State.create(rehydratedState) : undefined);
return function () {
service.stop();
};
}, []);
// Make sure options are kept updated when they change.

@@ -118,4 +82,29 @@ // This mutation assignment is safe because the service instance is only used

}, [actions, guards, activities, services, delays]);
useReactEffectActions(service);
return service;
}
export function useInterpret(getMachine) {
var _a = [];
for (var _i = 1; _i < arguments.length; _i++) {
_a[_i - 1] = arguments[_i];
}
var _b = __read(_a, 2), _c = _b[0], options = _c === void 0 ? {} : _c, observerOrListener = _b[1];
var service = useIdleInterpreter(getMachine, options);
useEffect(function () {
if (!observerOrListener) {
return;
}
var sub = service.subscribe(toObserver(observerOrListener));
return function () {
sub.unsubscribe();
};
}, [observerOrListener]);
useEffect(function () {
var rehydratedState = options.state;
service.start(rehydratedState ? State.create(rehydratedState) : undefined);
return function () {
service.stop();
service.status = InterpreterStatus.NotStarted;
};
}, []);
return service;
}

@@ -1,5 +0,3 @@

import { ActionFunction, AnyStateMachine, AreAllImplementationsAssumedToBeProvided, EventObject, InternalMachineOptions, InterpreterFrom, InterpreterOptions, StateConfig, StateFrom } from 'xstate';
import { MaybeLazy, Prop, ReactActionFunction } from './types';
export declare function asEffect<TContext, TEvent extends EventObject>(exec: ActionFunction<TContext, TEvent>): ReactActionFunction<TContext, TEvent>;
export declare function asLayoutEffect<TContext, TEvent extends EventObject>(exec: ActionFunction<TContext, TEvent>): ReactActionFunction<TContext, TEvent>;
import { AnyStateMachine, AreAllImplementationsAssumedToBeProvided, EventObject, InternalMachineOptions, InterpreterFrom, InterpreterOptions, StateConfig, StateFrom } from 'xstate';
import { MaybeLazy, Prop } from './types';
export interface UseMachineOptions<TContext, TEvent extends EventObject> {

@@ -6,0 +4,0 @@ /**

@@ -17,38 +17,9 @@ var __read = (this && this.__read) || function (o, n) {

};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
import { useCallback, useState } from 'react';
import { State } from 'xstate';
import { ReactEffectType } from './types';
import { useInterpret } from './useInterpret';
function createReactActionFunction(exec, tag) {
var effectExec = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
// don't execute; just return
return function () {
return exec.apply(void 0, __spreadArray([], __read(args), false));
};
};
Object.defineProperties(effectExec, {
name: { value: "effect:".concat(exec.name) },
__effect: { value: tag }
});
return effectExec;
import { useCallback, useEffect } from 'react';
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';
import { InterpreterStatus, State } from 'xstate';
import { useIdleInterpreter } from './useInterpret';
function identity(a) {
return a;
}
export function asEffect(exec) {
return createReactActionFunction(exec, ReactEffectType.Effect);
}
export function asLayoutEffect(exec) {
return createReactActionFunction(exec, ReactEffectType.LayoutEffect);
}
export function useMachine(getMachine) {

@@ -60,3 +31,17 @@ var _a = [];

var _b = __read(_a, 1), _c = _b[0], options = _c === void 0 ? {} : _c;
var listener = useCallback(function (nextState) {
// using `useIdleInterpreter` allows us to subscribe to the service *before* we start it
// so we don't miss any notifications
var service = useIdleInterpreter(getMachine, options);
var getSnapshot = useCallback(function () {
if (service.status === InterpreterStatus.NotStarted) {
return (options.state
? State.create(options.state)
: service.machine.initialState);
}
return service.state;
}, [service]);
var isEqual = useCallback(function (prevState, nextState) {
if (service.status === InterpreterStatus.NotStarted) {
return true;
}
// Only change the current state if:

@@ -67,15 +52,21 @@ // - the incoming state is the "live" initial state (since it might have new actors)

// The "live" initial state will have .changed === undefined.
var initialStateChanged = nextState.changed === undefined && Object.keys(nextState.children).length;
if (nextState.changed || initialStateChanged) {
setState(nextState);
}
var initialStateChanged = nextState.changed === undefined &&
(Object.keys(nextState.children).length > 0 ||
typeof prevState.changed === 'boolean');
return !(nextState.changed || initialStateChanged);
}, [service]);
var subscribe = useCallback(function (handleStoreChange) {
var unsubscribe = service.subscribe(handleStoreChange).unsubscribe;
return unsubscribe;
}, [service]);
var storeSnapshot = useSyncExternalStoreWithSelector(subscribe, getSnapshot, getSnapshot, identity, isEqual);
useEffect(function () {
var rehydratedState = options.state;
service.start(rehydratedState ? State.create(rehydratedState) : undefined);
return function () {
service.stop();
service.status = InterpreterStatus.NotStarted;
};
}, []);
var service = useInterpret(getMachine, options, listener);
var _d = __read(useState(function () {
var initialState = service.machine.initialState;
return (options.state
? State.create(options.state)
: initialState);
}), 2), state = _d[0], setState = _d[1];
return [state, service.send, service];
return [storeSnapshot, service.send, service];
}

@@ -1,4 +0,3 @@

import { useMemo, useRef } from 'react';
import { useSubscription } from 'use-subscription';
import useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';
import { useCallback } from 'react';
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';
import { isActorWithState } from './useActor';

@@ -20,52 +19,12 @@ import { getServiceSnapshot } from './utils';

if (getSnapshot === void 0) { getSnapshot = defaultGetSnapshot; }
var latestSelectorRef = useRef(selector);
var subscription = useMemo(function () {
var snapshot = getSnapshot(actor);
var current = selector(snapshot);
var notifySubscriber;
return {
getSnapshot: function () { return snapshot; },
getCurrentValue: function () { return current; },
setCurrentValue: function (newCurrent) {
current = newCurrent;
notifySubscriber === null || notifySubscriber === void 0 ? void 0 : notifySubscriber();
},
subscribe: function (callback) {
notifySubscriber = callback;
var sub = actor.subscribe(function (emitted) {
snapshot = emitted;
var next = latestSelectorRef.current(emitted);
if (!compare(current, next)) {
current = next;
callback();
}
});
return function () {
sub.unsubscribe();
};
}
};
// intentionally omit `getSnapshot` and `compare`
// - `getSnapshot`: it is only supposed to read the "initial" snapshot of an actor
// - `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)
var subscribe = useCallback(function (handleStoreChange) {
var unsubscribe = actor.subscribe(handleStoreChange).unsubscribe;
return unsubscribe;
}, [actor]);
var currentSelected = useSubscription(subscription);
var currentChanged = false;
if (latestSelectorRef.current !== selector) {
var selected = selector(subscription.getSnapshot());
if (!compare(currentSelected, selected)) {
currentChanged = true;
currentSelected = selected;
}
}
useIsomorphicLayoutEffect(function () {
latestSelectorRef.current = selector;
// this condition should not be required, but setState bailouts are currently buggy: https://github.com/facebook/react/issues/22654
if (currentChanged) {
// required so we don't cause a rerender by setting state (this could create infinite rerendering loop with inline selectors)
// 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
subscription.setCurrentValue(currentSelected);
}
});
return currentSelected;
var boundGetSnapshot = useCallback(function () { return getSnapshot(actor); }, [
actor,
getSnapshot
]);
var selectedSnapshot = useSyncExternalStoreWithSelector(subscribe, boundGetSnapshot, boundGetSnapshot, selector, compare);
return selectedSnapshot;
}

@@ -1,20 +0,4 @@

import { StateMachine, EventObject, Typestate } from '@xstate/fsm';
export declare function useMachine<TContext extends object, TEvent extends EventObject = EventObject, TState extends Typestate<TContext> = {
value: any;
context: TContext;
}>(stateMachine: StateMachine.Machine<TContext, TEvent, TState>, options?: {
actions?: StateMachine.ActionMap<TContext, TEvent>;
}): [
StateMachine.State<TContext, TEvent, TState>,
StateMachine.Service<TContext, TEvent, TState>['send'],
StateMachine.Service<TContext, TEvent, TState>
];
export declare function useService<TContext extends object, TEvent extends EventObject = EventObject, TState extends Typestate<TContext> = {
value: any;
context: TContext;
}>(service: StateMachine.Service<TContext, TEvent, TState>): [
StateMachine.State<TContext, TEvent, TState>,
StateMachine.Service<TContext, TEvent, TState>['send'],
StateMachine.Service<TContext, TEvent, TState>
];
import { MachineImplementationsFrom, ServiceFrom, StateFrom, StateMachine } from '@xstate/fsm';
export declare function useMachine<TMachine extends StateMachine.AnyMachine>(stateMachine: TMachine, options?: MachineImplementationsFrom<TMachine>): [StateFrom<TMachine>, ServiceFrom<TMachine>['send'], ServiceFrom<TMachine>];
export declare function useService<TService extends StateMachine.AnyService>(service: TService): [StateFrom<TService>, TService['send'], TService];
//# sourceMappingURL=fsm.d.ts.map

@@ -20,6 +20,10 @@ "use strict";

exports.useService = exports.useMachine = void 0;
var fsm_1 = require("@xstate/fsm");
var react_1 = require("react");
var fsm_1 = require("@xstate/fsm");
var use_subscription_1 = require("use-subscription");
var use_isomorphic_layout_effect_1 = require("use-isomorphic-layout-effect");
var with_selector_1 = require("use-sync-external-store/shim/with-selector");
var useConstant_1 = require("./useConstant");
function identity(a) {
return a;
}
var getServiceState = function (service) {

@@ -35,2 +39,3 @@ var currentValue;

function useMachine(stateMachine, options) {
var persistedStateRef = (0, react_1.useRef)();
if (process.env.NODE_ENV !== 'production') {

@@ -43,7 +48,17 @@ var _a = __read((0, react_1.useState)(stateMachine), 1), initialMachine = _a[0];

}
var service = (0, useConstant_1.default)(function () {
return (0, fsm_1.interpret)((0, fsm_1.createMachine)(stateMachine.config, options ? options : stateMachine._options)).start();
});
var _b = __read((0, react_1.useState)(function () { return getServiceState(service); }), 2), state = _b[0], setState = _b[1];
(0, react_1.useEffect)(function () {
var _b = __read((0, useConstant_1.default)(function () {
var queue = [];
var service = (0, fsm_1.interpret)((0, fsm_1.createMachine)(stateMachine.config, options ? options : stateMachine._options));
var send = service.send;
service.send = function (event) {
if (service.status === fsm_1.InterpreterStatus.NotStarted) {
queue.push(event);
return;
}
send(event);
persistedStateRef.current = service.state;
};
return [service, queue];
}), 2), service = _b[0], queue = _b[1];
(0, use_isomorphic_layout_effect_1.default)(function () {
if (options) {

@@ -53,4 +68,7 @@ service._machine._options = options;

});
var useServiceResult = useService(service);
(0, react_1.useEffect)(function () {
service.subscribe(setState);
service.start(persistedStateRef.current);
queue.forEach(service.send);
persistedStateRef.current = service.state;
return function () {

@@ -60,24 +78,15 @@ service.stop();

}, []);
return [state, service.send, service];
return useServiceResult;
}
exports.useMachine = useMachine;
var isEqual = function (_prevState, nextState) { return nextState.changed === false; };
function useService(service) {
var subscription = (0, react_1.useMemo)(function () {
var currentState = getServiceState(service);
return {
getCurrentValue: function () { return currentState; },
subscribe: function (callback) {
var unsubscribe = service.subscribe(function (state) {
if (state.changed !== false) {
currentState = state;
callback();
}
}).unsubscribe;
return unsubscribe;
}
};
var getSnapshot = (0, react_1.useCallback)(function () { return getServiceState(service); }, [service]);
var subscribe = (0, react_1.useCallback)(function (handleStoreChange) {
var unsubscribe = service.subscribe(handleStoreChange).unsubscribe;
return unsubscribe;
}, [service]);
var state = (0, use_subscription_1.useSubscription)(subscription);
return [state, service.send, service];
var storeSnapshot = (0, with_selector_1.useSyncExternalStoreWithSelector)(subscribe, getSnapshot, getSnapshot, identity, isEqual);
return [storeSnapshot, service.send, service];
}
exports.useService = useService;

@@ -1,2 +0,2 @@

export { useMachine, asEffect, asLayoutEffect } from './useMachine';
export { useMachine } from './useMachine';
export { useActor } from './useActor';

@@ -3,0 +3,0 @@ export { useInterpret } from './useInterpret';

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSpawn = exports.useSelector = exports.useInterpret = exports.useActor = exports.asLayoutEffect = exports.asEffect = exports.useMachine = void 0;
exports.useSpawn = exports.useSelector = exports.useInterpret = exports.useActor = exports.useMachine = void 0;
var useMachine_1 = require("./useMachine");
Object.defineProperty(exports, "useMachine", { enumerable: true, get: function () { return useMachine_1.useMachine; } });
Object.defineProperty(exports, "asEffect", { enumerable: true, get: function () { return useMachine_1.asEffect; } });
Object.defineProperty(exports, "asLayoutEffect", { enumerable: true, get: function () { return useMachine_1.asLayoutEffect; } });
var useActor_1 = require("./useActor");

@@ -9,0 +7,0 @@ Object.defineProperty(exports, "useActor", { enumerable: true, get: function () { return useActor_1.useActor; } });

@@ -1,16 +0,5 @@

import { ActionMeta, ActionObject, EventObject, State, StateConfig } from 'xstate';
import { EventObject, StateConfig } from 'xstate';
export declare type MaybeLazy<T> = T | (() => T);
export declare type NoInfer<T> = [T][T extends any ? 0 : any];
export declare type Prop<T, K> = K extends keyof T ? T[K] : never;
export declare enum ReactEffectType {
Effect = 1,
LayoutEffect = 2
}
export interface ReactActionFunction<TContext, TEvent extends EventObject> {
(context: TContext, event: TEvent, meta: ActionMeta<TContext, TEvent>): () => void;
__effect: ReactEffectType;
}
export interface ReactActionObject<TContext, TEvent extends EventObject> extends ActionObject<TContext, TEvent> {
exec: ReactActionFunction<TContext, TEvent>;
}
export interface UseMachineOptions<TContext, TEvent extends EventObject> {

@@ -27,6 +16,2 @@ /**

}
export declare type ActionStateTuple<TContext, TEvent extends EventObject> = [
ReactActionObject<TContext, TEvent>,
State<TContext, TEvent>
];
//# sourceMappingURL=types.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReactEffectType = void 0;
var ReactEffectType;
(function (ReactEffectType) {
ReactEffectType[ReactEffectType["Effect"] = 1] = "Effect";
ReactEffectType[ReactEffectType["LayoutEffect"] = 2] = "LayoutEffect";
})(ReactEffectType = exports.ReactEffectType || (exports.ReactEffectType = {}));
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -23,2 +7,3 @@ exports.useActor = exports.isActorWithState = void 0;

var useConstant_1 = require("./useConstant");
var shim_1 = require("use-sync-external-store/shim");
function isActorWithState(actorRef) {

@@ -31,5 +16,2 @@ return 'state' in actorRef;

}
var noop = function () {
/* ... */
};
function defaultGetSnapshot(actorRef) {

@@ -46,3 +28,11 @@ return 'getSnapshot' in actorRef

var deferredEventsRef = (0, react_1.useRef)([]);
var _a = __read((0, react_1.useState)(function () { return getSnapshot(actorRef); }), 2), current = _a[0], setCurrent = _a[1];
var subscribe = (0, react_1.useCallback)(function (handleStoreChange) {
var unsubscribe = actorRef.subscribe(handleStoreChange).unsubscribe;
return unsubscribe;
}, [actorRef]);
var boundGetSnapshot = (0, react_1.useCallback)(function () { return getSnapshot(actorRef); }, [
actorRef,
getSnapshot
]);
var storeSnapshot = (0, shim_1.useSyncExternalStore)(subscribe, boundGetSnapshot, boundGetSnapshot);
var send = (0, useConstant_1.default)(function () { return function () {

@@ -70,8 +60,2 @@ var args = [];

actorRefRef.current = actorRef;
setCurrent(getSnapshot(actorRef));
var subscription = actorRef.subscribe({
next: function (emitted) { return setCurrent(emitted); },
error: noop,
complete: noop
});
// Dequeue deferred events from the previous deferred actorRef

@@ -82,8 +66,5 @@ while (deferredEventsRef.current.length > 0) {

}
return function () {
subscription.unsubscribe();
};
}, [actorRef]);
return [current, send];
return [storeSnapshot, send];
}
exports.useActor = useActor;

@@ -1,4 +0,5 @@

import { AnyStateMachine, AreAllImplementationsAssumedToBeProvided, InternalMachineOptions, InterpreterFrom, InterpreterOptions, Observer, StateFrom } from 'xstate';
import { AnyInterpreter, AnyStateMachine, AreAllImplementationsAssumedToBeProvided, InternalMachineOptions, InterpreterFrom, InterpreterOptions, MachineOptions, Observer, StateFrom } from 'xstate';
import { MaybeLazy } from './types';
import { UseMachineOptions } from './useMachine';
export declare function useIdleInterpreter(getMachine: MaybeLazy<AnyStateMachine>, options: Partial<InterpreterOptions> & Partial<UseMachineOptions<unknown, never>> & Partial<MachineOptions<unknown, never>>): AnyInterpreter;
declare type RestParams<TMachine extends AnyStateMachine> = AreAllImplementationsAssumedToBeProvided<TMachine['__TResolvedTypesMeta']> extends false ? [

@@ -5,0 +6,0 @@ options: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta'], true>,

@@ -41,3 +41,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.useInterpret = void 0;
exports.useInterpret = exports.useIdleInterpreter = void 0;
var react_1 = require("react");

@@ -47,22 +47,3 @@ var use_isomorphic_layout_effect_1 = require("use-isomorphic-layout-effect");

var useConstant_1 = require("./useConstant");
var useReactEffectActions_1 = require("./useReactEffectActions");
// copied from core/src/utils.ts
// it avoids a breaking change between this package and XState which is its peer dep
function toObserver(nextHandler, errorHandler, completionHandler) {
if (typeof nextHandler === 'object') {
return nextHandler;
}
var noop = function () { return void 0; };
return {
next: nextHandler,
error: errorHandler || noop,
complete: completionHandler || noop
};
}
function useInterpret(getMachine) {
var _a = [];
for (var _i = 1; _i < arguments.length; _i++) {
_a[_i - 1] = arguments[_i];
}
var _b = __read(_a, 2), _c = _b[0], options = _c === void 0 ? {} : _c, observerOrListener = _b[1];
function useIdleInterpreter(getMachine, options) {
var machine = (0, useConstant_1.default)(function () {

@@ -73,3 +54,3 @@ return typeof getMachine === 'function' ? getMachine() : getMachine;

typeof getMachine !== 'function') {
var _d = __read((0, react_1.useState)(machine), 1), initialMachine = _d[0];
var _a = __read((0, react_1.useState)(machine), 1), initialMachine = _a[0];
if (getMachine !== initialMachine) {

@@ -80,5 +61,3 @@ console.warn('Machine given to `useMachine` has changed between renders. This is not supported and might lead to unexpected results.\n' +

}
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"]);
// it's not defined in `TypegenMachineOptions` so we can't just unpack this property here freely
var activities = options.activities;
var context = options.context, guards = options.guards, actions = options.actions, activities = options.activities, services = options.services, delays = options.delays, rehydratedState = options.state, interpreterOptions = __rest(options, ["context", "guards", "actions", "activities", "services", "delays", "state"]);
var service = (0, useConstant_1.default)(function () {

@@ -94,19 +73,4 @@ var machineConfig = {

var machineWithConfig = machine.withConfig(machineConfig, function () { return (__assign(__assign({}, machine.context), context)); });
return (0, xstate_1.interpret)(machineWithConfig, __assign({ deferEvents: true }, interpreterOptions));
return (0, xstate_1.interpret)(machineWithConfig, interpreterOptions);
});
(0, use_isomorphic_layout_effect_1.default)(function () {
var sub;
if (observerOrListener) {
sub = service.subscribe(toObserver(observerOrListener));
}
return function () {
sub === null || sub === void 0 ? void 0 : sub.unsubscribe();
};
}, [observerOrListener]);
(0, use_isomorphic_layout_effect_1.default)(function () {
service.start(rehydratedState ? xstate_1.State.create(rehydratedState) : undefined);
return function () {
service.stop();
};
}, []);
// Make sure options are kept updated when they change.

@@ -122,5 +86,31 @@ // This mutation assignment is safe because the service instance is only used

}, [actions, guards, activities, services, delays]);
(0, useReactEffectActions_1.useReactEffectActions)(service);
return service;
}
exports.useIdleInterpreter = useIdleInterpreter;
function useInterpret(getMachine) {
var _a = [];
for (var _i = 1; _i < arguments.length; _i++) {
_a[_i - 1] = arguments[_i];
}
var _b = __read(_a, 2), _c = _b[0], options = _c === void 0 ? {} : _c, observerOrListener = _b[1];
var service = useIdleInterpreter(getMachine, options);
(0, react_1.useEffect)(function () {
if (!observerOrListener) {
return;
}
var sub = service.subscribe((0, xstate_1.toObserver)(observerOrListener));
return function () {
sub.unsubscribe();
};
}, [observerOrListener]);
(0, react_1.useEffect)(function () {
var rehydratedState = options.state;
service.start(rehydratedState ? xstate_1.State.create(rehydratedState) : undefined);
return function () {
service.stop();
service.status = xstate_1.InterpreterStatus.NotStarted;
};
}, []);
return service;
}
exports.useInterpret = useInterpret;

@@ -1,5 +0,3 @@

import { ActionFunction, AnyStateMachine, AreAllImplementationsAssumedToBeProvided, EventObject, InternalMachineOptions, InterpreterFrom, InterpreterOptions, StateConfig, StateFrom } from 'xstate';
import { MaybeLazy, Prop, ReactActionFunction } from './types';
export declare function asEffect<TContext, TEvent extends EventObject>(exec: ActionFunction<TContext, TEvent>): ReactActionFunction<TContext, TEvent>;
export declare function asLayoutEffect<TContext, TEvent extends EventObject>(exec: ActionFunction<TContext, TEvent>): ReactActionFunction<TContext, TEvent>;
import { AnyStateMachine, AreAllImplementationsAssumedToBeProvided, EventObject, InternalMachineOptions, InterpreterFrom, InterpreterOptions, StateConfig, StateFrom } from 'xstate';
import { MaybeLazy, Prop } from './types';
export interface UseMachineOptions<TContext, TEvent extends EventObject> {

@@ -6,0 +4,0 @@ /**

@@ -18,42 +18,11 @@ "use strict";

};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useMachine = exports.asLayoutEffect = exports.asEffect = void 0;
exports.useMachine = void 0;
var react_1 = require("react");
var with_selector_1 = require("use-sync-external-store/shim/with-selector");
var xstate_1 = require("xstate");
var types_1 = require("./types");
var useInterpret_1 = require("./useInterpret");
function createReactActionFunction(exec, tag) {
var effectExec = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
// don't execute; just return
return function () {
return exec.apply(void 0, __spreadArray([], __read(args), false));
};
};
Object.defineProperties(effectExec, {
name: { value: "effect:".concat(exec.name) },
__effect: { value: tag }
});
return effectExec;
function identity(a) {
return a;
}
function asEffect(exec) {
return createReactActionFunction(exec, types_1.ReactEffectType.Effect);
}
exports.asEffect = asEffect;
function asLayoutEffect(exec) {
return createReactActionFunction(exec, types_1.ReactEffectType.LayoutEffect);
}
exports.asLayoutEffect = asLayoutEffect;
function useMachine(getMachine) {

@@ -65,3 +34,17 @@ var _a = [];

var _b = __read(_a, 1), _c = _b[0], options = _c === void 0 ? {} : _c;
var listener = (0, react_1.useCallback)(function (nextState) {
// using `useIdleInterpreter` allows us to subscribe to the service *before* we start it
// so we don't miss any notifications
var service = (0, useInterpret_1.useIdleInterpreter)(getMachine, options);
var getSnapshot = (0, react_1.useCallback)(function () {
if (service.status === xstate_1.InterpreterStatus.NotStarted) {
return (options.state
? xstate_1.State.create(options.state)
: service.machine.initialState);
}
return service.state;
}, [service]);
var isEqual = (0, react_1.useCallback)(function (prevState, nextState) {
if (service.status === xstate_1.InterpreterStatus.NotStarted) {
return true;
}
// Only change the current state if:

@@ -72,16 +55,22 @@ // - the incoming state is the "live" initial state (since it might have new actors)

// The "live" initial state will have .changed === undefined.
var initialStateChanged = nextState.changed === undefined && Object.keys(nextState.children).length;
if (nextState.changed || initialStateChanged) {
setState(nextState);
}
var initialStateChanged = nextState.changed === undefined &&
(Object.keys(nextState.children).length > 0 ||
typeof prevState.changed === 'boolean');
return !(nextState.changed || initialStateChanged);
}, [service]);
var subscribe = (0, react_1.useCallback)(function (handleStoreChange) {
var unsubscribe = service.subscribe(handleStoreChange).unsubscribe;
return unsubscribe;
}, [service]);
var storeSnapshot = (0, with_selector_1.useSyncExternalStoreWithSelector)(subscribe, getSnapshot, getSnapshot, identity, isEqual);
(0, react_1.useEffect)(function () {
var rehydratedState = options.state;
service.start(rehydratedState ? xstate_1.State.create(rehydratedState) : undefined);
return function () {
service.stop();
service.status = xstate_1.InterpreterStatus.NotStarted;
};
}, []);
var service = (0, useInterpret_1.useInterpret)(getMachine, options, listener);
var _d = __read((0, react_1.useState)(function () {
var initialState = service.machine.initialState;
return (options.state
? xstate_1.State.create(options.state)
: initialState);
}), 2), state = _d[0], setState = _d[1];
return [state, service.send, service];
return [storeSnapshot, service.send, service];
}
exports.useMachine = useMachine;

@@ -5,4 +5,3 @@ "use strict";

var react_1 = require("react");
var use_subscription_1 = require("use-subscription");
var use_isomorphic_layout_effect_1 = require("use-isomorphic-layout-effect");
var with_selector_1 = require("use-sync-external-store/shim/with-selector");
var useActor_1 = require("./useActor");

@@ -24,53 +23,13 @@ var utils_1 = require("./utils");

if (getSnapshot === void 0) { getSnapshot = defaultGetSnapshot; }
var latestSelectorRef = (0, react_1.useRef)(selector);
var subscription = (0, react_1.useMemo)(function () {
var snapshot = getSnapshot(actor);
var current = selector(snapshot);
var notifySubscriber;
return {
getSnapshot: function () { return snapshot; },
getCurrentValue: function () { return current; },
setCurrentValue: function (newCurrent) {
current = newCurrent;
notifySubscriber === null || notifySubscriber === void 0 ? void 0 : notifySubscriber();
},
subscribe: function (callback) {
notifySubscriber = callback;
var sub = actor.subscribe(function (emitted) {
snapshot = emitted;
var next = latestSelectorRef.current(emitted);
if (!compare(current, next)) {
current = next;
callback();
}
});
return function () {
sub.unsubscribe();
};
}
};
// intentionally omit `getSnapshot` and `compare`
// - `getSnapshot`: it is only supposed to read the "initial" snapshot of an actor
// - `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)
var subscribe = (0, react_1.useCallback)(function (handleStoreChange) {
var unsubscribe = actor.subscribe(handleStoreChange).unsubscribe;
return unsubscribe;
}, [actor]);
var currentSelected = (0, use_subscription_1.useSubscription)(subscription);
var currentChanged = false;
if (latestSelectorRef.current !== selector) {
var selected = selector(subscription.getSnapshot());
if (!compare(currentSelected, selected)) {
currentChanged = true;
currentSelected = selected;
}
}
(0, use_isomorphic_layout_effect_1.default)(function () {
latestSelectorRef.current = selector;
// this condition should not be required, but setState bailouts are currently buggy: https://github.com/facebook/react/issues/22654
if (currentChanged) {
// required so we don't cause a rerender by setting state (this could create infinite rerendering loop with inline selectors)
// 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
subscription.setCurrentValue(currentSelected);
}
});
return currentSelected;
var boundGetSnapshot = (0, react_1.useCallback)(function () { return getSnapshot(actor); }, [
actor,
getSnapshot
]);
var selectedSnapshot = (0, with_selector_1.useSyncExternalStoreWithSelector)(subscribe, boundGetSnapshot, boundGetSnapshot, selector, compare);
return selectedSnapshot;
}
exports.useSelector = useSelector;
{
"name": "@xstate/react",
"version": "2.0.1",
"version": "3.0.0",
"description": "XState tools for React",

@@ -55,5 +55,5 @@ "keywords": [

"peerDependencies": {
"@xstate/fsm": "^1.6.5",
"react": "^16.8.0 || ^17.0.0",
"xstate": "^4.30.3"
"@xstate/fsm": "^2.0.0",
"react": "^16.8.0 || ^17.0.0 || ^18.0.0",
"xstate": "^4.31.0"
},

@@ -70,3 +70,3 @@ "peerDependenciesMeta": {

"use-isomorphic-layout-effect": "^1.0.0",
"use-subscription": "^1.3.0"
"use-sync-external-store": "^1.0.0"
},

@@ -76,6 +76,7 @@ "devDependencies": {

"@rollup/plugin-node-resolve": "^11.0.1",
"@testing-library/react": "^8.0.9",
"@testing-library/react": "^13.0.0",
"@types/jsdom": "^12.2.3",
"@types/react": "^16.9.11",
"@types/react-dom": "^16.9.4",
"@types/react": "^17.0.43",
"@types/react-dom": "^17.0.14",
"@types/use-sync-external-store": "^0.0.3",
"@xstate/fsm": "*",

@@ -86,5 +87,5 @@ "jest": "^26.6.3",

"lerna-alias": "3.0.3-0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"rollup": "^2.35.1",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"rollup": "^2.69.0",
"rollup-plugin-replace": "^2.2.0",

@@ -91,0 +92,0 @@ "rollup-plugin-terser": "^5.1.2",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc