Skip to content

feat: add with-connect feature #192

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

Open
wants to merge 1 commit 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 apps/demo/src/app/app.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
<a mat-list-item routerLink="/immutable-state">withImmutableState</a>
<a mat-list-item routerLink="/feature-factory">withFeatureFactory</a>
<a mat-list-item routerLink="/conditional">withConditional</a>
<a mat-list-item routerLink="/connect">withConnect</a>
</mat-nav-list>
</mat-drawer>
<mat-drawer-content>
Expand Down
41 changes: 41 additions & 0 deletions apps/demo/src/app/connect/connect.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Component, inject, linkedSignal } from '@angular/core';
import { signalStore, withState } from '@ngrx/signals';
import { FormsModule } from '@angular/forms';
import { withConnect } from '@angular-architects/ngrx-toolkit';

const initialState = { user: { name: 'Max' } };

const UserStore = signalStore(
{ providedIn: 'root' },
withState(initialState),
withConnect()
);

@Component({
template: `
<h2>
<pre>withConnect</pre>
</h2>
<p>
withConnect() adds a method to connect Signals back to your store.
Everytime these Signals change, the store will be updated accordingly.
</p>

<p>User name in Store: {{ userStore.user.name() }}</p>

<p>Connected local user name: <input [(ngModel)]="userName" /></p>
`,
imports: [FormsModule],
})
export class ConnectComponent {
protected readonly userStore = inject(UserStore);
protected readonly userName = linkedSignal(() => this.userStore.user.name());

constructor() {
this.userStore.connect(() => ({
user: {
name: this.userName(),
},
}));
}
}
5 changes: 5 additions & 0 deletions apps/demo/src/app/lazy-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,9 @@ export const lazyRoutes: Route[] = [
(m) => m.ConditionalSettingComponent
),
},
{
path: 'connect',
loadComponent: () =>
import('./connect/connect.component').then((m) => m.ConnectComponent),
},
];
52 changes: 52 additions & 0 deletions docs/docs/with-connect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
---
title: withConnect()
---

```typescript
import { withConnect } from '@angular-architects/ngrx-toolkit';
```

`withConnect()` adds a method to connect Signals back to your store. Everytime these Signals change, the store will be updated accordingly.

Example:

```ts
const Store = signalStore(
{ protectedState: false },
withState({
maxWarpFactor: 8,
shipName: 'USS Enterprise',
registration: 'NCC-1701',
poeple: 430,
}),
withConnect()
);
```

```ts
@Component({ ... })
export class MyComponent {
private store = inject(OfferListStore);

readonly maxWarpFactor = signal(8);
readonly registration = signal('NCC-1701');
readonly people = signal(430);

constructor() {
//
// Every change in the local Signals is
// refected in the store
//
this.store.connect(() => ({
//
// Subset of state in the store
//
maxWarpFactor: this.maxWarpFactor(),
registration: this.registration(),
poeple: this.poeple(),
}));
}

...
}
```
1 change: 1 addition & 0 deletions docs/sidebars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const sidebars: SidebarsConfig = {
'with-feature-factory',
'with-conditional',
'with-call-state',
'with-connect',
],
reduxConnectorSidebar: [
{
Expand Down
1 change: 1 addition & 0 deletions libs/ngrx-toolkit/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,4 @@ export {
} from './lib/storage-sync/with-storage-sync';
export { emptyFeature, withConditional } from './lib/with-conditional';
export { withFeatureFactory } from './lib/with-feature-factory';
export * from './lib/with-connect';
61 changes: 61 additions & 0 deletions libs/ngrx-toolkit/src/lib/with-connect.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { getState, patchState, signalStore, withState } from '@ngrx/signals';
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { signal } from '@angular/core';
import { withConnect } from './with-connect';

describe('withConnect', () => {
const setup = () => {
const Store = signalStore(
{ protectedState: false },
withState({
maxWarpFactor: 8,
shipName: 'USS Enterprise',
registration: 'NCC-1701',
poeple: 430,
}),
withConnect('maxWarpFactor', 'registration', 'poeple')
);

const store = TestBed.configureTestingModule({
providers: [Store],
}).inject(Store);

return { store };
};

it('should update store after connected signals are changed', fakeAsync(() => {
const { store } = setup();

TestBed.runInInjectionContext(() => {
const maxWarpFactor = signal(9);
const registration = signal('NCC-1701-D');
const poeple = signal(1100);

store.connect(() => ({
maxWarpFactor: maxWarpFactor(),
registration: registration(),
poeple: poeple(),
}));
tick(1);
expect(getState(store)).toMatchObject({
maxWarpFactor: 9,
shipName: 'USS Enterprise',
registration: 'NCC-1701-D',
poeple: 1100,
});

maxWarpFactor.set(9.6);
tick(1);
expect(getState(store).maxWarpFactor).toBeCloseTo(9.6);
expect(getState(store).shipName).toEqual('USS Enterprise');

patchState(store, { maxWarpFactor: 9.2 });
tick(1);
expect(getState(store).maxWarpFactor).toBeCloseTo(9.2);
expect(getState(store).shipName).toEqual('USS Enterprise');

// It's just a one-way-sync
expect(maxWarpFactor()).toBeCloseTo(9.6);
});
}));
});
55 changes: 55 additions & 0 deletions libs/ngrx-toolkit/src/lib/with-connect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { computed } from '@angular/core';
import {
EmptyFeatureResult,
patchState,
signalMethod,
SignalStoreFeature,
signalStoreFeature,
SignalStoreFeatureResult,
withMethods,
} from '@ngrx/signals';

export type WithConnectResultType<
T extends SignalStoreFeatureResult,
K extends keyof T['state']
> = EmptyFeatureResult & {
methods: {
connect(state: () => Partial<Pick<T['state'], K>>): void;
};
};

export function withConnect<
T extends SignalStoreFeatureResult,
Keys extends readonly (keyof T['state'])[]
>(
...keys: Keys
): SignalStoreFeature<T, WithConnectResultType<T, Keys[number]>> {
return signalStoreFeature(
withMethods((store) => {
return {
connect(stateFn: () => Partial<Pick<T['state'], Keys[number]>>): void {
const stateSignal = computed(stateFn);

// TypeScript allows additional keys
validateKeys(stateFn, keys);

signalMethod<Partial<Pick<T['state'], Keys[number]>>>((state) => {
patchState(store, state);
})(stateSignal);
},
};
})
);
}

function validateKeys<
T extends SignalStoreFeatureResult,
Keys extends readonly (keyof T['state'])[]
>(stateFn: () => Partial<Pick<T['state'], Keys[number]>>, keys: Keys) {
const candKeys = Object.keys(stateFn()) as unknown as Keys;
for (const key of candKeys) {
if (!keys.includes(key)) {
throw new Error(`Key ${String(key)} is not provided via withConnect!`);
}
}
}