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

Added getSignalValues along with a demo #50

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
7 changes: 6 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,10 @@
"**/.DS_Store": true,
"**/Thumbs.db": true
},
"hide-files.files": []
"hide-files.files": [],
"workbench.colorCustomizations": {
"activityBar.background": "#0A350D",
"titleBar.activeBackground": "#0E4A12",
"titleBar.activeForeground": "#F2FCF2"
}
}
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 @@ -2,6 +2,7 @@
<div class="nav">
<mat-nav-list>
<a mat-list-item routerLink="/todo">DevTools</a>
<a mat-list-item routerLink="/todo-with-computed">getSignalValues</a>
<a mat-list-item routerLink="/flight-search">withRedux</a>
<a mat-list-item routerLink="/flight-search-data-service-simple">withDataService (Simple)</a>
<a mat-list-item routerLink="/flight-search-data-service-dynamic">withDataService (Dynamic)</a>
Expand Down
2 changes: 2 additions & 0 deletions apps/demo/src/app/lazy-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ import { FlightEditDynamicComponent } from './flight-search-data-service-dynamic
import { TodoStorageSyncComponent } from './todo-storage-sync/todo-storage-sync.component';
import { provideFlightStore } from './flight-search-redux-connector/+state/redux';
import { FlightSearchReducConnectorComponent } from './flight-search-redux-connector/flight-search.component';
import { TodoWithComputedComponent } from './todo-with-computed/todo-with-computed.component';

export const lazyRoutes: Route[] = [
{ path: 'todo', component: TodoComponent },
{ path: 'todo-with-computed', component: TodoWithComputedComponent},
{ path: 'flight-search', component: FlightSearchComponent },
{
path: 'flight-search-data-service-simple',
Expand Down
64 changes: 64 additions & 0 deletions apps/demo/src/app/todo-with-computed/todo-with-computed-store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { computed } from '@angular/core';
import { signalStore, withComputed, withHooks, withMethods } from '@ngrx/signals';
import {
EntityMap,
removeEntity,
setEntity,
updateEntity,
withEntities,
} from '@ngrx/signals/entities';
import { getSignalValues, updateState, withDevtools } from 'ngrx-toolkit';

export interface Todo {
id: number;
name: string;
finished: boolean;
description?: string;
deadline?: Date;
}

export type AddTodo = Omit<Todo, 'id'>;

export const TodoWithComputedStore = signalStore(
{ providedIn: 'root' },
withDevtools('todo'),
withEntities<Todo>(),
withComputed(store => ({
openItems: computed(() => openItems(getSignalValues(store)))
})),
withMethods((store) => {
let currentId = 0;
return {
add(todo: AddTodo) {
updateState(store, 'add todo', setEntity({ id: ++currentId, ...todo }));
},

remove(id: number) {
updateState(store, 'remove todo', removeEntity(id));
},

toggleFinished(id: number): void {
const todo = store.entityMap()[id];
updateState(
store,
'toggle todo',
updateEntity({ id, changes: { finished: !todo.finished } })
);
},
};
}),
withHooks({
onInit: (store) => {
store.add({ name: 'Go for a Walk', finished: false });
store.add({ name: 'Sleep 8 hours once', finished: false });
store.add({ name: 'Clean the room', finished: true });
},
})
);


function openItems(state: {entities: Todo[], entityMap: EntityMap<Todo>} ): string {
const openIds = state.entities.filter(todo => !todo.finished).map(todo => todo.id);
const strings = openIds.map(id => state.entityMap[id].name);
return strings.join(', ');
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<!-- Checkbox Column -->
<ng-container matColumnDef="finished">
<mat-header-cell *matHeaderCellDef></mat-header-cell>
<mat-cell *matCellDef="let row" class="actions">
<mat-checkbox
(click)="$event.stopPropagation()"
(change)="checkboxLabel(row)"
[checked]="row.finished"
>
</mat-checkbox>
<mat-icon (click)="removeTodo(row)">delete</mat-icon>
</mat-cell>
</ng-container>

<!-- Name Column -->
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
<mat-cell *matCellDef="let element">{{ element.name }}</mat-cell>
</ng-container>

<!-- Description Column -->
<ng-container matColumnDef="description">
<mat-header-cell *matHeaderCellDef>Description</mat-header-cell>
<mat-cell *matCellDef="let element">{{ element.description }}</mat-cell>
</ng-container>

<!-- Deadline Column -->
<ng-container matColumnDef="deadline">
<mat-header-cell mat-header-cell *matHeaderCellDef
>Deadline</mat-header-cell
>
<mat-cell mat-cell *matCellDef="let element">{{
element.deadline
}}</mat-cell>
</ng-container>

<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row
*matRowDef="let row; columns: displayedColumns"
(click)="selection.toggle(row)"
></mat-row>
</mat-table>

<hr>

<h1>State values without entityMap and ids:</h1>
<pre>
{{entireState() | json}}
</pre>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.actions{
display: flex;
align-items: center;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { Component, computed, effect, inject } from '@angular/core';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatIconModule } from '@angular/material/icon';
import { MatTableDataSource, MatTableModule } from '@angular/material/table';
import { Todo } from '../todo-store';
import { CategoryStore } from '../category.store';
import { SelectionModel } from '@angular/cdk/collections';
import { TodoWithComputedStore } from './todo-with-computed-store';
import { getSignalValues } from 'ngrx-toolkit';
import { CommonModule } from '@angular/common';

@Component({
selector: 'demo-todo-with-computed',
templateUrl: 'todo-with-computed.component.html',
styleUrl: 'todo-with-computed.component.scss',
standalone: true,
imports: [MatCheckboxModule, MatIconModule, MatTableModule, CommonModule],
})
export class TodoWithComputedComponent {
todoStore = inject(TodoWithComputedStore);
categoryStore = inject(CategoryStore);

displayedColumns: string[] = ['finished', 'name', 'description', 'deadline'];
dataSource = new MatTableDataSource<Todo>([]);
selection = new SelectionModel<Todo>(true, []);

entireState = computed(() => getSignalValues(this.todoStore, 'entityMap', 'ids'));

constructor() {
effect(() => {
this.dataSource.data = this.todoStore.entities();
});
}

checkboxLabel(todo: Todo) {
this.todoStore.toggleFinished(todo.id);
}

removeTodo(todo: Todo) {
this.todoStore.remove(todo.id);
}
}
1 change: 1 addition & 0 deletions libs/ngrx-toolkit/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ export * from './lib/with-data-service';
export { withStorageSync, SyncConfig } from './lib/with-storage-sync';
export * from './lib/redux-connector';
export * from './lib/redux-connector/rxjs-interop';
export * from './lib/shared/get-signal-values';
45 changes: 45 additions & 0 deletions libs/ngrx-toolkit/src/lib/shared/get-signal-values.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { Signal } from '@angular/core';
import { SIGNAL } from '@angular/core/primitives/signals';

type Rec = Record<string, any>;

type SignalPropertyNames<T extends Rec> = {
[K in keyof T]: T[K] extends Signal<any> ? K : never;
}[keyof T];

type SignalProperties<T extends Rec, Without extends keyof T = never> = Pick<
T,
Exclude<SignalPropertyNames<T>, Without>
>;

type SignalPropertyValues<T extends Rec, Without extends keyof T = never> = {
[K in keyof SignalProperties<
T,
Without
>]: SignalProperties<T>[K] extends Signal<any>
? ReturnType<SignalProperties<T>[K]>
: never;
};

export function getSignalValues<T extends Rec, Without extends keyof T = never>(
signals: T,
...exclude: Without[]
): SignalPropertyValues<T, Without> {
const result: Partial<SignalPropertyValues<T, Without>> = {};
const withouts = new Set(exclude);

const entries = Object.entries(signals)
.filter(
([_, value]) =>
typeof value === 'function' && hasOwnSymbol(value, SIGNAL)
)
.filter(([key]) => !withouts.has(key as Without))
.map(([key, value]) => [key, value()]);

const reduced = Object.fromEntries(entries) as SignalPropertyValues<T, Without>;
return reduced;
}

export function hasOwnSymbol(obj: any, symbol: symbol) {
return Object.getOwnPropertySymbols(obj).includes(symbol);
}