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(#632) - Locale pipe optimization #637

Open
wants to merge 2 commits into
base: master
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
36 changes: 34 additions & 2 deletions libs/transloco-locale/src/lib/pipes/base-locale.pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,50 @@ import { TranslocoLocaleService } from '../transloco-locale.service';

type Deps = [TranslocoLocaleService, ChangeDetectorRef];
@Injectable()
export abstract class BaseLocalePipe implements OnDestroy {
export abstract class BaseLocalePipe<VALUE = unknown, ARGS extends unknown[] = []> implements OnDestroy {
protected localeService = inject(TranslocoLocaleService);
protected cdr = inject(ChangeDetectorRef);

private localeChangeSub: Subscription | null =
this.localeService.localeChanges$.subscribe(() => this.cdr.markForCheck());
this.localeService.localeChanges$.subscribe(() => this.invalidate());

protected lastValue?: VALUE;
protected lastArgs?: string;

protected lastResult = '';

protected getLocale(locale?: Locale): Locale {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return locale || this.localeService.getLocale()!;
}

transform(value: VALUE, ...args: ARGS): string {
if (this.isSameValue(value) && this.isSameArgs(...args)) {
return this.lastResult;
}
this.lastResult = this.doTransform(value, ...args);
this.lastValue = value;
this.lastArgs = JSON.stringify(args);
return this.lastResult;
}

protected abstract doTransform(value: VALUE, ...args: ARGS): string;

protected isSameValue(value: VALUE): boolean {
return this.lastValue === value;
}

protected isSameArgs(...args: ARGS): boolean {
return JSON.stringify(args) === this.lastArgs;
}

invalidate() {
this.lastValue = undefined;
this.lastArgs = undefined;
this.lastResult = '';
this.cdr.markForCheck();
}

ngOnDestroy(): void {
this.localeChangeSub?.unsubscribe();
// Caretaker note: it's important to clean up references to subscriptions since they save the `next`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ import { BaseLocalePipe } from './base-locale.pipe';
standalone: true,
})
export class TranslocoCurrencyPipe
extends BaseLocalePipe
extends BaseLocalePipe<number | string, [
display?: 'code' | 'symbol' | 'name',
numberFormatOptions?: NumberFormatOptions,
currencyCode?: Currency,
locale?: Locale]>
implements PipeTransform
{
private localeConfig: LocaleConfig = inject(TRANSLOCO_LOCALE_CONFIG);
Expand All @@ -35,7 +39,7 @@ export class TranslocoCurrencyPipe
* 1000000 | translocoCurrency: 'narrowSymbol' : {minimumFractionDigits: 0 } : CAD // $1,000,000
*
*/
transform(
protected override doTransform(
value: number | string,
display: 'code' | 'symbol' | 'narrowSymbol' | 'name' = 'symbol',
numberFormatOptions: NumberFormatOptions = {},
Expand Down
15 changes: 13 additions & 2 deletions libs/transloco-locale/src/lib/pipes/transloco-date.pipe.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { inject, Pipe, PipeTransform } from '@angular/core';
import { isNil } from '@ngneat/transloco';

import { isDate } from '../helpers';
import { getDefaultOptions } from '../shared';
import { TRANSLOCO_LOCALE_CONFIG } from '../transloco-locale.config';
import {
Expand All @@ -17,7 +18,9 @@ import { BaseLocalePipe } from './base-locale.pipe';
pure: false,
standalone: true,
})
export class TranslocoDatePipe extends BaseLocalePipe implements PipeTransform {
export class TranslocoDatePipe
extends BaseLocalePipe<ValidDate, [options?: DateFormatOptions, locale?: Locale]>
implements PipeTransform {
private localeConfig: LocaleConfig = inject(TRANSLOCO_LOCALE_CONFIG);

/**
Expand All @@ -34,13 +37,21 @@ export class TranslocoDatePipe extends BaseLocalePipe implements PipeTransform {
* 1 | translocoDate: { dateStyle: 'medium' } // Jan 1, 1970
* '2019-02-08' | translocoDate: { dateStyle: 'medium' } // Feb 8, 2019
*/
transform(date: ValidDate, options: DateFormatOptions = {}, locale?: Locale) {
protected override doTransform(date: ValidDate, options: DateFormatOptions = {}, locale?: Locale) {
if (isNil(date)) return '';
locale = this.getLocale(locale);

return this.localeService.localizeDate(date, locale, {
...getDefaultOptions(locale, 'date', this.localeConfig),
...options,
});
}

protected override isSameValue(value?: ValidDate) {
return this.getComparableDate(this.lastValue) === this.getComparableDate(value);
}

private getComparableDate(value?: any) {
return isDate(value) ? value.getTime() : value;
}
}
4 changes: 2 additions & 2 deletions libs/transloco-locale/src/lib/pipes/transloco-decimal.pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { BaseLocalePipe } from './base-locale.pipe';
standalone: true,
})
export class TranslocoDecimalPipe
extends BaseLocalePipe
extends BaseLocalePipe<string | number, [numberFormatOptions?: NumberFormatOptions, locale?: Locale]>
implements PipeTransform
{
private localeConfig: LocaleConfig = inject(TRANSLOCO_LOCALE_CONFIG);
Expand All @@ -31,7 +31,7 @@ export class TranslocoDecimalPipe
* 1234567890 | translocoDecimal: {useGrouping: false}: en-US // 1234567890
*
*/
transform(
protected override doTransform(
value: string | number,
numberFormatOptions: NumberFormatOptions = {},
locale?: Locale
Expand Down
4 changes: 2 additions & 2 deletions libs/transloco-locale/src/lib/pipes/transloco-percent.pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { BaseLocalePipe } from './base-locale.pipe';
standalone: true,
})
export class TranslocoPercentPipe
extends BaseLocalePipe
extends BaseLocalePipe<number | string, [numberFormatOptions?: NumberFormatOptions, locale?: Locale]>
implements PipeTransform
{
private localeConfig: LocaleConfig = inject(TRANSLOCO_LOCALE_CONFIG);
Expand All @@ -31,7 +31,7 @@ export class TranslocoPercentPipe
* "1" | translocoPercent : {} : en-US // 100%
*
*/
transform(
protected override doTransform(
value: number | string,
numberFormatOptions: NumberFormatOptions = {},
locale?: Locale
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,39 @@ describe('TranslocoCurrencyPipe', () => {
expect(maximumFractionDigits).toEqual(4);
});

it('should return previous result with same config', () => {
spectator = pipeFactory(
`{{ data | translocoCurrency:'symbol':config }}`,
{
hostProps: {
data: '123',
config: {
useGrouping: false,
maximumFractionDigits: 3,
},
},
}
);

const [, { useGrouping, maximumFractionDigits }] = getIntlCallArgs();
expect(useGrouping).toBeFalsy();
expect(maximumFractionDigits).toEqual(3);
const first = spectator.element.textContent;

intlSpy.calls.reset();
spectator.setHostInput({
data: '123',
config: {
useGrouping: false,
maximumFractionDigits: 3,
},
});
const second = spectator.element.textContent;

expect(intlSpy).not.toHaveBeenCalled();
expect(second).toBe(first);
});

it('should take number options from locale settings', () => {
spectator = pipeFactory(`{{ '123' | translocoCurrency }}`, {
providers: [provideTranslocoServiceMock('es-ES')],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,30 @@ describe('TranslocoDatePipe', () => {
expect(timeStyle).toEqual('medium');
});

it('should return previous result with same config', () => {
spectator = pipeFactory(`{{ date | translocoDate:config }}`, {
hostProps: {
date,
config: { dateStyle: 'medium', timeStyle: 'medium' },
},
});

const [, { dateStyle, timeStyle }] = getIntlCallArgs();
expect(dateStyle).toEqual('medium');
expect(timeStyle).toEqual('medium');
const first = spectator.element.textContent;

intlSpy.calls.reset();
spectator.setHostInput({
date,
config: { dateStyle: 'medium', timeStyle: 'medium' },
});
const second = spectator.element.textContent;

expect(intlSpy).not.toHaveBeenCalled();
expect(second).toBe(first);
});

it('should consider a global date config', () => {
spectator = pipeFactory(`{{ date | translocoDate }}`, {
hostProps: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,31 @@ describe('TranslocoDecimalPipe', () => {
expect(spectator.element).toHaveText('');
});
});

it('should return previous result with same config', () => {
spectator = pipeFactory(
`{{ data | translocoDecimal:config }}`,
{
hostProps: {
data: 123,
config: { useGrouping: false, maximumFractionDigits: 3 }
}
}
);

const [, { useGrouping, maximumFractionDigits }] = getIntlCallArgs();
expect(useGrouping).toBeFalsy();
expect(maximumFractionDigits).toEqual(3);
const first = spectator.element.textContent;

intlSpy.calls.reset();
spectator.setHostInput({
data: 123,
config: { useGrouping: false, maximumFractionDigits: 3 }
});
const second = spectator.element.textContent;

expect(intlSpy).not.toHaveBeenCalled();
expect(second).toBe(first);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,31 @@ describe('TranslocoPercentPipe', () => {
expect(useGrouping).toBeTrue();
expect(maximumFractionDigits).toEqual(3);
});

it('should return previous result with same config', () => {
spectator = pipeFactory(
`{{ data | translocoPercent:config }}`,
{
hostProps: {
data: '123',
config: { useGrouping: false, maximumFractionDigits: 3 }
}
}
);

const [, { useGrouping, maximumFractionDigits }] = getIntlCallArgs();
expect(useGrouping).toBeFalsy();
expect(maximumFractionDigits).toEqual(3);
const first = spectator.element.textContent;

intlSpy.calls.reset();
spectator.setHostInput({
data: '123',
config: { useGrouping: false, maximumFractionDigits: 3 }
});
const second = spectator.element.textContent;

expect(intlSpy).not.toHaveBeenCalled();
expect(second).toBe(first);
});
});
Loading