Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First Draft for @xstate/angular #4816

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ module.exports = {
setPublicClassFields: true,
setSpreadProperties: true
},
ignore: [/\/xstate-angular\//],
presets: [
[
'@babel/preset-env',
Expand Down
15 changes: 14 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
const { constants } = require('jest-config');
const { defaultTransformerOptions } = require('jest-preset-angular/presets');

/**
* @type {import('@jest/types').Config.InitialOptions}
*/
module.exports = {
setupFilesAfterEnv: ['@xstate-repo/jest-utils/setup'],
setupFilesAfterEnv: [
'@xstate-repo/jest-utils/setup',
'jest-preset-angular/setup-jest'
],
moduleFileExtensions: ['ts', 'html', 'js', 'json', 'mjs'],
transform: {
'^.+\\.(mjs)$|^.+xstate-angular/.+\\.(ts|js)$': [
'jest-preset-angular',
{
...defaultTransformerOptions,
useESM: true
}
],
[constants.DEFAULT_JS_PATTERN]: 'babel-jest',
'^.+\\.vue$': '@vue/vue3-jest',
'^.+\\.svelte$': [
Expand All @@ -16,6 +28,7 @@ module.exports = {
}
]
},
transformIgnorePatterns: [`/node_modules/(?!(@angular|.*.mjs$))`],
resolver: '<rootDir>/scripts/jest-resolver.js',
globals: {
'vue-jest': {
Expand Down
8 changes: 3 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
},
"preconstruct": {
"packages": [
"packages/!(xstate-dev)"
"packages/!(xstate-dev|xstate-angular)"
],
"globals": {
"react": "React"
Expand Down Expand Up @@ -70,6 +70,7 @@
"jest": "^29.7.0",
"jest-config": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"jest-preset-angular": "14.0.3",
"jest-regex-util": "^29.6.3",
"jest-watch-typeahead": "^2.2.2",
"lint-staged": "^8.2.1",
Expand All @@ -78,15 +79,12 @@
"prettier": "^3.1.0",
"spawn-command": "0.0.2-1",
"synckit": "^0.8.5",
"tslib": "^2.3.1",
"tslib": "2.6.2",
"tslint": "^5.11.0",
"typescript": "^5.4.2",
"vue": "^3.0.11",
"webpack-dev-middleware": "^3.6.0"
},
"resolutions": {
"**/tslib": "^2.3.1"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
Expand Down
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@
"jsdom": "^14.0.0",
"jsdom-global": "^3.0.2",
"pkg-up": "^3.1.0",
"rxjs": "^7.8.0",
"rxjs": "^7.8.1",
"xml-js": "^1.6.11"
},
"preconstruct": {
Expand Down
Empty file.
22 changes: 22 additions & 0 deletions packages/xstate-angular/LICENSE
Original file line number Diff line number Diff line change
@@ -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.

55 changes: 55 additions & 0 deletions packages/xstate-angular/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# @xstate/angular

This package contains utilities for using [XState](https://github.com/statelyai/xstate) with [Angular](https://github.com/angular/angular).

- [Read the full documentation in the XState docs](https://stately.ai/docs/xstate-angular).
- [Read our contribution guidelines](https://github.com/statelyai/xstate/blob/main/CONTRIBUTING.md).

## Quick start

1. Install `xstate` and `@xstate/angular`:

```bash
npm i xstate @xstate/angular
```

2. Import the `useMachine` function:

```angular-ts
import { useMachine } from '@xstate/angular';
import { createMachine } from 'xstate';
import {Component, inject} from '@angular/core';

const toggleMachine = createMachine({
id: 'toggle',
initial: 'inactive',
states: {
inactive: {
on: { TOGGLE: 'active' }
},
active: {
on: { TOGGLE: 'inactive' }
}
}
});

const ToggleMachine = useMachine(toggleMachine, {providedIn: 'root'})

@Component({
selector: 'app-toggle',
standalone: true,
imports: [],
template: `<button (click)="toggleMachine.send({type: 'TOGGLE'})">
{{
toggleMachine.snapshot().value === 'inactive'
? 'Click to activate'
: 'Active! Click to deactivate'
}}
</button>
`,
styleUrl: './toggle.component.css'
})
export class ToggleComponent {
public toggleMachine = inject(ToggleMachine);
}
```
7 changes: 7 additions & 0 deletions packages/xstate-angular/ng-package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
"dest": "./dist",
"lib": {
"entryFile": "src/index.ts"
}
}
77 changes: 77 additions & 0 deletions packages/xstate-angular/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
{
"name": "@xstate/angular",
"version": "0.0.1",
"description": "XState tools for Angular",
"keywords": [
"state",
"machine",
"statechart",
"scxml",
"state",
"graph",
"angular"
],
"type": "module",
"author": "David Khourshid <[email protected]>",
"homepage": "https://github.com/statelyai/xstate/tree/main/packages/xstate-angular#readme",
"license": "MIT",
"main": "dist/xstate-angular.cjs.js",
"module": "dist/xstate-angular.esm.js",
"exports": {
".": {
"types": {
"import": "./dist/xstate-angular.cjs.mjs",
"default": "./dist/xstate-angular.cjs.js"
},
"development": {
"module": "./dist/xstate-angular.development.esm.js",
"import": "./dist/xstate-angular.development.cjs.mjs",
"default": "./dist/xstate-angular.development.cjs.js"
},
"module": "./dist/xstate-angular.esm.js",
"import": "./dist/xstate-angular.cjs.mjs",
"default": "./dist/xstate-angular.cjs.js"
},
"./package.json": "./package.json"
},
"imports": {
"#is-development": {
"development": "./src/true.ts",
"default": "./src/false.ts"
}
},
"sideEffects": false,
"files": [
"dist"
],
"repository": {
"type": "git",
"url": "git+ssh://[email protected]/statelyai/xstate.git"
},
"bugs": {
"url": "https://github.com/statelyai/xstate/issues"
},
"peerDependencies": {
"@angular/core": "^17.0.0",
"xstate": "^5.9.1"
},
"peerDependenciesMeta": {
"xstate": {
"optional": true
}
},
"devDependencies": {
"@angular/common": "^17.0.0",
"@angular/compiler": "^17.0.0",
"@angular/compiler-cli": "^17.0.0",
"@angular/core": "^17.0.0",
"@angular/platform-browser": "^17.0.0",
"@angular/platform-browser-dynamic": "^17.0.0",
"ng-packagr": "^17.0.0",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How strongly required this is? it might be slightly challenging to incorporate this into our current setup. It's certainly doable but if we wouldn't have to use this... that would be kinda simpler for us

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it is required but I will check in the morning

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah it is needed. Not sure what the best way to move forward is on this one, as using babel/preconstruct doesn't make a whole lot of sense here (from what I can say)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can figure it out on my own before we land this - I don't want to put on you the burden of figuring intricacies of our build pipeline. I wonder, what makes it required? Angular surely has to be able to consume regular npm packages - what's different about a package like this one?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://angular.io/guide/angular-package-format They are doing pre-optimizations, it would probably work fine.
For now I will just exclude it from preconstruct.

We can also schedule a call and figure out the build together, also feel somewhat bad to put that burden on you :D

"rxjs": "^7.8.1",
"tslib": "2.6.2",
"typescript": "^5.4.2",
"xstate": "5.9.1",
"zone.js": "0.14.4"
}
}
1 change: 1 addition & 0 deletions packages/xstate-angular/src/false.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default false;
4 changes: 4 additions & 0 deletions packages/xstate-angular/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export { useActor } from './useActor.ts';
export { useActorRef } from './useActorRef.ts';
export { useMachine } from './useMachine.ts';
export { useSelector } from './useSelector.ts';
1 change: 1 addition & 0 deletions packages/xstate-angular/src/true.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default true;
51 changes: 51 additions & 0 deletions packages/xstate-angular/src/useActor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import {
Actor,
ActorOptions,
AnyActorLogic,
Snapshot,
SnapshotFrom
} from 'xstate';
import {
Injectable,
Signal,
signal,
Type,
WritableSignal
} from '@angular/core';
import { useSelector } from './useSelector.ts';
import { useActorRef } from './useActorRef.ts';

export function useActor<TLogic extends AnyActorLogic>(
actorLogic: TLogic,
_options?: ActorOptions<TLogic> & { providedIn: 'root' }
): Type<ActorStoreProps<TLogic>> {
const { providedIn, ...options } = _options ?? {};

@Injectable({ providedIn: providedIn ?? null })
class ActorStore implements ActorStoreProps<TLogic> {
public actorRef: Actor<TLogic>;
private _snapshot: WritableSignal<SnapshotFrom<TLogic>>;
public send: Actor<TLogic>['send'];

public get snapshot() {
return this._snapshot.asReadonly();
}

constructor() {
const listener = (nextSnapshot: Snapshot<unknown>) => {
this._snapshot?.set(nextSnapshot as any);
};

this.actorRef = useActorRef(actorLogic, options, listener);
this._snapshot = signal(useSelector(this.actorRef as any, (s) => s)());
this.send = this.actorRef.send;
}
}
return ActorStore;
Comment on lines +24 to +44
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of creating an injectable like this, I think we can just use an injection token with a factory which should simplify this a lot.

}

export interface ActorStoreProps<TLogic extends AnyActorLogic> {
actorRef: Actor<TLogic>;
snapshot: Signal<SnapshotFrom<TLogic>>;
send: Actor<TLogic>['send'];
}
45 changes: 45 additions & 0 deletions packages/xstate-angular/src/useActorRef.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import {
Actor,
ActorOptions,
AnyActorLogic,
createActor,
Observer,
SnapshotFrom,
Subscription,
toObserver
} from 'xstate';
import {
afterNextRender,
AfterRenderPhase,
DestroyRef,
inject
} from '@angular/core';

export function useActorRef<TLogic extends AnyActorLogic>(
actorLogic: TLogic,
options: ActorOptions<TLogic> = {},
observerOrListener?:
| Observer<SnapshotFrom<TLogic>>
| ((value: SnapshotFrom<TLogic>) => void)
): Actor<TLogic> {
const actorRef = createActor(actorLogic, options);

let sub: Subscription;
if (observerOrListener) {
sub = actorRef.subscribe(toObserver(observerOrListener));
}

afterNextRender(
() => {
actorRef.start();
},
{ phase: AfterRenderPhase.Read }
);
Comment on lines +32 to +37
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't we just start it directly? What's the idea of running it after next render?


inject(DestroyRef).onDestroy(() => {
actorRef.stop();
sub?.unsubscribe();
});

return actorRef;
}
12 changes: 12 additions & 0 deletions packages/xstate-angular/src/useMachine.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { ActorOptions, AnyStateMachine } from 'xstate';
import { useActor } from './useActor.ts';

/**
* @alias useActor
*/
export function useMachine<TMachine extends AnyStateMachine>(
actorLogic: TMachine,
options?: ActorOptions<TMachine> & { providedIn: 'root' }
) {
return useActor(actorLogic, options);
}
26 changes: 26 additions & 0 deletions packages/xstate-angular/src/useSelector.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { ActorRef, SnapshotFrom } from 'xstate';
import { computed, Signal, signal } from '@angular/core';

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

export function useSelector<TActor extends ActorRef<any, any> | undefined, T>(
actor: TActor,
selector: (
snapshot: TActor extends ActorRef<any, any>
? SnapshotFrom<TActor>
: undefined
) => T,
compare: (a: T, b: T) => boolean = defaultCompare
): Signal<T> {
const actorRefRef = signal(actor);
return computed(
() => {
const actorRef = actorRefRef();
const snapshot = actorRef?.getSnapshot();
return selector(snapshot);
},
{ equal: compare }
);
}
Loading
Loading