Skip to content
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
3 changes: 3 additions & 0 deletions projects/components/action-button/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// export what ./public_api exports so we can import with the lib name like this:
// import { ModuleA } from 'libname'
export * from './public_api';
5 changes: 5 additions & 0 deletions projects/components/action-button/ng-package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"lib": {
"entryFile": "index.ts"
}
}
6 changes: 6 additions & 0 deletions projects/components/action-button/public_api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export { ZvActionButtonComponent, type IZvActionButton } from './src/action-button.component';
export {
ZvActionButtonDataSource,
type IZvActionButtonDataSource,
type IZvActionButtonDataSourceOptions,
} from './src/action-button-data-source';
40 changes: 40 additions & 0 deletions projects/components/action-button/src/action-button-data-source.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { computed, DestroyRef, effect, inject, linkedSignal, Signal } from '@angular/core';
import { ZvActionDataSource, ZvActionDataSourceOptions, ZvExceptionMessageExtractor } from '@zvoove/components/core';

export interface IZvActionButtonDataSource {
readonly showSuccess: Signal<boolean>;
readonly showLoading: Signal<boolean>;
readonly showError: Signal<boolean>;
readonly error: Signal<unknown>;
readonly errorMessage: Signal<string | null>;
readonly disabled: Signal<boolean>;
execute(): void;
}

export declare type IZvActionButtonDataSourceOptions = ZvActionDataSourceOptions;

export class ZvActionButtonDataSource extends ZvActionDataSource implements IZvActionButtonDataSource {
readonly #destroyRef = inject(DestroyRef);
readonly #errorMessageExtractor = inject(ZvExceptionMessageExtractor);
#timeoutRef: NodeJS.Timeout | undefined;

public readonly showLoading = this.isLoading;
public readonly showError = this.hasError;
public readonly disabled = this.isLoading;
public readonly showSuccess = linkedSignal(() => this.succeeded());
public readonly errorMessage = computed(() => (this.hasError() ? this.#errorMessageExtractor.extractErrorMessage(this.error()) : null));

constructor(options: IZvActionButtonDataSourceOptions) {
super(options);

effect(() => {
if (this.showSuccess()) {
clearTimeout(this.#timeoutRef);
this.#timeoutRef = setTimeout(() => {
this.showSuccess.set(false);
}, 2000);
}
});
this.#destroyRef.onDestroy(() => clearTimeout(this.#timeoutRef));
}
}
19 changes: 19 additions & 0 deletions projects/components/action-button/src/action-button.component.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<button
type="button"
[color]="color()"
mat-raised-button
(click)="dataSource().execute()"
[disabled]="dataSource().disabled() || disabled()"
[matTooltip]="dataSource().errorMessage()"
>
@if (dataSource().showError()) {
<mat-icon [color]="'warn'">error</mat-icon>
} @else if (dataSource().showLoading()) {
<mat-icon><mat-spinner [diameter]="18" /></mat-icon>
} @else if (dataSource().showSuccess()) {
<mat-icon [color]="'success'">check_circle</mat-icon>
} @else if (icon()) {
<mat-icon>{{ icon() }}</mat-icon>
}
<ng-content />
</button>
122 changes: 122 additions & 0 deletions projects/components/action-button/src/action-button.component.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { tap, timer } from 'rxjs';
import { ZvActionButtonDataSource } from './action-button-data-source';
import { ZvActionButtonComponent } from './action-button.component';
import { ZvActionButtonHarness } from './action-button.harness';
import { ZvButtonColors } from '@zvoove/components/core';

@Component({
selector: 'zv-test-component',
template: `
<zv-action-button [dataSource]="dataSource" [color]="color()" [icon]="'home'" [disabled]="isDisabled()"> label </zv-action-button>
`,
// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection
changeDetection: ChangeDetectionStrategy.Default,
imports: [ZvActionButtonComponent],
})
export class TestComponent {
public readonly isDisabled = signal<boolean>(false);
public readonly color = signal<ZvButtonColors | null>('primary');
public actionFnCalled = false;
public throwError: Error | null = null;
dataSource = new ZvActionButtonDataSource({
actionFn: () =>
timer(100).pipe(
tap(() => {
this.actionFnCalled = true;
if (this.throwError) {
throw this.throwError;
}
})
),
});
}
describe('ZvActionButton', () => {
let fixture: ComponentFixture<TestComponent>;
let component: TestComponent;
let loader: HarnessLoader;
let harness: ZvActionButtonHarness;

beforeEach(async () => {
TestBed.configureTestingModule({
imports: [TestComponent],
}).compileComponents();

fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
loader = TestbedHarnessEnvironment.loader(fixture);
harness = await loader.getHarness(ZvActionButtonHarness);
});

it('should create', () => {
expect(component).toBeDefined();
});

it('should call dataSource.execute() on click', async () => {
expect(component.actionFnCalled).toBeFalse();
await harness.click();
expect(component.actionFnCalled).toBeTrue();
});

it('should be blocked while loading', fakeAsync(async () => {
await harness.click();
tick(1);
expect(component.dataSource.showLoading()).toBeTrue();
expect(await harness.isLoading()).toBeTrue();
}));

it('should be disabled while loading', fakeAsync(async () => {
await harness.click();
tick(1);
expect(component.dataSource.showLoading()).toBeTrue();
expect(await harness.isDisabled()).toBeTrue();
}));

it('should respect disabled property', async () => {
expect(await harness.isDisabled()).toBeFalse();
component.isDisabled.set(true);
expect(await harness.isDisabled()).toBeTrue();
component.isDisabled.set(false);
expect(await harness.isDisabled()).toBeFalse();
});

it('should respect color property', async () => {
expect(await harness.hasClass('mat-primary')).toBeTrue();
component.color.set('accent');
expect(await harness.hasClass('mat-accent')).toBeTrue();
component.color.set('warn');
expect(await harness.hasClass('mat-warn')).toBeTrue();
});

it('should show icon', async () => {
expect(await harness.getIcon()).toBe('home');
});

it('should show label', async () => {
const buttonContent = await harness.getLabel();
expect(buttonContent).toContain('label');
});

it('should show success icon for 2 seconds', fakeAsync(async () => {
await harness.click();
tick(100);
expect(component.dataSource.showLoading()).toBeFalse();
expect(component.dataSource.showSuccess()).toBeTrue();
expect(await harness.getIcon()).toBe('check_circle');

tick(2000);
expect(component.dataSource.showSuccess()).toBeFalse();
expect(await harness.getIcon()).toBe('home');
}));

it('should show error message', fakeAsync(async () => {
component.throwError = new Error('action failed');
await harness.click();
tick(100);
expect(await harness.getIcon()).toBe('error');
expect(await harness.getErrorMessage()).toBe(component.throwError.message);
}));
});
39 changes: 39 additions & 0 deletions projects/components/action-button/src/action-button.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { afterRenderEffect, ChangeDetectionStrategy, Component, input, Signal, viewChild } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { ThemePalette } from '@angular/material/core';
import { MatIcon } from '@angular/material/icon';
import { MatProgressSpinner } from '@angular/material/progress-spinner';
import { MatTooltip } from '@angular/material/tooltip';
import { ZvButtonColors } from '@zvoove/components/core';
import { IZvActionButtonDataSource } from './action-button-data-source';

export interface IZvActionButton {
label: string;
color: ThemePalette | null;
icon: string;
dataCy: string;
isDisabled?: Signal<boolean>;
}

@Component({
selector: 'zv-action-button',
templateUrl: './action-button.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [MatIcon, MatButtonModule, MatProgressSpinner, MatTooltip],
})
export class ZvActionButtonComponent {
public readonly dataSource = input.required<IZvActionButtonDataSource>();
public readonly icon = input<string | null>(null);
public readonly color = input<ZvButtonColors | null | undefined>(null);
public readonly disabled = input<boolean>(false);

private readonly _tooltip = viewChild(MatTooltip);

constructor() {
afterRenderEffect(() => {
if (this.dataSource().showError()) {
this._tooltip()?.show(0);
}
});
}
}
38 changes: 38 additions & 0 deletions projects/components/action-button/src/action-button.harness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { ComponentHarness } from '@angular/cdk/testing';

export class ZvActionButtonHarness extends ComponentHarness {
static hostSelector = 'zv-action-button';

private _button = this.locatorForOptional('button');
private _buttonIcon = this.locatorForOptional('button mat-icon');
private _loadingSpinner = this.locatorForOptional('button mat-spinner');

public async click(): Promise<void> {
const button = await this._button();
return await button?.click();
}

public async getIcon(): Promise<string | undefined> {
return await (await this._buttonIcon())?.text();
}

public async getLabel(): Promise<string | null> {
return (await (await this._button())?.text()) ?? null;
}

public async isLoading(): Promise<boolean> {
return !!(await this._loadingSpinner());
}

public async isDisabled(): Promise<boolean | undefined> {
return await (await this._button())?.getProperty('disabled');
}

public async hasClass(className: string): Promise<boolean> {
return (await (await this._button())?.hasClass(className)) ?? false;
}

public async getErrorMessage(): Promise<string> {
return (await (await this._button())?.getAttribute('ng-reflect-message')) ?? '';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { ZvBlockUiHarness } from './testing/block-ui.harness';
})
export class TestComponent {
public blocked = false;
public spinnerText: string = null;
public spinnerText = '';
}

describe('ZvBlockUi', () => {
Expand Down
2 changes: 2 additions & 0 deletions projects/components/core/public_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,5 @@ export { provideDateTimeAdapters, provideDateTimeFormats } from './src/date-time
export { ZvDateTimeAdapter, type ZvDateTimeParts } from './src/date-time/date-time-adapter';
export { type ZvDateTimeFormats } from './src/date-time/date-time-formats';
export { ZvNativeDateTimeAdapter } from './src/date-time/native-date-time-adapter';

export { ZvActionDataSource, type IZvActionDataSource, type ZvActionDataSourceOptions } from './src/action-data-source/action-data-source';
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { switchMap, throwError, timer } from 'rxjs';
import { ZvActionDataSource } from './action-data-source';

describe('ActionDataSource', () => {
beforeAll(() => {
TestBed.configureTestingModule({});
});
it('should set properties correctly', fakeAsync(() => {
TestBed.runInInjectionContext(() => {
const dataSource = new ZvActionDataSource({ actionFn: () => timer(1) });
expect(dataSource.error()).toBe(null);
expect(dataSource.isLoading()).toBe(false);
expect(dataSource.hasError()).toBe(false);
expect(dataSource.succeeded()).toBe(false);

dataSource.execute();
expect(dataSource.error()).toBe(null);
expect(dataSource.isLoading()).toBe(true);
expect(dataSource.hasError()).toBe(false);
expect(dataSource.succeeded()).toBe(false);

tick(1);
expect(dataSource.error()).toBe(null);
expect(dataSource.isLoading()).toBe(false);
expect(dataSource.hasError()).toBe(false);
expect(dataSource.succeeded()).toBe(true);
});
}));

it('should set error correctly', fakeAsync(() => {
TestBed.runInInjectionContext(() => {
const error = new Error('action failed');
const dataSource = new ZvActionDataSource({ actionFn: () => timer(1).pipe(switchMap(() => throwError(() => error))) });
expect(dataSource.error()).toBe(null);
expect(dataSource.isLoading()).toBe(false);
expect(dataSource.hasError()).toBe(false);
expect(dataSource.succeeded()).toBe(false);

dataSource.execute();
expect(dataSource.error()).toBe(null);
expect(dataSource.isLoading()).toBe(true);
expect(dataSource.hasError()).toBe(false);
expect(dataSource.succeeded()).toBe(false);

tick(1);
expect(dataSource.error()).toBe(error);
expect(dataSource.isLoading()).toBe(false);
expect(dataSource.hasError()).toBe(true);
expect(dataSource.succeeded()).toBe(false);
});
}));
});
Loading