Skip to content

Commit

Permalink
XState Store (#4752)
Browse files Browse the repository at this point in the history
* Initial commit

* Try EventPayloadMap

* Cleanup + add select()

* Fix types

* React, immer, custom API

* Simplify API

* Remove select, add createStoreWithProducer

* Fix types, sorta

* Add assigners

* Add property assigner tests

* Add JSDoc & test for subscription

* Reorganize types, start withTransitions

* Use common snapshot interface

* Use context, continued

* Add snapshot.status

* Cleanup

* Changeset

* Add preconstruct

* Add SymbolConstructor

* Sort packages

* hide some functionality in a private fn

* Fix deps?

* Ungenericize producer

* Remove TODO

* Address nit

* Remove custom API

* Remove XState dependency

* move `use-sync-external-store` back to dependencies

* remove last dep on XState

* preconstruct fix

* Fix React export

* Refactor: createStoreTransition(...)

* fromStore

* Reduce EventfromLogic scope, InputFrom scope

* Tighten types

* JSDoc

* Revert "Reduce EventfromLogic scope, InputFrom scope"

This reverts commit b6e3fc2.

* fixed types

* fixed types again

* Delete packages/xstate-store/pnpm-lock.yaml

* limit public API

* revert accidental change

---------

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
  • Loading branch information
davidkpiano and Andarist committed Apr 7, 2024
1 parent a16d96e commit 8a32374
Show file tree
Hide file tree
Showing 15 changed files with 1,260 additions and 13 deletions.
38 changes: 38 additions & 0 deletions .changeset/mighty-walls-know.md
@@ -0,0 +1,38 @@
---
'@xstate/store': patch
---

Initial release of `@xstate/store`

```ts
import { createStore } from '@xstate/store';

const store = createStore(
// initial context
{ count: 0, greeting: 'hello' },
// transitions
{
inc: {
count: (context) => context.count + 1
},
updateBoth: {
count: () => 42,
greeting: 'hi'
}
}
);

store.send({
type: 'inc'
});

console.log(store.getSnapshot());
// Logs:
// {
// status: 'active',
// context: {
// count: 1,
// greeting: 'hello'
// }
// }
```
4 changes: 2 additions & 2 deletions packages/xstate-react/package.json
Expand Up @@ -64,10 +64,10 @@
},
"dependencies": {
"use-isomorphic-layout-effect": "^1.1.2",
"use-sync-external-store": "^1.0.0"
"use-sync-external-store": "^1.2.0"
},
"devDependencies": {
"@testing-library/react": "^13.4.0",
"@testing-library/react": "^14.2.1",
"@types/jsdom": "^12.2.3",
"@types/react": "^17.0.43",
"@types/react-dom": "^17.0.14",
Expand Down
22 changes: 22 additions & 0 deletions packages/xstate-store/LICENSE
@@ -0,0 +1,22 @@
The MIT License (MIT)

Copyright (c) 2015 David Khourshid

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

1 change: 1 addition & 0 deletions packages/xstate-store/README.md
@@ -0,0 +1 @@
# `@xstate/store`
72 changes: 72 additions & 0 deletions packages/xstate-store/package.json
@@ -0,0 +1,72 @@
{
"name": "@xstate/store",
"version": "0.0.1",
"description": "Simple stores",
"keywords": [
"store",
"state"
],
"author": "David Khourshid <davidkpiano@gmail.com>",
"homepage": "https://github.com/statelyai/xstate/tree/main/packages/xstate-store#readme",
"license": "MIT",
"main": "dist/xstate-store.cjs.js",
"module": "dist/xstate-store.esm.js",
"exports": {
".": {
"types": {
"import": "./dist/xstate-store.cjs.mjs",
"default": "./dist/xstate-store.cjs.js"
},
"module": "./dist/xstate-store.esm.js",
"import": "./dist/xstate-store.cjs.mjs",
"default": "./dist/xstate-store.cjs.js"
},
"./react": {
"types": {
"import": "./react/dist/xstate-store-react.cjs.mjs",
"default": "./react/dist/xstate-store-react.cjs.js"
},
"module": "./react/dist/xstate-store-react.esm.js",
"import": "./react/dist/xstate-store-react.cjs.mjs",
"default": "./react/dist/xstate-store-react.cjs.js"
},
"./package.json": "./package.json"
},
"sideEffects": false,
"files": [
"dist",
"react"
],
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/statelyai/xstate.git"
},
"scripts": {},
"bugs": {
"url": "https://github.com/statelyai/xstate/issues"
},
"dependencies": {
"use-sync-external-store": "^1.2.0"
},
"devDependencies": {
"@testing-library/react": "^14.2.1",
"immer": "^10.0.2",
"react": "^18.0.0",
"xstate": "^5.9.1"
},
"peerDependencies": {
"react": "^18.2.0"
},
"peerDependenciesMeta": {
"react": {
"optional": true
}
},
"preconstruct": {
"umdName": "XStateStore",
"entrypoints": [
"./index.ts",
"./react.ts"
]
}
}
4 changes: 4 additions & 0 deletions packages/xstate-store/react/package.json
@@ -0,0 +1,4 @@
{
"main": "dist/xstate-store-react.cjs.js",
"module": "dist/xstate-store-react.esm.js"
}
44 changes: 44 additions & 0 deletions packages/xstate-store/src/fromStore.ts
@@ -0,0 +1,44 @@
import { createStore, createStoreTransition } from './store';
import {
EventPayloadMap,
StoreContext,
StoreSnapshot,
Snapshot
} from './types';

/**
* An actor logic creator which creates store actor logic.
*
* @param initialContext The initial context for the store, either a function that returns context based on input, or the context itself
* @param transitions The transitions object defining how the context updates due to events
* @returns An actor logic creator function that creates store actor logic
*/
export function fromStore<
TContext extends StoreContext,
TEventPayloadMap extends EventPayloadMap,
TInput
>(
initialContext: ((input: TInput) => TContext) | TContext,
transitions: Parameters<typeof createStore<TContext, TEventPayloadMap>>[1]
) {
const transition = createStoreTransition<TContext, TEventPayloadMap>(
transitions
);
return {
transition,
start: () => {},
getInitialSnapshot: (_: any, input: TInput) => {
return {
status: 'active',
context:
typeof initialContext === 'function'
? initialContext(input)
: initialContext,
output: undefined,
error: undefined
} satisfies StoreSnapshot<TContext>;
},
getPersistedSnapshot: (s: StoreSnapshot<TContext>) => s,
restoreSnapshot: (s: Snapshot<unknown>) => s as StoreSnapshot<TContext>
};
}
2 changes: 2 additions & 0 deletions packages/xstate-store/src/index.ts
@@ -0,0 +1,2 @@
export { fromStore } from './fromStore';
export { createStore, createStoreWithProducer } from './store';
45 changes: 45 additions & 0 deletions packages/xstate-store/src/react.ts
@@ -0,0 +1,45 @@
import { useCallback } from 'react';
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';
import { Store, SnapshotFromStore } from './types';

type SyncExternalStoreSubscribe = Parameters<
typeof useSyncExternalStoreWithSelector
>[0];

function defaultCompare<T>(a: T, b: T) {
return a === b;
}

export function useSelector<TStore extends Store<any, any> | undefined, T>(
actor: TStore,
selector: (
emitted: TStore extends Store<any, any>
? SnapshotFromStore<TStore>
: undefined
) => T,
compare: (a: T, b: T) => boolean = defaultCompare
): T {
const subscribe: SyncExternalStoreSubscribe = useCallback(
(handleStoreChange) => {
if (!actor) {
return () => {};
}
const { unsubscribe } = actor.subscribe(handleStoreChange);
return unsubscribe;
},
[actor]
);

const boundGetSnapshot = useCallback(() => actor?.getSnapshot(), [actor]);

const selectedSnapshot = useSyncExternalStoreWithSelector(
subscribe,
// @ts-ignore
boundGetSnapshot,
boundGetSnapshot,
selector,
compare
);

return selectedSnapshot;
}

0 comments on commit 8a32374

Please sign in to comment.