Skip to content

Commit

Permalink
feat(signal-state): Introducing a new library to the S-Libs family: S…
Browse files Browse the repository at this point in the history
…ignal State! A state management library similar to App State, built on Angular Signals instead of RxJS.
  • Loading branch information
ersimont authored Jan 2, 2024
1 parent 6df8150 commit e7f8797
Show file tree
Hide file tree
Showing 44 changed files with 1,442 additions and 62 deletions.
13 changes: 13 additions & 0 deletions .idea/runConfigurations/signal_store___build.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions .idea/runConfigurations/signal_store___test_server.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ This is a collection of libraries from Simonton Software, written in TypeScript
- [`ng-core`](https://github.com/simontonsoftware/s-libs/tree/master/projects/ng-core): Miscellaneous utilities for Angular
- [`ng-app-state`](https://github.com/simontonsoftware/s-libs/tree/master/projects/ng-app-state): Painlessly integrate `app-state` into template-driven Angular forms
- [`ng-mat-core`](https://github.com/simontonsoftware/s-libs/tree/master/projects/ng-mat-core): Miscellaneous utilities for Angular Material
- [`signal-store`](https://github.com/simontonsoftware/s-libs/tree/master/projects/signal-store): A state management library based on Angular signals
- [`ng-dev`](https://github.com/simontonsoftware/s-libs/tree/master/projects/ng-dev): Miscellaneous utilities to use while developing Angular apps
- [`eslint-config-ng`](https://github.com/simontonsoftware/s-libs/tree/master/projects/eslint-config-ng): Recommended default config for ESLint in an Angular project.
39 changes: 39 additions & 0 deletions angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,45 @@
}
}
}
},
"signal-store": {
"projectType": "library",
"root": "projects/signal-store",
"sourceRoot": "projects/signal-store/src",
"prefix": "s",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:ng-packagr",
"options": {
"project": "projects/signal-store/ng-package.json"
},
"configurations": {
"production": {
"tsConfig": "projects/signal-store/tsconfig.lib.prod.json"
},
"development": {
"tsConfig": "projects/signal-store/tsconfig.lib.json"
}
},
"defaultConfiguration": "production"
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"tsConfig": "projects/signal-store/tsconfig.spec.json",
"polyfills": ["zone.js", "zone.js/testing"]
}
},
"lint": {
"builder": "@angular-eslint/builder:lint",
"options": {
"lintFilePatterns": [
"projects/signal-store/**/*.ts",
"projects/signal-store/**/*.html"
]
}
}
}
}
},
"schematics": {
Expand Down
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@
"filename": "projects/ng-mat-core/package.json",
"type": "json"
},
{
"filename": "projects/signal-store/package.json",
"type": "json"
},
{
"filename": "projects/rxjs-core/package.json",
"type": "json"
Expand Down
65 changes: 6 additions & 59 deletions projects/app-state/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
An observable state management library. Think of it like Redux, but without actions or reducers. That makes it a natural fit for anyone who wants the benefits of centralized state management, without adopting a function style of programming.
An observable state management library. Directly read, write, and observe any part of your state without writing any selectors, actions, or reducers.

## API Documentation

Expand All @@ -9,11 +9,11 @@ Once you are familiar with the basics, it may help to see the [api documentation
A basic idea behind this library is to keep all the state of your app in one place, accessible for any component or service to access, modify and subscribe to changes. This has several benefits:

- Components no longer need multiple inputs and outputs to route state and mutations to the proper components. Instead they can obtain the store via dependency injection.
- During debugging you can look in one place to see the state of your entire app. Moreover, development tools can be used to see this information at a glance along with a full history of changes leading up to the current state ([Redux DevTools](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en)).
- During debugging, you can look in one place to see the state of your entire app. Moreover, development tools can be used to see this information at a glance along with a full history of changes leading up to the current state ([Redux DevTools](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en)).
- The objects in the store are immutable (as long as you only modify the state via the store, as you should), which enables more benefits:
- Immutable objects allow you to use Angular's on-push change detection, which can be a huge performance gain for apps with a large state.
- Immutable objects allow efficient comparison using `===` to determine if they changed. Note that if you are using Angular this enables on-push change detection, but you should consider the newer [`signal-store`](https://github.com/simontonsoftware/s-libs/tree/master/projects/signal-store) instead!
- Undo/redo features become very simple. This library includes a helper to make it even easier (more info below).
- Every piece of state is observable. You can subscribe to the root of the store to get notified of every state change anywhere in the app, for a specific boolean buried deep within your state, or anywhere in between.
- Every piece of state is observable. You can subscribe to the root of the store to get notified of every state change anywhere in the app, a specific boolean buried deep within your state, or anywhere in between.

2 terms are worth defining immediately. As they are used in this library, they mean:

Expand Down Expand Up @@ -52,73 +52,21 @@ export class User {
}
```

Then create a subclass of `RootStore`. A single instance of that class will serve as the entry point to obtain and modify the state it holds. Most often you will make that class an Angular service that can be injected anywhere in your app. For example:
Then create a subclass of `RootStore`. A single instance of that class will serve as the entry point to obtain and modify the state it holds.

```ts
// state/my-store.service.ts
// state/my-store.ts

import { Injectable } from "@angular/core";
import { RootStore } from "@s-libs/app-state";
import { MyState } from "./my-state";

@Injectable({ providedIn: "root" })
export class MyStore extends RootStore<MyState> {
constructor() {
super(new MyState());
}
}
```

## Usage

Consider this translation of the counter example from the `ngrx/store` readme:

```ts
// app-state.ts
export class AppState {
counter = 0;
}

// app-store.ts
@Injectable({ providedIn: "root" })
export class AppStore extends RootStore<AppState> {
constructor() {
super(new AppState());
}
}

// my-app-component.ts
@Component({
selector: "my-app",
template: `
<button (click)="increment()">Increment</button>
<div>Current Count: {{ counterStore.$ | async }}</div>
<button (click)="decrement()">Decrement</button>
<button (click)="reset()">Reset Counter</button>
`,
})
export class MyAppComponent {
counterStore: Store<number>;

constructor(store: AppStore) {
this.counterStore = store("counter");
}

increment() {
this.counterStore.set(this.counterStore.state() + 1);
}

decrement() {
this.counterStore.set(this.counterStore.state() - 1);
}

reset() {
this.counterStore.set(0);
}
}
```

## Style Guide

- Define your state using classes instead of interfaces, and when possible make `new StateObject()` come with the default values for all its properties.
Expand All @@ -139,7 +87,6 @@ export class MyAppComponent {
This package includes an abstract class, `UndoManager`, to assist you in creating undo/redo functionality. For example, a simple subclass that captures every state change into the undo history:

```ts
@Injectable()
class UndoService extends UndoManager<MyAppState, MyAppState> {
private skipNextChange = true;
Expand Down
15 changes: 15 additions & 0 deletions projects/integration/src/app/api-tests/signal-store.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { PersistentStore, RootStore, Store } from '@s-libs/signal-store';

describe('signal-store', () => {
it('has PersistentStore', () => {
expect(PersistentStore).toBeDefined();
});

it('has RootStore', () => {
expect(RootStore).toBeDefined();
});

it('has Store', () => {
expect(Store).toBeDefined();
});
});
4 changes: 3 additions & 1 deletion projects/integration/src/app/app.component.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<a routerLink="/nas-model">NasModel</a>
-
<a routerLink="/app-state-performance">AppState Performance</a>
<a routerLink="/app-state-performance">App State Performance</a>
-
<a routerLink="/signal-store-performance">Signal Store Performance</a>
-
<a routerLink="/playground">Playground</a>

Expand Down
3 changes: 1 addition & 2 deletions projects/integration/src/app/app.config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { ApplicationConfig } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import { provideAnimations } from '@angular/platform-browser/animations';

export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes), provideAnimations()],
Expand Down
5 changes: 5 additions & 0 deletions projects/integration/src/app/app.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,15 @@ import { Routes } from '@angular/router';
import { AppStatePerformanceComponent } from './app-state-performance/app-state-performance.component';
import { NasModelComponent } from './nas-model/nas-model.component';
import { PlaygroundComponent } from './playground/playground.component';
import { SignalStorePerformanceComponent } from './signal-store-performance/signal-store-performance.component';

export const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'nas-model' },
{ path: 'nas-model', component: NasModelComponent },
{ path: 'app-state-performance', component: AppStatePerformanceComponent },
{
path: 'signal-store-performance',
component: SignalStorePerformanceComponent,
},
{ path: 'playground', component: PlaygroundComponent },
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<br />
<input [(ngModel)]="depth" /> Depth
<br />
<input [(ngModel)]="iterations" /> Iterations
<br />
<button (click)="run()">Run</button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import {
ChangeDetectionStrategy,
Component,
createEnvironmentInjector,
EnvironmentInjector,
inject,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RootStore } from '@s-libs/signal-store';
import {
DeepState,
runDeep,
subscribeDeep,
} from '../../../../../signal-store/src/performance/deep-performance';
import { unsubscribe } from '../../../../../signal-store/src/performance/performance-utils';

@Component({
selector: 'sl-deep-performance',
templateUrl: './deep-performance.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [FormsModule],
})
export class DeepPerformanceComponent {
protected depth = 1000;
protected iterations = 1000;

#injector = inject(EnvironmentInjector);

protected async run(): Promise<void> {
// `any` because we import functions directly from `signal-store` and TS doesn't like that
const store: any = new RootStore(new DeepState(this.depth));
const injector = createEnvironmentInjector([], this.#injector);

subscribeDeep(store, injector);
await runDeep(store, this.iterations, async () => Promise.resolve());
unsubscribe(this.depth, injector);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<sl-wide-performance />
<hr />
<sl-deep-performance />
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { DeepPerformanceComponent } from './deep-performance/deep-performance.component';
import { WidePerformanceComponent } from './wide-performance/wide-performance.component';

@Component({
selector: 'sl-signal-store-performance',
templateUrl: './signal-store-performance.component.html',
styleUrls: ['./signal-store-performance.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [DeepPerformanceComponent, WidePerformanceComponent],
})
export class SignalStorePerformanceComponent {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<br />
<input [(ngModel)]="width" /> Width
<br />
<input [(ngModel)]="iterations" /> Iterations
<br />
<button (click)="run()">Run</button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import {
ChangeDetectionStrategy,
Component,
createEnvironmentInjector,
EnvironmentInjector,
inject,
} from '@angular/core';
import { RootStore } from '@s-libs/signal-store';
import { unsubscribe } from '../../../../../signal-store/src/performance/performance-utils';
import {
runWide,
subscribeWide,
WideState,
} from '../../../../../signal-store/src/performance/wide-performance';
import { FormsModule } from '@angular/forms';

@Component({
selector: 'sl-wide-performance',
templateUrl: './wide-performance.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [FormsModule],
})
export class WidePerformanceComponent {
protected width = 1000;
protected iterations = 1000;

#injector = inject(EnvironmentInjector);

protected async run(): Promise<void> {
// `any` because we import functions directly from `signal-store` and TS doesn't like that
const store: any = new RootStore(new WideState(this.width));
const injector = createEnvironmentInjector([], this.#injector);

subscribeWide(store, injector);
await runWide(store, this.iterations, async () => Promise.resolve());
unsubscribe(this.width, injector);
}
}
2 changes: 2 additions & 0 deletions projects/ng-app-state/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
Painlessly integrate [`app-state`](https://github.com/simontonsoftware/s-libs/projects/app-state) into template-driven Angular forms.

**PLEASE NOTE:** [`signal-store`](https://github.com/simontonsoftware/s-libs/tree/master/projects/signal-store) is now available for Angular apps, based on Angular signals instead of RxJS. Its updated design does not require a separate library like this for integration into forms. Instead, with that library you simply use `[(ngModel)]="store.state"`.

## Installation

Install along with its peer dependencies using:
Expand Down
14 changes: 14 additions & 0 deletions projects/signal-store/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"extends": "../../.eslintrc.json",
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts"],
"parserOptions": {
"project": ["projects/signal-store/tsconfig.(lib|spec).json"]
},
"rules": {}
},
{ "files": ["*.html"], "rules": {} }
]
}
Loading

0 comments on commit e7f8797

Please sign in to comment.