@xstate/react 1.0.3 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,65 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.2.2
4
+
5
+ ### Patch Changes
6
+
7
+ - [`4b31cefb`](https://github.com/davidkpiano/xstate/commit/4b31cefb3d3497e5515314046639df7e27dbe9e8) [#1780](https://github.com/davidkpiano/xstate/pull/1780) Thanks [@Andarist](https://github.com/Andarist)! - Fixed an issue with some external packages not being bundled correctly into the UMD bundles.
8
+
9
+ ## 1.2.1
10
+
11
+ ### Patch Changes
12
+
13
+ - [`a16a5f2f`](https://github.com/davidkpiano/xstate/commit/a16a5f2ff5ba9d4d7834ec3ca2d0adecf5d6a870) [#1756](https://github.com/davidkpiano/xstate/pull/1756) Thanks [@dimitardanailov](https://github.com/dimitardanailov)! - Fixed an issue with `process` references not being removed correctly from the UMD bundles.
14
+
15
+ ## 1.2.0
16
+
17
+ ### Minor Changes
18
+
19
+ - [`dd98296e`](https://github.com/davidkpiano/xstate/commit/dd98296e9fcbae905da2395e67e876e28be7c774) [#1738](https://github.com/davidkpiano/xstate/pull/1738) Thanks [@dimitardanailov](https://github.com/dimitardanailov)! - Added UMD bundle.
20
+
21
+ ## 1.1.0
22
+
23
+ ### Minor Changes
24
+
25
+ - [`89f9c27c`](https://github.com/davidkpiano/xstate/commit/89f9c27c453dc56bdfdf49c8ea1f0f87ff1f9b67) [#1622](https://github.com/davidkpiano/xstate/pull/1622) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Spawned/invoked actors and interpreters are now typed as extending `ActorRef` rather than `Actor` or `Interpreter`. This unification of types should make it more straightforward to provide actor types in React:
26
+
27
+ ```ts
28
+ import { ActorRef } from 'xstate';
29
+ import { useActor } from '@xstate/react';
30
+
31
+ const Child: React.FC<{ actorRef: ActorRef<SomeEvent, SomeEmitted> }> = ({
32
+ actorRef
33
+ }) => {
34
+ // `state` is typed as `SomeEmitted`
35
+ // `send` can be called with `SomeEvent` values
36
+ const [state, send] = useActor(actorRef);
37
+
38
+ // . ..
39
+ };
40
+ ```
41
+
42
+ It's also easier to specify the type of a spawned/invoked machine with `ActorRefFrom`:
43
+
44
+ ```ts
45
+ import { createMachine, ActorRefFrom } from 'xstate';
46
+ import { useActor } from '@xstate/react';
47
+
48
+ const someMachine = createMachine<SomeContext, SomeEvent>({
49
+ // ...
50
+ });
51
+
52
+ const Child: React.FC<{ someRef: ActorRefFrom<typeof someMachine> }> = ({
53
+ someRef
54
+ }) => {
55
+ // `state` is typed as `State<SomeContext, SomeEvent>`
56
+ // `send` can be called with `SomeEvent` values
57
+ const [state, send] = useActor(someRef);
58
+
59
+ // . ..
60
+ };
61
+ ```
62
+
3
63
  ## 1.0.3
4
64
 
5
65
  ### Patch Changes
package/README.md CHANGED
@@ -29,6 +29,22 @@
29
29
  npm i xstate @xstate/react
30
30
  ```
31
31
 
32
+ **Via CDN**
33
+
34
+ ```html
35
+ <script src="https://unpkg.com/@xstate/react/dist/xstate-react.umd.min.js"></script>
36
+ ```
37
+
38
+ By using the global variable `XStateReact`
39
+
40
+ or
41
+
42
+ ```html
43
+ <script src="https://unpkg.com/@xstate/react/dist/xstate-react-fsm.umd.min.js"></script>
44
+ ```
45
+
46
+ By using the global variable `XStateReactFSM`
47
+
32
48
  2. Import the `useMachine` hook:
33
49
 
34
50
  ```js
@@ -0,0 +1,28 @@
1
+ !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);
2
+ /*! *****************************************************************************
3
+ Copyright (c) Microsoft Corporation. All rights reserved.
4
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
5
+ this file except in compliance with the License. You may obtain a copy of the
6
+ License at http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
9
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
10
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
11
+ MERCHANTABLITY OR NON-INFRINGEMENT.
12
+
13
+ See the Apache Version 2.0 License for specific language governing permissions
14
+ and limitations under the License.
15
+ ***************************************************************************** */function o(e){var t={exports:{}};return e(t,t.exports),t.exports
16
+ /*
17
+ object-assign
18
+ (c) Sindre Sorhus
19
+ @license MIT
20
+ */}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})));
21
+ /** @license React v1.4.1
22
+ * use-subscription.production.min.js
23
+ *
24
+ * Copyright (c) Facebook, Inc. and its affiliates.
25
+ *
26
+ * This source code is licensed under the MIT license found in the
27
+ * LICENSE file in the root directory of this source tree.
28
+ */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})}));
@@ -0,0 +1,15 @@
1
+ !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";
2
+ /*! *****************************************************************************
3
+ Copyright (c) Microsoft Corporation. All rights reserved.
4
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
5
+ this file except in compliance with the License. You may obtain a copy of the
6
+ License at http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
9
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
10
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
11
+ MERCHANTABLITY OR NON-INFRINGEMENT.
12
+
13
+ See the Apache Version 2.0 License for specific language governing permissions
14
+ and limitations under the License.
15
+ ***************************************************************************** */var r=function(){return(r=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t}).apply(this,arguments)};function o(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,u=n.call(t),c=[];try{for(;(void 0===e||e-- >0)&&!(r=u.next()).done;)c.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=u.return)&&n.call(u)}finally{if(o)throw o.error}}return c}function u(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(o(arguments[e]));return t}var c,i=e.useLayoutEffect;function f(t){var n=e.useRef();return n.current||(n.current={v:t()}),n.current.v}function a(t,e){var n,r,u=o([[],[]],2),c=u[0],i=u[1];try{for(var f=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),a=f.next();!a.done;a=f.next()){var s=a.value;e(s)?c.push(s):i.push(s)}}catch(t){n={error:t}}finally{try{a&&!a.done&&(r=f.return)&&r.call(f)}finally{if(n)throw n.error}}return[c,i]}function s(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,u(e))}};return Object.defineProperties(n,{name:{value:"effect:"+t.name},__effect:{value:e}}),n}function l(t,e){(0,t.exec)(e.context,e._event.data,{action:t,state:e,_event:e._event})()}!function(t){t[t.Effect=1]="Effect",t[t.LayoutEffect=2]="LayoutEffect"}(c||(c={}));var v=function(){};function p(t,n){void 0===n&&(n=function(t){return function(t){return"state"in t}(t)?t.state:void 0});var r=e.useRef(t),u=e.useRef([]),c=o(e.useState((function(){return n(t)})),2),a=c[0],s=c[1],l=f((function(){return function(t){var e=r.current;(function(t){return"deferred"in t})(e)&&e.deferred?u.current.push(t):e.send(t)}}));return i((function(){r.current=t,s(n(t));for(var e=t.subscribe({next:function(t){return s(t)},error:v,complete:v});u.current.length>0;){var o=u.current.shift();t.send(o)}return function(){e.unsubscribe()}}),[t]),[a,l]}t.asEffect=function(t){return s(t,c.Effect)},t.asLayoutEffect=function(t){return s(t,c.LayoutEffect)},t.useActor=p,t.useMachine=function(t,s){void 0===s&&(s={});var v=f((function(){return"function"==typeof t?t():t})),p=s.context,d=s.guards,y=s.actions,h=s.activities,b=s.services,g=s.delays,x=s.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 o=0;for(r=Object.getOwnPropertySymbols(t);o<r.length;o++)e.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(t,r[o])&&(n[r[o]]=t[r[o]])}return n}(s,["context","guards","actions","activities","services","delays","state"]),O=o(f((function(){var t={context:p,guards:d,actions:y,activities:h,services:b,delays:g},e=v.withConfig(t,r(r({},v.context),p));return[e,n.interpret(e,r({deferEvents:!0},m))]})),2),E=O[0],S=O[1],j=o(e.useState((function(){var t=E.initialState;return x?n.State.create(x):t})),2),_=j[0],w=j[1],R=e.useRef([]),P=e.useRef([]);return i((function(){return S.onTransition((function(t){var e,n,r=void 0===t.changed&&Object.keys(t.children).length;if((t.changed||r)&&w(t),t.actions.length){var i=o(a(t.actions.filter((function(t){return"function"==typeof t.exec&&"__effect"in t.exec})),(function(t){return t.exec.__effect===c.Effect})),2),f=i[0],s=i[1];(e=R.current).push.apply(e,u(f.map((function(e){return[e,t]})))),(n=P.current).push.apply(n,u(s.map((function(e){return[e,t]}))))}})).start(x?n.State.create(x):void 0),function(){S.stop()}}),[]),e.useEffect((function(){Object.assign(S.machine.options.actions,y)}),[y]),e.useEffect((function(){Object.assign(S.machine.options.services,b)}),[b]),i((function(){for(;P.current.length;){var t=o(P.current.shift(),2);l(t[0],t[1])}}),[_]),e.useEffect((function(){for(;R.current.length;){var t=o(R.current.shift(),2);l(t[0],t[1])}}),[_]),[_,S.send,S]},t.useService=function(t){return[o(p(t,(function(){return 0!==("status"in t?t.status:t._status)?t.state:t.machine.initialState})),1)[0],t.send]},Object.defineProperty(t,"__esModule",{value:!0})}));
package/es/types.d.ts CHANGED
@@ -12,20 +12,6 @@ export interface Subscribable<T> {
12
12
  subscribe(observer: Observer<T>): Subscription;
13
13
  subscribe(next: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;
14
14
  }
15
- export interface ActorRef<TEvent extends EventObject, TEmitted = any> extends Subscribable<TEmitted> {
16
- send: Sender<TEvent>;
17
- stop: () => void;
18
- /**
19
- * The most recently emitted value.
20
- */
21
- current: TEmitted;
22
- name: string;
23
- }
24
- export interface ActorRefLike<TEvent extends EventObject, TEmitted = any> extends Subscribable<TEmitted> {
25
- send: Sender<TEvent>;
26
- stop?: () => void;
27
- [key: string]: any;
28
- }
29
15
  export declare type MaybeLazy<T> = T | (() => T);
30
16
  declare type ExcludeType<A> = {
31
17
  [K in Exclude<keyof A, 'type'>]: A[K];
@@ -45,5 +31,8 @@ export interface PayloadSender<TEvent extends EventObject> {
45
31
  */
46
32
  <K extends TEvent['type']>(eventType: K, payload: NeverIfEmpty<ExtractExtraParameters<TEvent, K>>): void;
47
33
  }
34
+ export interface ActorRef<TEvent extends EventObject, TEmitted = any> extends Subscribable<TEmitted> {
35
+ send: Sender<TEvent>;
36
+ }
48
37
  export {};
49
38
  //# sourceMappingURL=types.d.ts.map
package/es/useActor.d.ts CHANGED
@@ -1,4 +1,8 @@
1
- import { Sender, ActorRefLike } from './types';
2
- import { EventObject, Actor } from 'xstate';
3
- export declare function useActor<TEvent extends EventObject, TEmitted = any>(actorRef: ActorRefLike<TEvent, TEmitted> | Actor, getSnapshot?: (actor: typeof actorRef) => TEmitted): [TEmitted, Sender<TEvent>];
1
+ import { Sender } from './types';
2
+ import { ActorRef, EventObject } from 'xstate';
3
+ declare type EventOfActorRef<TActor extends ActorRef<any, any>> = TActor extends ActorRef<infer TEvent, any> ? TEvent : never;
4
+ declare type EmittedOfActorRef<TActor extends ActorRef<any, any>> = TActor extends ActorRef<any, infer TEmitted> ? TEmitted : never;
5
+ export declare function useActor<TActor extends ActorRef<any, any>>(actorRef: TActor, getSnapshot?: (actor: TActor) => EmittedOfActorRef<TActor>): [EmittedOfActorRef<TActor>, Sender<EventOfActorRef<TActor>>];
6
+ export declare function useActor<TEvent extends EventObject, TEmitted>(actorRef: ActorRef<TEvent, TEmitted>, getSnapshot?: (actor: ActorRef<TEvent, TEmitted>) => TEmitted): [TEmitted, Sender<TEvent>];
7
+ export {};
4
8
  //# sourceMappingURL=useActor.d.ts.map
package/es/useActor.js CHANGED
@@ -17,9 +17,18 @@ var __read = (this && this.__read) || function (o, n) {
17
17
  import { useState, useRef } from 'react';
18
18
  import useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';
19
19
  import useConstant from './useConstant';
20
+ function isActorWithState(actorRef) {
21
+ return 'state' in actorRef;
22
+ }
23
+ function isDeferredActor(actorRef) {
24
+ return 'deferred' in actorRef;
25
+ }
26
+ var noop = function () {
27
+ /* ... */
28
+ };
20
29
  export function useActor(actorRef, getSnapshot) {
21
30
  if (getSnapshot === void 0) { getSnapshot = function (a) {
22
- return 'state' in a ? a.state : undefined;
31
+ return isActorWithState(a) ? a.state : undefined;
23
32
  }; }
24
33
  var actorRefRef = useRef(actorRef);
25
34
  var deferredEventsRef = useRef([]);
@@ -29,7 +38,7 @@ export function useActor(actorRef, getSnapshot) {
29
38
  // If the previous actor is a deferred actor,
30
39
  // queue the events so that they can be replayed
31
40
  // on the non-deferred actor.
32
- if ('deferred' in currentActorRef && currentActorRef.deferred) {
41
+ if (isDeferredActor(currentActorRef) && currentActorRef.deferred) {
33
42
  deferredEventsRef.current.push(event);
34
43
  }
35
44
  else {
@@ -39,7 +48,11 @@ export function useActor(actorRef, getSnapshot) {
39
48
  useIsomorphicLayoutEffect(function () {
40
49
  actorRefRef.current = actorRef;
41
50
  setCurrent(getSnapshot(actorRef));
42
- var subscription = actorRef.subscribe(setCurrent);
51
+ var subscription = actorRef.subscribe({
52
+ next: function (emitted) { return setCurrent(emitted); },
53
+ error: noop,
54
+ complete: noop
55
+ });
43
56
  // Dequeue deferred events from the previous deferred actorRef
44
57
  while (deferredEventsRef.current.length > 0) {
45
58
  var deferredEvent = deferredEventsRef.current.shift();
@@ -1,6 +1,5 @@
1
1
  import { EventObject, State, Interpreter, Typestate } from 'xstate';
2
- import { ActorRef, PayloadSender } from './types';
3
- export declare function fromService<TContext, TEvent extends EventObject>(service: Interpreter<TContext, any, TEvent>): ActorRef<TEvent, State<TContext, TEvent>>;
2
+ import { PayloadSender } from './types';
4
3
  export declare function useService<TContext, TEvent extends EventObject, TTypestate extends Typestate<TContext> = {
5
4
  value: any;
6
5
  context: TContext;
package/es/useService.js CHANGED
@@ -14,26 +14,16 @@ var __read = (this && this.__read) || function (o, n) {
14
14
  }
15
15
  return ar;
16
16
  };
17
- import { useMemo } from 'react';
18
17
  import { useActor } from './useActor';
19
- export function fromService(service) {
18
+ export function useService(service) {
20
19
  if (process.env.NODE_ENV !== 'production' && !('machine' in service)) {
21
20
  throw new Error("Attempted to use an actor-like object instead of a service in the useService() hook. Please use the useActor() hook instead.");
22
21
  }
23
- var machine = service.machine;
24
- return {
25
- send: service.send.bind(service),
26
- subscribe: function (cb) { return service.subscribe(function (state) { return cb(state); }); },
27
- stop: service.stop,
22
+ var _a = __read(useActor(service, function () {
28
23
  // TODO: remove compat lines in a new major, replace literal number with InterpreterStatus then as well
29
- current: ('status' in service ? service.status : service._status) !== 0
24
+ return ('status' in service ? service.status : service._status) !== 0
30
25
  ? service.state
31
- : machine.initialState,
32
- name: service.sessionId
33
- };
34
- }
35
- export function useService(service) {
36
- var serviceActor = useMemo(function () { return fromService(service); }, [service]);
37
- var _a = __read(useActor(serviceActor, function (actor) { return actor.current; }), 1), state = _a[0];
26
+ : service.machine.initialState;
27
+ }), 1), state = _a[0];
38
28
  return [state, service.send];
39
29
  }
package/lib/types.d.ts CHANGED
@@ -12,20 +12,6 @@ export interface Subscribable<T> {
12
12
  subscribe(observer: Observer<T>): Subscription;
13
13
  subscribe(next: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;
14
14
  }
15
- export interface ActorRef<TEvent extends EventObject, TEmitted = any> extends Subscribable<TEmitted> {
16
- send: Sender<TEvent>;
17
- stop: () => void;
18
- /**
19
- * The most recently emitted value.
20
- */
21
- current: TEmitted;
22
- name: string;
23
- }
24
- export interface ActorRefLike<TEvent extends EventObject, TEmitted = any> extends Subscribable<TEmitted> {
25
- send: Sender<TEvent>;
26
- stop?: () => void;
27
- [key: string]: any;
28
- }
29
15
  export declare type MaybeLazy<T> = T | (() => T);
30
16
  declare type ExcludeType<A> = {
31
17
  [K in Exclude<keyof A, 'type'>]: A[K];
@@ -45,5 +31,8 @@ export interface PayloadSender<TEvent extends EventObject> {
45
31
  */
46
32
  <K extends TEvent['type']>(eventType: K, payload: NeverIfEmpty<ExtractExtraParameters<TEvent, K>>): void;
47
33
  }
34
+ export interface ActorRef<TEvent extends EventObject, TEmitted = any> extends Subscribable<TEmitted> {
35
+ send: Sender<TEvent>;
36
+ }
48
37
  export {};
49
38
  //# sourceMappingURL=types.d.ts.map
package/lib/useActor.d.ts CHANGED
@@ -1,4 +1,8 @@
1
- import { Sender, ActorRefLike } from './types';
2
- import { EventObject, Actor } from 'xstate';
3
- export declare function useActor<TEvent extends EventObject, TEmitted = any>(actorRef: ActorRefLike<TEvent, TEmitted> | Actor, getSnapshot?: (actor: typeof actorRef) => TEmitted): [TEmitted, Sender<TEvent>];
1
+ import { Sender } from './types';
2
+ import { ActorRef, EventObject } from 'xstate';
3
+ declare type EventOfActorRef<TActor extends ActorRef<any, any>> = TActor extends ActorRef<infer TEvent, any> ? TEvent : never;
4
+ declare type EmittedOfActorRef<TActor extends ActorRef<any, any>> = TActor extends ActorRef<any, infer TEmitted> ? TEmitted : never;
5
+ export declare function useActor<TActor extends ActorRef<any, any>>(actorRef: TActor, getSnapshot?: (actor: TActor) => EmittedOfActorRef<TActor>): [EmittedOfActorRef<TActor>, Sender<EventOfActorRef<TActor>>];
6
+ export declare function useActor<TEvent extends EventObject, TEmitted>(actorRef: ActorRef<TEvent, TEmitted>, getSnapshot?: (actor: ActorRef<TEvent, TEmitted>) => TEmitted): [TEmitted, Sender<TEvent>];
7
+ export {};
4
8
  //# sourceMappingURL=useActor.d.ts.map
package/lib/useActor.js CHANGED
@@ -20,9 +20,18 @@ exports.useActor = void 0;
20
20
  var react_1 = require("react");
21
21
  var use_isomorphic_layout_effect_1 = require("use-isomorphic-layout-effect");
22
22
  var useConstant_1 = require("./useConstant");
23
+ function isActorWithState(actorRef) {
24
+ return 'state' in actorRef;
25
+ }
26
+ function isDeferredActor(actorRef) {
27
+ return 'deferred' in actorRef;
28
+ }
29
+ var noop = function () {
30
+ /* ... */
31
+ };
23
32
  function useActor(actorRef, getSnapshot) {
24
33
  if (getSnapshot === void 0) { getSnapshot = function (a) {
25
- return 'state' in a ? a.state : undefined;
34
+ return isActorWithState(a) ? a.state : undefined;
26
35
  }; }
27
36
  var actorRefRef = react_1.useRef(actorRef);
28
37
  var deferredEventsRef = react_1.useRef([]);
@@ -32,7 +41,7 @@ function useActor(actorRef, getSnapshot) {
32
41
  // If the previous actor is a deferred actor,
33
42
  // queue the events so that they can be replayed
34
43
  // on the non-deferred actor.
35
- if ('deferred' in currentActorRef && currentActorRef.deferred) {
44
+ if (isDeferredActor(currentActorRef) && currentActorRef.deferred) {
36
45
  deferredEventsRef.current.push(event);
37
46
  }
38
47
  else {
@@ -42,7 +51,11 @@ function useActor(actorRef, getSnapshot) {
42
51
  use_isomorphic_layout_effect_1.default(function () {
43
52
  actorRefRef.current = actorRef;
44
53
  setCurrent(getSnapshot(actorRef));
45
- var subscription = actorRef.subscribe(setCurrent);
54
+ var subscription = actorRef.subscribe({
55
+ next: function (emitted) { return setCurrent(emitted); },
56
+ error: noop,
57
+ complete: noop
58
+ });
46
59
  // Dequeue deferred events from the previous deferred actorRef
47
60
  while (deferredEventsRef.current.length > 0) {
48
61
  var deferredEvent = deferredEventsRef.current.shift();
@@ -1,6 +1,5 @@
1
1
  import { EventObject, State, Interpreter, Typestate } from 'xstate';
2
- import { ActorRef, PayloadSender } from './types';
3
- export declare function fromService<TContext, TEvent extends EventObject>(service: Interpreter<TContext, any, TEvent>): ActorRef<TEvent, State<TContext, TEvent>>;
2
+ import { PayloadSender } from './types';
4
3
  export declare function useService<TContext, TEvent extends EventObject, TTypestate extends Typestate<TContext> = {
5
4
  value: any;
6
5
  context: TContext;
package/lib/useService.js CHANGED
@@ -16,29 +16,18 @@ var __read = (this && this.__read) || function (o, n) {
16
16
  return ar;
17
17
  };
18
18
  Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.useService = exports.fromService = void 0;
20
- var react_1 = require("react");
19
+ exports.useService = void 0;
21
20
  var useActor_1 = require("./useActor");
22
- function fromService(service) {
21
+ function useService(service) {
23
22
  if (process.env.NODE_ENV !== 'production' && !('machine' in service)) {
24
23
  throw new Error("Attempted to use an actor-like object instead of a service in the useService() hook. Please use the useActor() hook instead.");
25
24
  }
26
- var machine = service.machine;
27
- return {
28
- send: service.send.bind(service),
29
- subscribe: function (cb) { return service.subscribe(function (state) { return cb(state); }); },
30
- stop: service.stop,
25
+ var _a = __read(useActor_1.useActor(service, function () {
31
26
  // TODO: remove compat lines in a new major, replace literal number with InterpreterStatus then as well
32
- current: ('status' in service ? service.status : service._status) !== 0
27
+ return ('status' in service ? service.status : service._status) !== 0
33
28
  ? service.state
34
- : machine.initialState,
35
- name: service.sessionId
36
- };
37
- }
38
- exports.fromService = fromService;
39
- function useService(service) {
40
- var serviceActor = react_1.useMemo(function () { return fromService(service); }, [service]);
41
- var _a = __read(useActor_1.useActor(serviceActor, function (actor) { return actor.current; }), 1), state = _a[0];
29
+ : service.machine.initialState;
30
+ }), 1), state = _a[0];
42
31
  return [state, service.send];
43
32
  }
44
33
  exports.useService = useService;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xstate/react",
3
- "version": "1.0.3",
3
+ "version": "1.2.2",
4
4
  "description": "XState tools for React",
5
5
  "keywords": [
6
6
  "state",
@@ -26,6 +26,7 @@
26
26
  "files": [
27
27
  "lib/**/*.js",
28
28
  "lib/**/*.d.ts",
29
+ "dist/**/*.js",
29
30
  "es/**/*.js",
30
31
  "es/**/*.d.ts"
31
32
  ],
@@ -35,7 +36,7 @@
35
36
  },
36
37
  "scripts": {
37
38
  "clean": "rm -rf dist lib tsconfig.tsbuildinfo",
38
- "build": "tsc && tsc --outDir es --module es2015",
39
+ "build": "tsc && tsc --outDir es --module es2015 && rollup -c",
39
40
  "test": "jest",
40
41
  "prepublish": "npm run build && npm run test"
41
42
  },
@@ -60,6 +61,8 @@
60
61
  "use-subscription": "^1.3.0"
61
62
  },
62
63
  "devDependencies": {
64
+ "@rollup/plugin-commonjs": "^17.0.0",
65
+ "@rollup/plugin-node-resolve": "^11.0.1",
63
66
  "@testing-library/react": "^8.0.9",
64
67
  "@types/jsdom": "^12.2.3",
65
68
  "@types/react": "^16.9.11",
@@ -71,8 +74,12 @@
71
74
  "lerna-alias": "3.0.3-0",
72
75
  "react": "^16.12.0",
73
76
  "react-dom": "^16.12.0",
77
+ "rollup": "^2.35.1",
78
+ "rollup-plugin-replace": "^2.2.0",
79
+ "rollup-plugin-terser": "^5.1.2",
80
+ "rollup-plugin-typescript2": "^0.29.0",
74
81
  "ts-jest": "^26.4.0",
75
- "typescript": "^4.0.3",
82
+ "typescript": "^4.1.2",
76
83
  "xstate": "*"
77
84
  }
78
85
  }