@xstate/react
Advanced tools
Comparing version 1.6.3 to 3.2.2
@@ -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"),require("xstate/lib/behaviors")):"function"==typeof define&&define.amd?define(["exports","react","xstate","xstate/lib/behaviors"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateReact={},t.React,t.XState,t.behaviors)}(this,(function(t,e,n,r){"use strict";function u(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var i,o=u(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 a(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,u,i=n.call(t),o=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(t){u={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(u)throw u.error}}return o}function f(t,e,n){if(n||2===arguments.length)for(var r,u=0,i=e.length;u<i;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"}(i||(i={}));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),i=u[0],o=u[1];try{for(var c=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=c.next();!f.done;f=c.next()){var s=f.value;e(s)?i.push(s):o.push(s)}}catch(t){n={error:t}}finally{try{f&&!f.done&&(r=c.return)&&r.call(c)}finally{if(n)throw n.error}}return[i,o]}function p(t,e){(0,t.exec)(e.context,e._event.data,{action:t,state:e,_event:e._event})()}function b(t,r,u){void 0===r&&(r={});var o=l((function(){return"function"==typeof t?t():t})),b=r.context,d=r.guards,y=r.actions,h=r.activities,g=r.services,O=r.delays,j=r.state,m=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}(r,["context","guards","actions","activities","services","delays","state"]),x=l((function(){var t={context:b,guards:d,actions:y,activities:h,services:g,delays:O},e=o.withConfig(t,(function(){return c(c({},o.context),b)}));return n.interpret(e,c({deferEvents:!0},m))}));return s((function(){var t;return u&&(t=x.subscribe(function(t,e,n){if("object"==typeof t)return t;var r=function(){};return{next:t,error:e||r,complete:n||r}}(u))),function(){null==t||t.unsubscribe()}}),[u]),s((function(){return x.start(j?n.State.create(j):void 0),function(){x.stop()}}),[]),s((function(){Object.assign(x.machine.options.actions,y),Object.assign(x.machine.options.guards,d),Object.assign(x.machine.options.activities,h),Object.assign(x.machine.options.services,g),Object.assign(x.machine.options.delays,O)}),[y,d,h,g,O]),function(t){var n=e.useRef([]),r=e.useRef([]);s((function(){var e=t.subscribe((function(t){var e,u;if(t.actions.length){var o=a(v(t.actions.filter((function(t){return"function"==typeof t.exec&&"__effect"in t.exec})),(function(t){return t.exec.__effect===i.Effect})),2),c=o[0],s=o[1];(e=n.current).push.apply(e,f([],a(c.map((function(e){return[e,t]}))),!1)),(u=r.current).push.apply(u,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])}}))}(x),x}function d(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 y(t){return"state"in t}function h(t){return"deferred"in t}var g=function(){};function O(t){return"getSnapshot"in t?t.getSnapshot():y(t)?t.state:void 0}function j(t,n){void 0===n&&(n=O);var r=e.useRef(t),u=e.useRef([]),i=a(e.useState((function(){return n(t)})),2),o=i[0],c=i[1],f=l((function(){return function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=t[0],i=r.current;h(i)&&i.deferred?u.current.push(n):i.send(n)}}));return s((function(){r.current=t,c(n(t));for(var e=t.subscribe({next:function(t){return c(t)},error:g,complete:g});u.current.length>0;){var i=u.current.shift();t.send(i)}return function(){e.unsubscribe()}}),[t]),[o,f]}function m(t){var e={exports:{}};return t(e,e.exports),e.exports | ||
/* | ||
object-assign | ||
(c) Sindre Sorhus | ||
@license MIT | ||
*/}var x=Object.getOwnPropertySymbols,S=Object.prototype.hasOwnProperty,w=Object.prototype.propertyIsEnumerable;function E(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=E(t),i=1;i<arguments.length;i++){for(var o in n=Object(arguments[i]))S.call(n,o)&&(u[o]=n[o]);if(x){r=x(n);for(var c=0;c<r.length;c++)w.call(n,r[c])&&(u[r[c]]=n[r[c]])}}return u},C={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,i=n(t);return t(),function(){r=!0,i()}}),[e,n]),r}},P=(m((function(t,e){})),m((function(t){t.exports=C}))); | ||
/** @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 o=r(e),a=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,o=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=o.next()).done;)a.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 a}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 V=function(t,e){return t===e},R=function(t){return"state"in(n=t)&&"machine"in n?0!==("status"in(e=t)?e.status:e._status)?e.state:e.machine.initialState:y(t)?t.state:void 0;var e,n};t.asEffect=function(t){return d(t,i.Effect)},t.asLayoutEffect=function(t){return d(t,i.LayoutEffect)},t.useActor=j,t.useInterpret=b,t.useMachine=function(t,r){void 0===r&&(r={});var u=e.useCallback((function(t){var e=void 0===t.changed&&Object.keys(t.children).length;(t.changed||e)&&f(t)}),[]),i=b(t,r,u),o=a(e.useState((function(){var t=i.machine.initialState;return r.state?n.State.create(r.state):t})),2),c=o[0],f=o[1];return[c,i.send,i]},t.useSelector=function(t,n,r,u){void 0===r&&(r=V),void 0===u&&(u=R);var i=e.useRef(n),o=e.useMemo((function(){var e,o=u(t),c=n(o);return{getSnapshot:function(){return o},getCurrentValue:function(){return c},setCurrentValue:function(t){c=t,null==e||e()},subscribe:function(n){e=n;var u=t.subscribe((function(t){o=t;var e=i.current(t);r(c,e)||(c=e,n())}));return function(){u.unsubscribe()}}}}),[t]),c=P.useSubscription(o),a=!1;if(i.current!==n){var f=n(o.getSnapshot());r(c,f)||(a=!0,c=f)}return s((function(){i.current=n,a&&o.setCurrentValue(c)})),c},t.useService=function(t){return[a(j(t),1)[0],t.send]},t.useSpawn=function(t){return l((function(){return r.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=o.default.useState,v=o.default.useEffect,d=o.default.useLayoutEffect,p=o.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 h="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,o=r[1];return d((function(){u.value=n,u.getSnapshot=e,b(u)&&o({inst:u})}),[t,n,e]),v((function(){return b(u)&&o({inst:u}),t((function(){b(u)&&o({inst:u})}))}),[t]),p(n),n},y={useSyncExternalStore:void 0!==o.default.useSyncExternalStore?o.default.useSyncExternalStore:h}; | ||
/** | ||
* @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=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 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,j=o.default.useRef,x=o.default.useEffect,m=o.default.useMemo,E=o.default.useDebugValue,w={useSyncExternalStoreWithSelector:function(t,e,n,r,u){var o=j(null);if(null===o.current){var a={hasValue:!1,value:null};o.current=a}else a=o.current;o=m((function(){function t(t){if(!c){if(c=!0,o=t,t=r(t),void 0!==u&&a.hasValue){var e=a.value;if(u(e,t))return i=e}return i=t}if(e=i,g(o,t))return e;var n=r(t);return void 0!==u&&u(e,n)?e:(o=t,i=n)}var o,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,o[0],o[1]);return x((function(){a.hasValue=!0,a.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=a.useRef();return e.current||(e.current={v:t()}),e.current.v}function R(t,e){var r=P((function(){return"function"==typeof t?t():t})),u=e.context,o=e.guards,a=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:o,actions:a,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,a),Object.assign(v.machine.options.guards,o),Object.assign(v.machine.options.activities,c),Object.assign(v.machine.options.services,s),Object.assign(v.machine.options.delays,f)}),[a,o,c,s,f]),v}function N(t){for(var r=[],u=1;u<arguments.length;u++)r[u-1]=arguments[u];var o=c(r,2),a=o[0],i=void 0===a?{}:a,s=o[1],f=R(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}function I(t){return 0!==t.status?t.getSnapshot():t.machine.initialState}function A(t,e){return t===e?0!==t||0!==e||1/t==1/e:t!=t&&e!=e}function V(t){return"state"in t&&"machine"in t}function M(t,e,r){if(t.status===n.InterpreterStatus.NotStarted)return!0;var u=void 0===r.changed&&(Object.keys(r.children).length>0||"boolean"==typeof e.changed);return!(r.changed||u)}function W(t){return t}function _(t){return t}function q(t){return"state"in t}function D(t){return"deferred"in t}function L(t){return"getSnapshot"in t?V(t)?I(t):t.getSnapshot():q(t)?t.state:void 0}function T(t,n){void 0===n&&(n=L);var r=e.useRef(t),u=e.useRef([]),o=e.useCallback((function(e){return t.subscribe(e).unsubscribe}),[t]),a=e.useCallback((function(){return n(t)}),[t,n]),i=e.useCallback((function(e,n){return V(t)?M(t,e,n):e===n}),[t]),c=k.useSyncExternalStoreWithSelector(o,a,a,_,i),s=P((function(){return function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=t[0],o=r.current;D(o)&&o.deferred?u.current.push(n):o.send(n)}}));return C((function(){for(r.current=t;u.current.length>0;){var e=u.current.shift();t.send(e)}}),[t]),[c,s]}var X=function(t,e){return t===e};function z(t,n,r,u){void 0===r&&(r=X);var o=e.useRef(null),a=e.useCallback((function(e){return t.subscribe(e).unsubscribe}),[t]),i=e.useCallback((function(){return u?u(t):function(t,e){if(V(t)){if(0===t.status&&e.current)return e.current;var n=I(t);return e.current=0===t.status?n:null,n}return q(t)?t.state:void 0}(t,o)}),[t,u]);return k.useSyncExternalStoreWithSelector(a,i,i,n,r)}t.createActorContext=function(t,e,n){var r=a.createContext(null),u=r.Provider;function o(r){var o=r.children,c=r.machine,s=void 0===c?t:c,f=r.options,l=N(s,i(i({},e),f),n);return a.createElement(u,{value:l},o)}function c(){var t=a.useContext(r);if(!t)throw new Error('You used a hook from "'.concat(o.displayName,"\" but it's not inside a <").concat(o.displayName,"> component."));return t}return o.displayName="ActorProvider(".concat(t.id,")"),{Provider:o,useActorRef:c,useActor:function(){return T(c())},useSelector:function(t,e){return z(c(),t,e)}}},t.shallowEqual=function(t,e){if(A(t,e))return!0;if("object"!=typeof t||null===t||"object"!=typeof e||null===e)return!1;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(var u=0;u<n.length;u++)if(!Object.prototype.hasOwnProperty.call(e,n[u])||!A(t[n[u]],e[n[u]]))return!1;return!0},t.useActor=T,t.useInterpret=N,t.useMachine=function(t){for(var r=[],u=1;u<arguments.length;u++)r[u-1]=arguments[u];var o=c(r,1),a=o[0],i=void 0===a?{}:a,s=R(t,i),f=e.useCallback((function(){return s.status===n.InterpreterStatus.NotStarted?i.state?n.State.create(i.state):s.machine.initialState:s.getSnapshot()}),[s]),l=e.useCallback((function(t,e){return M(s,t,e)}),[s]),v=e.useCallback((function(t){return s.subscribe(t).unsubscribe}),[s]),d=k.useSyncExternalStoreWithSelector(v,f,f,W,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=z,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,3 +0,2 @@ | ||
export { useMachine, asEffect, asLayoutEffect } from './useMachine'; | ||
export { useService } from './useService'; | ||
export { useMachine } from './useMachine'; | ||
export { useActor } from './useActor'; | ||
@@ -7,2 +6,4 @@ export { useInterpret } from './useInterpret'; | ||
export { useSpawn } from './useSpawn'; | ||
export { shallowEqual } from './utils'; | ||
export { createActorContext } from './createActorContext'; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -1,3 +0,2 @@ | ||
export { useMachine, asEffect, asLayoutEffect } from './useMachine'; | ||
export { useService } from './useService'; | ||
export { useMachine } from './useMachine'; | ||
export { useActor } from './useActor'; | ||
@@ -7,1 +6,3 @@ export { useInterpret } from './useInterpret'; | ||
export { useSpawn } from './useSpawn'; | ||
export { shallowEqual } from './utils'; | ||
export { createActorContext } from './createActorContext'; |
@@ -1,48 +0,5 @@ | ||
import { ActionMeta, ActionObject, EventObject, State, StateConfig } from 'xstate'; | ||
export declare type Sender<TEvent extends EventObject> = (event: TEvent) => void; | ||
export interface Subscription { | ||
unsubscribe(): void; | ||
} | ||
export interface Observer<T> { | ||
next?: (value: T) => void; | ||
error?: (errorValue: any) => void; | ||
complete: () => void; | ||
} | ||
export interface Subscribable<T> { | ||
subscribe(observer: Observer<T>): Subscription; | ||
subscribe(next: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription; | ||
} | ||
import { EventObject, StateConfig } from 'xstate'; | ||
export declare type MaybeLazy<T> = T | (() => T); | ||
declare type ExcludeType<A> = { | ||
[K in Exclude<keyof A, 'type'>]: A[K]; | ||
}; | ||
declare type ExtractExtraParameters<A, T> = A extends { | ||
type: T; | ||
} ? ExcludeType<A> : never; | ||
declare type ExtractSimple<A> = A extends any ? {} extends ExcludeType<A> ? A : never : never; | ||
declare type NeverIfEmpty<T> = {} extends T ? never : T; | ||
export interface PayloadSender<TEvent extends EventObject> { | ||
/** | ||
* Send an event object or just the event type, if the event has no other payload | ||
*/ | ||
(event: TEvent | ExtractSimple<TEvent>['type']): void; | ||
/** | ||
* Send an event type and its payload | ||
*/ | ||
<K extends TEvent['type']>(eventType: K, payload: NeverIfEmpty<ExtractExtraParameters<TEvent, K>>): void; | ||
} | ||
export interface ActorRef<TEvent extends EventObject, TEmitted = any> extends Subscribable<TEmitted> { | ||
send: Sender<TEvent>; | ||
} | ||
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 declare type NoInfer<T> = [T][T extends any ? 0 : any]; | ||
export declare type Prop<T, K> = K extends keyof T ? T[K] : never; | ||
export interface UseMachineOptions<TContext, TEvent extends EventObject> { | ||
@@ -59,7 +16,2 @@ /** | ||
} | ||
export declare type ActionStateTuple<TContext, TEvent extends EventObject> = [ | ||
ReactActionObject<TContext, TEvent>, | ||
State<TContext, TEvent> | ||
]; | ||
export {}; | ||
//# 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,3 +0,2 @@ | ||
import { Sender } from './types'; | ||
import { ActorRef, EventObject } from 'xstate'; | ||
import { ActorRef, EventObject, Sender } from 'xstate'; | ||
export declare function isActorWithState<T extends ActorRef<any>>(actorRef: T): actorRef is T & { | ||
@@ -4,0 +3,0 @@ state: any; |
@@ -1,20 +0,9 @@ | ||
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 { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector'; | ||
import { getServiceSnapshot, isInterpreterStateEqual, isService } from './utils'; | ||
function identity(a) { | ||
return a; | ||
} | ||
export function isActorWithState(actorRef) { | ||
@@ -26,8 +15,7 @@ return 'state' in actorRef; | ||
} | ||
var noop = function () { | ||
/* ... */ | ||
}; | ||
function defaultGetSnapshot(actorRef) { | ||
return 'getSnapshot' in actorRef | ||
? actorRef.getSnapshot() | ||
? isService(actorRef) | ||
? getServiceSnapshot(actorRef) | ||
: actorRef.getSnapshot() | ||
: isActorWithState(actorRef) | ||
@@ -41,3 +29,14 @@ ? actorRef.state | ||
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 isEqual = useCallback(function (prevState, nextState) { | ||
if (isService(actorRef)) { | ||
return isInterpreterStateEqual(actorRef, prevState, nextState); | ||
} | ||
return prevState === nextState; | ||
}, [actorRef]); | ||
var storeSnapshot = useSyncExternalStoreWithSelector(subscribe, boundGetSnapshot, boundGetSnapshot, identity, isEqual); | ||
var send = useConstant(function () { return function () { | ||
@@ -65,8 +64,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 +70,4 @@ while (deferredEventsRef.current.length > 0) { | ||
} | ||
return function () { | ||
subscription.unsubscribe(); | ||
}; | ||
}, [actorRef]); | ||
return [current, send]; | ||
return [storeSnapshot, send]; | ||
} |
@@ -1,8 +0,14 @@ | ||
import { EventObject, StateMachine, State, Interpreter, InterpreterOptions, MachineOptions, Typestate, Observer } 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 useInterpret<TContext, TEvent extends EventObject, TTypestate extends Typestate<TContext> = { | ||
value: any; | ||
context: TContext; | ||
}>(getMachine: MaybeLazy<StateMachine<TContext, any, TEvent, TTypestate>>, options?: Partial<InterpreterOptions> & Partial<UseMachineOptions<TContext, TEvent>> & Partial<MachineOptions<TContext, TEvent>>, observerOrListener?: Observer<State<TContext, TEvent, any, TTypestate>> | ((value: State<TContext, TEvent, any, TTypestate>) => void)): Interpreter<TContext, any, TEvent, TTypestate>; | ||
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 ? [ | ||
options: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta'], true>, | ||
observerOrListener?: Observer<StateFrom<TMachine>> | ((value: StateFrom<TMachine>) => void) | ||
] : [ | ||
options?: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta']>, | ||
observerOrListener?: Observer<StateFrom<TMachine>> | ((value: StateFrom<TMachine>) => void) | ||
]; | ||
export declare function useInterpret<TMachine extends AnyStateMachine>(getMachine: MaybeLazy<TMachine>, ...[options, observerOrListener]: RestParams<TMachine>): InterpreterFrom<TMachine>; | ||
export {}; | ||
//# sourceMappingURL=useInterpret.d.ts.map |
@@ -39,22 +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, options, observerOrListener) { | ||
if (options === void 0) { options = {}; } | ||
export function useIdleInterpreter(getMachine, options) { | ||
var machine = useConstant(function () { | ||
@@ -82,19 +67,4 @@ return typeof getMachine === 'function' ? getMachine() : getMachine; | ||
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. | ||
@@ -110,4 +80,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 { EventObject, StateMachine, State, Interpreter, InterpreterOptions, MachineOptions, StateConfig, Typestate, ActionFunction } from 'xstate'; | ||
import { MaybeLazy, 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> { | ||
@@ -16,10 +14,10 @@ /** | ||
} | ||
export declare function useMachine<TContext, TEvent extends EventObject, TTypestate extends Typestate<TContext> = { | ||
value: any; | ||
context: TContext; | ||
}>(getMachine: MaybeLazy<StateMachine<TContext, any, TEvent, TTypestate>>, options?: Partial<InterpreterOptions> & Partial<UseMachineOptions<TContext, TEvent>> & Partial<MachineOptions<TContext, TEvent>>): [ | ||
State<TContext, TEvent, any, TTypestate>, | ||
Interpreter<TContext, any, TEvent, TTypestate>['send'], | ||
Interpreter<TContext, any, TEvent, TTypestate> | ||
declare type RestParams<TMachine extends AnyStateMachine> = AreAllImplementationsAssumedToBeProvided<TMachine['__TResolvedTypesMeta']> extends false ? [ | ||
options: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta'], true> | ||
] : [ | ||
options?: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta']> | ||
]; | ||
declare type UseMachineReturn<TMachine extends AnyStateMachine, TInterpreter = InterpreterFrom<TMachine>> = [StateFrom<TMachine>, Prop<TInterpreter, 'send'>, TInterpreter]; | ||
export declare function useMachine<TMachine extends AnyStateMachine>(getMachine: MaybeLazy<TMachine>, ...[options]: RestParams<TMachine>): UseMachineReturn<TMachine>; | ||
export {}; | ||
//# sourceMappingURL=useMachine.d.ts.map |
@@ -17,60 +17,44 @@ 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]; | ||
} | ||
import { useCallback, useEffect } from 'react'; | ||
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector'; | ||
import { InterpreterStatus, State } from 'xstate'; | ||
import { useIdleInterpreter } from './useInterpret'; | ||
import { isInterpreterStateEqual } from './utils'; | ||
function identity(a) { | ||
return a; | ||
} | ||
export function useMachine(getMachine) { | ||
var _a = []; | ||
for (var _i = 1; _i < arguments.length; _i++) { | ||
_a[_i - 1] = arguments[_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]; | ||
var _b = __read(_a, 1), _c = _b[0], options = _c === void 0 ? {} : _c; | ||
// 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); | ||
} | ||
// don't execute; just return | ||
return service.getSnapshot(); | ||
}, [service]); | ||
var isEqual = useCallback(function (prevState, nextState) { | ||
return isInterpreterStateEqual(service, prevState, nextState); | ||
}, [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 () { | ||
return exec.apply(void 0, __spreadArray([], __read(args), false)); | ||
service.stop(); | ||
service.status = InterpreterStatus.NotStarted; | ||
}; | ||
}; | ||
Object.defineProperties(effectExec, { | ||
name: { value: "effect:".concat(exec.name) }, | ||
__effect: { value: tag } | ||
}); | ||
return effectExec; | ||
} | ||
export function asEffect(exec) { | ||
return createReactActionFunction(exec, ReactEffectType.Effect); | ||
} | ||
export function asLayoutEffect(exec) { | ||
return createReactActionFunction(exec, ReactEffectType.LayoutEffect); | ||
} | ||
export function useMachine(getMachine, options) { | ||
if (options === void 0) { options = {}; } | ||
var listener = useCallback(function (nextState) { | ||
// Only change the current state if: | ||
// - the incoming state is the "live" initial state (since it might have new actors) | ||
// - OR the incoming state actually changed. | ||
// | ||
// 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 service = useInterpret(getMachine, options, listener); | ||
var _a = __read(useState(function () { | ||
var initialState = service.machine.initialState; | ||
return (options.state | ||
? State.create(options.state) | ||
: initialState); | ||
}), 2), state = _a[0], setState = _a[1]; | ||
return [state, service.send, service]; | ||
return [storeSnapshot, service.send, service]; | ||
} |
@@ -1,70 +0,33 @@ | ||
import { useMemo, useRef } from 'react'; | ||
import { useSubscription } from 'use-subscription'; | ||
import useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect'; | ||
import { useCallback, useRef } from 'react'; | ||
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector'; | ||
import { isActorWithState } from './useActor'; | ||
import { getServiceSnapshot } from './useService'; | ||
function isService(actor) { | ||
return 'state' in actor && 'machine' in actor; | ||
} | ||
import { getServiceSnapshot, isService } from './utils'; | ||
var defaultCompare = function (a, b) { return a === b; }; | ||
var defaultGetSnapshot = function (a) { | ||
return isService(a) | ||
? getServiceSnapshot(a) | ||
: isActorWithState(a) | ||
? a.state | ||
: undefined; | ||
var defaultGetSnapshot = function (a, initialStateCacheRef) { | ||
if (isService(a)) { | ||
// A status of 0 = interpreter not started | ||
if (a.status === 0 && initialStateCacheRef.current) { | ||
return initialStateCacheRef.current; | ||
} | ||
var snapshot = getServiceSnapshot(a); | ||
initialStateCacheRef.current = a.status === 0 ? snapshot : null; | ||
return snapshot; | ||
} | ||
return isActorWithState(a) ? a.state : undefined; | ||
}; | ||
export function useSelector(actor, selector, compare, getSnapshot) { | ||
if (compare === void 0) { compare = defaultCompare; } | ||
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 initialStateCacheRef = useRef(null); | ||
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; | ||
var boundGetSnapshot = useCallback(function () { | ||
if (getSnapshot) { | ||
return getSnapshot(actor); | ||
} | ||
} | ||
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; | ||
return defaultGetSnapshot(actor, initialStateCacheRef); | ||
}, [actor, getSnapshot]); | ||
var selectedSnapshot = useSyncExternalStoreWithSelector(subscribe, boundGetSnapshot, boundGetSnapshot, selector, compare); | ||
return selectedSnapshot; | ||
} |
@@ -1,2 +0,2 @@ | ||
import { spawnBehavior } from 'xstate/lib/behaviors'; | ||
import { spawnBehavior } from 'xstate'; | ||
import useConstant from './useConstant'; | ||
@@ -3,0 +3,0 @@ /** |
@@ -0,2 +1,7 @@ | ||
import { AnyInterpreter, AnyState, Interpreter } from 'xstate'; | ||
export declare function partition<T, A extends T, B extends T>(items: T[], predicate: (item: T) => item is A): [A[], B[]]; | ||
export declare function getServiceSnapshot<TService extends Interpreter<any, any, any, any>>(service: TService): TService['state']; | ||
export declare function shallowEqual(objA: any, objB: any): boolean; | ||
export declare function isService(actor: any): actor is Interpreter<any, any, any, any>; | ||
export declare function isInterpreterStateEqual(service: AnyInterpreter, prevState: AnyState, nextState: AnyState): boolean; | ||
//# sourceMappingURL=utils.d.ts.map |
@@ -28,2 +28,3 @@ var __read = (this && this.__read) || function (o, n) { | ||
}; | ||
import { InterpreterStatus } from 'xstate'; | ||
export function partition(items, predicate) { | ||
@@ -52,1 +53,53 @@ var e_1, _a; | ||
} | ||
export function getServiceSnapshot(service) { | ||
return service.status !== 0 | ||
? service.getSnapshot() | ||
: service.machine.initialState; | ||
} | ||
// From https://github.com/reduxjs/react-redux/blob/master/src/utils/shallowEqual.ts | ||
function is(x, y) { | ||
if (x === y) { | ||
return x !== 0 || y !== 0 || 1 / x === 1 / y; | ||
} | ||
else { | ||
return x !== x && y !== y; | ||
} | ||
} | ||
export function shallowEqual(objA, objB) { | ||
if (is(objA, objB)) | ||
return true; | ||
if (typeof objA !== 'object' || | ||
objA === null || | ||
typeof objB !== 'object' || | ||
objB === null) { | ||
return false; | ||
} | ||
var keysA = Object.keys(objA); | ||
var keysB = Object.keys(objB); | ||
if (keysA.length !== keysB.length) | ||
return false; | ||
for (var i = 0; i < keysA.length; i++) { | ||
if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || | ||
!is(objA[keysA[i]], objB[keysA[i]])) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
} | ||
export function isService(actor) { | ||
return 'state' in actor && 'machine' in actor; | ||
} | ||
export function isInterpreterStateEqual(service, prevState, nextState) { | ||
if (service.status === InterpreterStatus.NotStarted) { | ||
return true; | ||
} | ||
// Only change the current state if: | ||
// - the incoming state is the "live" initial state (since it might have new actors) | ||
// - OR the incoming state actually changed. | ||
// | ||
// The "live" initial state will have .changed === undefined. | ||
var initialStateChanged = nextState.changed === undefined && | ||
(Object.keys(nextState.children).length > 0 || | ||
typeof prevState.changed === 'boolean'); | ||
return !(nextState.changed || initialStateChanged); | ||
} |
@@ -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,3 +0,2 @@ | ||
export { useMachine, asEffect, asLayoutEffect } from './useMachine'; | ||
export { useService } from './useService'; | ||
export { useMachine } from './useMachine'; | ||
export { useActor } from './useActor'; | ||
@@ -7,2 +6,4 @@ export { useInterpret } from './useInterpret'; | ||
export { useSpawn } from './useSpawn'; | ||
export { shallowEqual } from './utils'; | ||
export { createActorContext } from './createActorContext'; | ||
//# sourceMappingURL=index.d.ts.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.useSpawn = exports.useSelector = exports.useInterpret = exports.useActor = exports.useService = exports.asLayoutEffect = exports.asEffect = exports.useMachine = void 0; | ||
exports.createActorContext = exports.shallowEqual = 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 useService_1 = require("./useService"); | ||
Object.defineProperty(exports, "useService", { enumerable: true, get: function () { return useService_1.useService; } }); | ||
var useActor_1 = require("./useActor"); | ||
@@ -18,1 +14,5 @@ Object.defineProperty(exports, "useActor", { enumerable: true, get: function () { return useActor_1.useActor; } }); | ||
Object.defineProperty(exports, "useSpawn", { enumerable: true, get: function () { return useSpawn_1.useSpawn; } }); | ||
var utils_1 = require("./utils"); | ||
Object.defineProperty(exports, "shallowEqual", { enumerable: true, get: function () { return utils_1.shallowEqual; } }); | ||
var createActorContext_1 = require("./createActorContext"); | ||
Object.defineProperty(exports, "createActorContext", { enumerable: true, get: function () { return createActorContext_1.createActorContext; } }); |
@@ -1,48 +0,5 @@ | ||
import { ActionMeta, ActionObject, EventObject, State, StateConfig } from 'xstate'; | ||
export declare type Sender<TEvent extends EventObject> = (event: TEvent) => void; | ||
export interface Subscription { | ||
unsubscribe(): void; | ||
} | ||
export interface Observer<T> { | ||
next?: (value: T) => void; | ||
error?: (errorValue: any) => void; | ||
complete: () => void; | ||
} | ||
export interface Subscribable<T> { | ||
subscribe(observer: Observer<T>): Subscription; | ||
subscribe(next: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription; | ||
} | ||
import { EventObject, StateConfig } from 'xstate'; | ||
export declare type MaybeLazy<T> = T | (() => T); | ||
declare type ExcludeType<A> = { | ||
[K in Exclude<keyof A, 'type'>]: A[K]; | ||
}; | ||
declare type ExtractExtraParameters<A, T> = A extends { | ||
type: T; | ||
} ? ExcludeType<A> : never; | ||
declare type ExtractSimple<A> = A extends any ? {} extends ExcludeType<A> ? A : never : never; | ||
declare type NeverIfEmpty<T> = {} extends T ? never : T; | ||
export interface PayloadSender<TEvent extends EventObject> { | ||
/** | ||
* Send an event object or just the event type, if the event has no other payload | ||
*/ | ||
(event: TEvent | ExtractSimple<TEvent>['type']): void; | ||
/** | ||
* Send an event type and its payload | ||
*/ | ||
<K extends TEvent['type']>(eventType: K, payload: NeverIfEmpty<ExtractExtraParameters<TEvent, K>>): void; | ||
} | ||
export interface ActorRef<TEvent extends EventObject, TEmitted = any> extends Subscribable<TEmitted> { | ||
send: Sender<TEvent>; | ||
} | ||
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 declare type NoInfer<T> = [T][T extends any ? 0 : any]; | ||
export declare type Prop<T, K> = K extends keyof T ? T[K] : never; | ||
export interface UseMachineOptions<TContext, TEvent extends EventObject> { | ||
@@ -59,7 +16,2 @@ /** | ||
} | ||
export declare type ActionStateTuple<TContext, TEvent extends EventObject> = [ | ||
ReactActionObject<TContext, TEvent>, | ||
State<TContext, TEvent> | ||
]; | ||
export {}; | ||
//# 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 = {})); |
@@ -1,3 +0,2 @@ | ||
import { Sender } from './types'; | ||
import { ActorRef, EventObject } from 'xstate'; | ||
import { ActorRef, EventObject, Sender } from 'xstate'; | ||
export declare function isActorWithState<T extends ActorRef<any>>(actorRef: T): actorRef is T & { | ||
@@ -4,0 +3,0 @@ state: any; |
"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,7 @@ exports.useActor = exports.isActorWithState = void 0; | ||
var useConstant_1 = require("./useConstant"); | ||
var with_selector_1 = require("use-sync-external-store/shim/with-selector"); | ||
var utils_1 = require("./utils"); | ||
function identity(a) { | ||
return a; | ||
} | ||
function isActorWithState(actorRef) { | ||
@@ -31,8 +20,7 @@ return 'state' in actorRef; | ||
} | ||
var noop = function () { | ||
/* ... */ | ||
}; | ||
function defaultGetSnapshot(actorRef) { | ||
return 'getSnapshot' in actorRef | ||
? actorRef.getSnapshot() | ||
? (0, utils_1.isService)(actorRef) | ||
? (0, utils_1.getServiceSnapshot)(actorRef) | ||
: actorRef.getSnapshot() | ||
: isActorWithState(actorRef) | ||
@@ -46,3 +34,14 @@ ? actorRef.state | ||
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 isEqual = (0, react_1.useCallback)(function (prevState, nextState) { | ||
if ((0, utils_1.isService)(actorRef)) { | ||
return (0, utils_1.isInterpreterStateEqual)(actorRef, prevState, nextState); | ||
} | ||
return prevState === nextState; | ||
}, [actorRef]); | ||
var storeSnapshot = (0, with_selector_1.useSyncExternalStoreWithSelector)(subscribe, boundGetSnapshot, boundGetSnapshot, identity, isEqual); | ||
var send = (0, useConstant_1.default)(function () { return function () { | ||
@@ -70,8 +69,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 +75,5 @@ while (deferredEventsRef.current.length > 0) { | ||
} | ||
return function () { | ||
subscription.unsubscribe(); | ||
}; | ||
}, [actorRef]); | ||
return [current, send]; | ||
return [storeSnapshot, send]; | ||
} | ||
exports.useActor = useActor; |
@@ -1,8 +0,14 @@ | ||
import { EventObject, StateMachine, State, Interpreter, InterpreterOptions, MachineOptions, Typestate, Observer } 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 useInterpret<TContext, TEvent extends EventObject, TTypestate extends Typestate<TContext> = { | ||
value: any; | ||
context: TContext; | ||
}>(getMachine: MaybeLazy<StateMachine<TContext, any, TEvent, TTypestate>>, options?: Partial<InterpreterOptions> & Partial<UseMachineOptions<TContext, TEvent>> & Partial<MachineOptions<TContext, TEvent>>, observerOrListener?: Observer<State<TContext, TEvent, any, TTypestate>> | ((value: State<TContext, TEvent, any, TTypestate>) => void)): Interpreter<TContext, any, TEvent, TTypestate>; | ||
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 ? [ | ||
options: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta'], true>, | ||
observerOrListener?: Observer<StateFrom<TMachine>> | ((value: StateFrom<TMachine>) => void) | ||
] : [ | ||
options?: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta']>, | ||
observerOrListener?: Observer<StateFrom<TMachine>> | ((value: StateFrom<TMachine>) => void) | ||
]; | ||
export declare function useInterpret<TMachine extends AnyStateMachine>(getMachine: MaybeLazy<TMachine>, ...[options, observerOrListener]: RestParams<TMachine>): InterpreterFrom<TMachine>; | ||
export {}; | ||
//# sourceMappingURL=useInterpret.d.ts.map |
@@ -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,18 +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, options, observerOrListener) { | ||
if (options === void 0) { options = {}; } | ||
function useIdleInterpreter(getMachine, options) { | ||
var machine = (0, useConstant_1.default)(function () { | ||
@@ -86,19 +71,4 @@ return typeof getMachine === 'function' ? getMachine() : getMachine; | ||
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. | ||
@@ -114,5 +84,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 { EventObject, StateMachine, State, Interpreter, InterpreterOptions, MachineOptions, StateConfig, Typestate, ActionFunction } from 'xstate'; | ||
import { MaybeLazy, 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> { | ||
@@ -16,10 +14,10 @@ /** | ||
} | ||
export declare function useMachine<TContext, TEvent extends EventObject, TTypestate extends Typestate<TContext> = { | ||
value: any; | ||
context: TContext; | ||
}>(getMachine: MaybeLazy<StateMachine<TContext, any, TEvent, TTypestate>>, options?: Partial<InterpreterOptions> & Partial<UseMachineOptions<TContext, TEvent>> & Partial<MachineOptions<TContext, TEvent>>): [ | ||
State<TContext, TEvent, any, TTypestate>, | ||
Interpreter<TContext, any, TEvent, TTypestate>['send'], | ||
Interpreter<TContext, any, TEvent, TTypestate> | ||
declare type RestParams<TMachine extends AnyStateMachine> = AreAllImplementationsAssumedToBeProvided<TMachine['__TResolvedTypesMeta']> extends false ? [ | ||
options: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta'], true> | ||
] : [ | ||
options?: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta']> | ||
]; | ||
declare type UseMachineReturn<TMachine extends AnyStateMachine, TInterpreter = InterpreterFrom<TMachine>> = [StateFrom<TMachine>, Prop<TInterpreter, 'send'>, TInterpreter]; | ||
export declare function useMachine<TMachine extends AnyStateMachine>(getMachine: MaybeLazy<TMachine>, ...[options]: RestParams<TMachine>): UseMachineReturn<TMachine>; | ||
export {}; | ||
//# sourceMappingURL=useMachine.d.ts.map |
@@ -18,65 +18,47 @@ "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]; | ||
var utils_1 = require("./utils"); | ||
function identity(a) { | ||
return a; | ||
} | ||
function useMachine(getMachine) { | ||
var _a = []; | ||
for (var _i = 1; _i < arguments.length; _i++) { | ||
_a[_i - 1] = arguments[_i]; | ||
} | ||
var _b = __read(_a, 1), _c = _b[0], options = _c === void 0 ? {} : _c; | ||
// 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); | ||
} | ||
// don't execute; just return | ||
return service.getSnapshot(); | ||
}, [service]); | ||
var isEqual = (0, react_1.useCallback)(function (prevState, nextState) { | ||
return (0, utils_1.isInterpreterStateEqual)(service, prevState, nextState); | ||
}, [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 () { | ||
return exec.apply(void 0, __spreadArray([], __read(args), false)); | ||
service.stop(); | ||
service.status = xstate_1.InterpreterStatus.NotStarted; | ||
}; | ||
}; | ||
Object.defineProperties(effectExec, { | ||
name: { value: "effect:".concat(exec.name) }, | ||
__effect: { value: tag } | ||
}); | ||
return effectExec; | ||
} | ||
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, options) { | ||
if (options === void 0) { options = {}; } | ||
var listener = (0, react_1.useCallback)(function (nextState) { | ||
// Only change the current state if: | ||
// - the incoming state is the "live" initial state (since it might have new actors) | ||
// - OR the incoming state actually changed. | ||
// | ||
// 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 service = (0, useInterpret_1.useInterpret)(getMachine, options, listener); | ||
var _a = __read((0, react_1.useState)(function () { | ||
var initialState = service.machine.initialState; | ||
return (options.state | ||
? xstate_1.State.create(options.state) | ||
: initialState); | ||
}), 2), state = _a[0], setState = _a[1]; | ||
return [state, service.send, service]; | ||
return [storeSnapshot, service.send, service]; | ||
} | ||
exports.useMachine = useMachine; |
@@ -5,71 +5,34 @@ "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"); | ||
var useService_1 = require("./useService"); | ||
function isService(actor) { | ||
return 'state' in actor && 'machine' in actor; | ||
} | ||
var utils_1 = require("./utils"); | ||
var defaultCompare = function (a, b) { return a === b; }; | ||
var defaultGetSnapshot = function (a) { | ||
return isService(a) | ||
? (0, useService_1.getServiceSnapshot)(a) | ||
: (0, useActor_1.isActorWithState)(a) | ||
? a.state | ||
: undefined; | ||
var defaultGetSnapshot = function (a, initialStateCacheRef) { | ||
if ((0, utils_1.isService)(a)) { | ||
// A status of 0 = interpreter not started | ||
if (a.status === 0 && initialStateCacheRef.current) { | ||
return initialStateCacheRef.current; | ||
} | ||
var snapshot = (0, utils_1.getServiceSnapshot)(a); | ||
initialStateCacheRef.current = a.status === 0 ? snapshot : null; | ||
return snapshot; | ||
} | ||
return (0, useActor_1.isActorWithState)(a) ? a.state : undefined; | ||
}; | ||
function useSelector(actor, selector, compare, getSnapshot) { | ||
if (compare === void 0) { compare = defaultCompare; } | ||
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 initialStateCacheRef = (0, react_1.useRef)(null); | ||
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; | ||
var boundGetSnapshot = (0, react_1.useCallback)(function () { | ||
if (getSnapshot) { | ||
return getSnapshot(actor); | ||
} | ||
} | ||
(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; | ||
return defaultGetSnapshot(actor, initialStateCacheRef); | ||
}, [actor, getSnapshot]); | ||
var selectedSnapshot = (0, with_selector_1.useSyncExternalStoreWithSelector)(subscribe, boundGetSnapshot, boundGetSnapshot, selector, compare); | ||
return selectedSnapshot; | ||
} | ||
exports.useSelector = useSelector; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.useSpawn = void 0; | ||
var behaviors_1 = require("xstate/lib/behaviors"); | ||
var xstate_1 = require("xstate"); | ||
var useConstant_1 = require("./useConstant"); | ||
@@ -15,3 +15,3 @@ /** | ||
var actorRef = (0, useConstant_1.default)(function () { | ||
return (0, behaviors_1.spawnBehavior)(behavior); | ||
return (0, xstate_1.spawnBehavior)(behavior); | ||
}); | ||
@@ -18,0 +18,0 @@ return actorRef; |
@@ -0,2 +1,7 @@ | ||
import { AnyInterpreter, AnyState, Interpreter } from 'xstate'; | ||
export declare function partition<T, A extends T, B extends T>(items: T[], predicate: (item: T) => item is A): [A[], B[]]; | ||
export declare function getServiceSnapshot<TService extends Interpreter<any, any, any, any>>(service: TService): TService['state']; | ||
export declare function shallowEqual(objA: any, objB: any): boolean; | ||
export declare function isService(actor: any): actor is Interpreter<any, any, any, any>; | ||
export declare function isInterpreterStateEqual(service: AnyInterpreter, prevState: AnyState, nextState: AnyState): boolean; | ||
//# sourceMappingURL=utils.d.ts.map |
@@ -30,3 +30,4 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.partition = void 0; | ||
exports.isInterpreterStateEqual = exports.isService = exports.shallowEqual = exports.getServiceSnapshot = exports.partition = void 0; | ||
var xstate_1 = require("xstate"); | ||
function partition(items, predicate) { | ||
@@ -56,1 +57,57 @@ var e_1, _a; | ||
exports.partition = partition; | ||
function getServiceSnapshot(service) { | ||
return service.status !== 0 | ||
? service.getSnapshot() | ||
: service.machine.initialState; | ||
} | ||
exports.getServiceSnapshot = getServiceSnapshot; | ||
// From https://github.com/reduxjs/react-redux/blob/master/src/utils/shallowEqual.ts | ||
function is(x, y) { | ||
if (x === y) { | ||
return x !== 0 || y !== 0 || 1 / x === 1 / y; | ||
} | ||
else { | ||
return x !== x && y !== y; | ||
} | ||
} | ||
function shallowEqual(objA, objB) { | ||
if (is(objA, objB)) | ||
return true; | ||
if (typeof objA !== 'object' || | ||
objA === null || | ||
typeof objB !== 'object' || | ||
objB === null) { | ||
return false; | ||
} | ||
var keysA = Object.keys(objA); | ||
var keysB = Object.keys(objB); | ||
if (keysA.length !== keysB.length) | ||
return false; | ||
for (var i = 0; i < keysA.length; i++) { | ||
if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || | ||
!is(objA[keysA[i]], objB[keysA[i]])) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
} | ||
exports.shallowEqual = shallowEqual; | ||
function isService(actor) { | ||
return 'state' in actor && 'machine' in actor; | ||
} | ||
exports.isService = isService; | ||
function isInterpreterStateEqual(service, prevState, nextState) { | ||
if (service.status === xstate_1.InterpreterStatus.NotStarted) { | ||
return true; | ||
} | ||
// Only change the current state if: | ||
// - the incoming state is the "live" initial state (since it might have new actors) | ||
// - OR the incoming state actually changed. | ||
// | ||
// The "live" initial state will have .changed === undefined. | ||
var initialStateChanged = nextState.changed === undefined && | ||
(Object.keys(nextState.children).length > 0 || | ||
typeof prevState.changed === 'boolean'); | ||
return !(nextState.changed || initialStateChanged); | ||
} | ||
exports.isInterpreterStateEqual = isInterpreterStateEqual; |
{ | ||
"name": "@xstate/react", | ||
"version": "1.6.3", | ||
"version": "3.2.2", | ||
"description": "XState tools for React", | ||
@@ -16,3 +16,3 @@ "keywords": [ | ||
"author": "David Khourshid <davidkpiano@gmail.com>", | ||
"homepage": "https://github.com/davidkpiano/xstate/tree/main/packages/xstate-react#readme", | ||
"homepage": "https://github.com/statelyai/xstate/tree/main/packages/xstate-react#readme", | ||
"license": "MIT", | ||
@@ -22,2 +22,9 @@ "main": "lib/index.js", | ||
"types": "lib/index.d.ts", | ||
"typesVersions": { | ||
"<4.0": { | ||
"lib/index.d.ts": [ | ||
"index.v3.d.ts" | ||
] | ||
} | ||
}, | ||
"sideEffects": false, | ||
@@ -38,3 +45,3 @@ "directories": { | ||
"type": "git", | ||
"url": "git+ssh://git@github.com/davidkpiano/xstate.git" | ||
"url": "git+ssh://git@github.com/statelyai/xstate.git" | ||
}, | ||
@@ -45,11 +52,11 @@ "scripts": { | ||
"test": "jest", | ||
"prepublish": "npm run build" | ||
"prepare": "npm run build" | ||
}, | ||
"bugs": { | ||
"url": "https://github.com/davidkpiano/xstate/issues" | ||
"url": "https://github.com/statelyai/xstate/issues" | ||
}, | ||
"peerDependencies": { | ||
"@xstate/fsm": "^1.0.0", | ||
"react": "^16.8.0 || ^17.0.0", | ||
"xstate": "^4.11.0" | ||
"@xstate/fsm": "^2.0.0", | ||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0", | ||
"xstate": "^4.37.2" | ||
}, | ||
@@ -65,4 +72,4 @@ "peerDependenciesMeta": { | ||
"dependencies": { | ||
"use-isomorphic-layout-effect": "^1.0.0", | ||
"use-subscription": "^1.3.0" | ||
"use-isomorphic-layout-effect": "^1.1.2", | ||
"use-sync-external-store": "^1.0.0" | ||
}, | ||
@@ -72,6 +79,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": "*", | ||
@@ -82,5 +90,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", | ||
@@ -90,5 +98,5 @@ "rollup-plugin-terser": "^5.1.2", | ||
"ts-jest": "^26.5.6", | ||
"typescript": "^4.5.2", | ||
"typescript": "^4.8.4", | ||
"xstate": "*" | ||
} | ||
} |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
6
80894
21
50
1441
+ Added@xstate/fsm@2.1.0(transitive)
+ Addedreact@18.3.1(transitive)
- Removeduse-subscription@^1.3.0
- Removed@xstate/fsm@1.6.5(transitive)
- Removedobject-assign@4.1.1(transitive)
- Removedreact@17.0.2(transitive)
- Removeduse-subscription@1.8.2(transitive)