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

Fix/several fixes #51

Merged
merged 7 commits into from
Apr 17, 2024
Merged
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
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { ProductDetail } from '../../models';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatCardModule } from '@angular/material/card';
import { CurrencyPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { input } from '@angular/core';
import { MatCardModule } from '@angular/material/card';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';

import { ProductDetail } from '../../models';

@Component({
selector: 'product-detail',
Expand All @@ -13,22 +14,22 @@ import { input } from '@angular/core';
@if (product()) {
<mat-card>
<mat-card-header>
<mat-card-title>{{ product()?.name }}</mat-card-title>
<mat-card-title>{{ product().name }}</mat-card-title>
<mat-card-subtitle
>Price: £{{ product()?.price | currency }} Released:
{{ product()?.releaseDate }}</mat-card-subtitle
>
</mat-card-header>
<img mat-card-image src="/{{ product()?.image }}" />
<mat-card-content>
<p>{{ product()?.description }}</p>
</mat-card-content>
</mat-card>
}
} @else {
<mat-spinner></mat-spinner>
>Price: £{{ product().price | currency }} Released:
{{ product().releaseDate }}</mat-card-subtitle
>
</mat-card-header>
<img mat-card-image src="/{{ product().image }}" />
<mat-card-content>
<p>{{ product().description }}</p>
</mat-card-content>
</mat-card>
}
`,
} @else {
<mat-spinner></mat-spinner>
}
`,
styles: [
`
mat-spinner {
Expand All @@ -41,6 +42,6 @@ import { input } from '@angular/core';
imports: [MatCardModule, MatProgressSpinnerModule, CurrencyPipe],
})
export class ProductDetailComponent {
product = input<ProductDetail>();
product = input.required<ProductDetail>();
productLoading = input(false);
}
7 changes: 7 additions & 0 deletions apps/example-app/src/app/examples/examples-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ const routes: Routes = [
'./signals/product-list-paginated-page/signal-product-list-paginated-page-container.component'
).then((m) => m.SignalProductListPaginatedPageContainerComponent),
},
{
path: 'infinite-scroll',
loadComponent: () =>
import(
'./signals/infinete-scroll-page/infinite-scroll-page.component'
).then((m) => m.InfiniteScrollPageComponent),
},
],
},
{
Expand Down
11 changes: 11 additions & 0 deletions apps/example-app/src/app/examples/models/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@ export interface ProductsStoreDetail {
manager: string;
departments: Department[];
}
export type ProductsStoreQuery = {
search?: string | undefined;
sortColumn?: keyof ProductsStore | undefined;
sortAscending?: string | undefined;
skip?: string | undefined;
take?: string | undefined;
};
export interface ProductsStoreResponse {
resultList: ProductsStore[];
total: number;
}

export interface ProductsStoreFilter {
search?: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,54 @@
import { ProductsStore, ProductsStoreDetail } from '../../models';
import { getRandomInteger } from '../../utils/form-utils';
import { sortData } from '@ngrx-traits/common';
import { rest } from 'msw';

import {
ProductsStore,
ProductsStoreDetail,
ProductsStoreQuery,
ProductsStoreResponse,
} from '../../models';
import { getRandomInteger } from '../../utils/form-utils';

export const storeHandlers = [
rest.get<never, never, ProductsStore[]>('/stores', (req, res, context) => {
return res(context.status(200), context.json(mockStores));
}),
rest.get<never, ProductsStoreQuery, ProductsStoreResponse>(
'/stores',
(req, res, ctx) => {
let result = [...mockStores];
const options = {
search: req.url.searchParams.get('search'),
sortColumn: req.url.searchParams.get('sortColumn'),
sortAscending: req.url.searchParams.get('sortAscending'),
skip: req.url.searchParams.get('skip'),
take: req.url.searchParams.get('take'),
};
if (options?.search)
result = mockStores.filter((entity) => {
return options?.search
? entity.name.toLowerCase().includes(options?.search.toLowerCase())
: false;
});
const total = result.length;
if (options?.skip || options?.take) {
const skip = +(options?.skip ?? 0);
const take = +(options?.take ?? 0);
result = result.slice(skip, skip + take);
}
if (options?.sortColumn) {
result = sortData(result, {
active: options.sortColumn as any,
direction: options.sortAscending === 'true' ? 'asc' : 'desc',
});
}
return res(ctx.status(200), ctx.json({ resultList: result, total }));
},
),
rest.get<never, { id: string }, ProductsStoreDetail | undefined>(
'/stores/:id',
(req, res, context) => {
const id = +req.params.id;
const storeDetail = mockStoresDetails.find((value) => value.id === id);
return res(context.status(200), context.json(storeDetail));
}
},
),
];

Expand Down Expand Up @@ -81,7 +117,7 @@ const names = [
'Wendi Ellis',
];

const mockStoresDetails: ProductsStoreDetail[] = new Array(200)
const mockStoresDetails: ProductsStoreDetail[] = new Array(500)
.fill(null)
.map((_, index) => {
return {
Expand Down Expand Up @@ -114,5 +150,5 @@ const mockStores: ProductsStore[] = mockStoresDetails.map(
id,
name,
address: address.line1 + ', ' + address.town + ', ' + address.postCode,
})
}),
);
Original file line number Diff line number Diff line change
@@ -1,14 +1,31 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ProductsStore, ProductsStoreDetail } from '../models';
import { delay, map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

import {
Product,
ProductsStore,
ProductsStoreDetail,
ProductsStoreResponse,
} from '../models';

@Injectable({ providedIn: 'root' })
export class ProductsStoreService {
constructor(private httpClient: HttpClient) {}

getStores() {
return this.httpClient.get<ProductsStore[]>('/stores/').pipe(delay(500));
getStores(options?: {
search?: string | undefined;
sortColumn?: keyof Product | string | undefined;
sortAscending?: boolean | undefined;
skip?: number | undefined;
take?: number | undefined;
}) {
console.log('getStores', options);
return this.httpClient
.get<ProductsStoreResponse>('/stores', {
params: { ...options, search: options?.search ?? '' },
})
.pipe(delay(500));
}
getStoreDetails(id: number) {
return this.httpClient
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import {
CdkFixedSizeVirtualScroll,
CdkScrollableModule,
CdkVirtualForOf,
CdkVirtualScrollViewport,
} from '@angular/cdk/scrolling';
import { CommonModule } from '@angular/common';
import { Component, inject, input } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { MatFormField, MatLabel } from '@angular/material/form-field';
import { MatProgressSpinner } from '@angular/material/progress-spinner';
import { MatOption, MatSelect } from '@angular/material/select';
import { getInfiniteScrollDataSource } from '@ngrx-traits/signals';

import { SearchOptionsComponent } from '../../../../components/search-options/search-options.component';
import { ProductsStore } from '../../../../models';
import { ProductsBranchStore } from './products-branch.store';

@Component({
selector: 'products-branch-dropdown',
standalone: true,
imports: [
CommonModule,
MatFormField,
MatLabel,
MatSelect,
SearchOptionsComponent,
MatOption,
MatProgressSpinner,
ReactiveFormsModule,
CdkVirtualScrollViewport,
CdkFixedSizeVirtualScroll,
CdkVirtualForOf,
],
template: ` <mat-form-field class="container" floatLabel="always">
<mat-label>{{ label() }}</mat-label>
<mat-select
[formControl]="control"
[placeholder]="store.isLoading() ? 'Loading...' : placeholder()"
[compareWith]="compareById"
(closed)="search('')"
>
<search-options (valueChanges)="search($event)"></search-options>
<cdk-virtual-scroll-viewport
itemSize="42"
class="fact-scroll-viewport"
minBufferPx="200"
maxBufferPx="200"
>
<mat-option
*ngIf="!!control.value"
class="fact-item"
[style]="{ height: 0 }"
[value]="control.value"
>
{{ control.value.name }}
</mat-option>
<mat-option
*cdkVirtualFor="let item of dataSource; trackBy: trackByFn"
class="fact-item"
[value]="item"
>
{{ item.name }}
</mat-option>
<mat-option disabled *ngIf="store.isLoading()">
<mat-spinner diameter="35"></mat-spinner>
</mat-option>
</cdk-virtual-scroll-viewport>
</mat-select>
</mat-form-field>`,
styles: [
`
.fact-scroll-viewport {
display: flex;
flex-direction: column;
box-sizing: border-box;
overflow-y: auto;
overflow-x: hidden;
height: 200px;
width: 100%;
}
:host {
display: inline-block;
}
.container {
width: 100%;
}
`,
],
providers: [ProductsBranchStore],
})
export class ProductsBranchDropdownComponent {
label = input('Branch');
placeholder = input('Please Select');
control = new FormControl();
store = inject(ProductsBranchStore);
dataSource = getInfiniteScrollDataSource({ store: this.store });

search(query: string) {
this.store.filterEntities({ filter: { search: query } });
}

trackByFn(index: number, item: ProductsStore) {
return item.id;
}
compareById(value: ProductsStore, option: ProductsStore) {
return value && option && value.id == option.id;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { inject } from '@angular/core';
import {
withCallStatus,
withEntitiesLoadingCall,
withEntitiesRemoteFilter,
withEntitiesRemoteScrollPagination,
withLogger,
} from '@ngrx-traits/signals';
import { signalStore, type } from '@ngrx/signals';
import { withEntities } from '@ngrx/signals/entities';
import { lastValueFrom } from 'rxjs';

import { ProductsStore } from '../../../../models';
import { ProductsStoreService } from '../../../../services/products-store.service';

const entity = type<ProductsStore>();
export const ProductsBranchStore = signalStore(
withEntities({
entity,
}),
withCallStatus({ initialValue: 'loading' }),
withEntitiesRemoteFilter({
entity,
defaultFilter: { search: '' },
}),
withEntitiesRemoteScrollPagination({
pageSize: 10,
entity,
}),

withEntitiesLoadingCall({
fetchEntities: async ({ entitiesPagedRequest, entitiesFilter }) => {
console.log('fetchEntities', entitiesPagedRequest(), entitiesFilter());
const res = await lastValueFrom(
inject(ProductsStoreService).getStores({
search: entitiesFilter().search,
skip: entitiesPagedRequest().startIndex,
take: entitiesPagedRequest().size,
}),
);
console.log({
search: entitiesFilter().search,
skip: entitiesPagedRequest().startIndex,
take: entitiesPagedRequest().size,
entities: res.resultList.length,
total: res.total,
});
return { entities: res.resultList, total: res.total };
},
}),
withLogger('branchStore'),
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';

import { ProductsBranchDropdownComponent } from './components/products-branch-dropdown/products-branch-dropdown.component';

@Component({
selector: 'infinite-scroll-page',
standalone: true,
imports: [CommonModule, ProductsBranchDropdownComponent],
template: `<products-branch-dropdown />`,
styles: ``,
})
export class InfiniteScrollPageComponent {}
Loading
Loading