[ADF-4713] Add new DecimalNumber Pipe to transform and localize numbers (#4926)

* [ADF-4713] Add new DecimalNumber Pipe to transform and localize numbers

* Unsubscribe from userPreference service

* Make Pipe impure

* Add documentation in localization page
This commit is contained in:
davidcanonieto
2019-07-18 11:09:50 +01:00
committed by Eugenio Romano
parent 8ee5cd1908
commit a0d4160c11
25 changed files with 457 additions and 66 deletions

View File

@@ -78,7 +78,7 @@
"UPLOADER": "Uploader", "UPLOADER": "Uploader",
"WEBSCRIPT": "Webscript", "WEBSCRIPT": "Webscript",
"TAG": "Tag", "TAG": "Tag",
"DATE": "Date", "PIPES": "Pipes",
"TRASHCAN": "Trashcan", "TRASHCAN": "Trashcan",
"SOCIAL": "Social", "SOCIAL": "Social",
"SETTINGS": "Settings", "SETTINGS": "Settings",

View File

@@ -438,11 +438,16 @@
20 20
] ]
}, },
"dateValues":{ "dateValues": {
"defaultDateFormat": "mediumDate", "defaultDateFormat": "mediumDate",
"defaultDateTimeFormat": "MMM d, y, H:mm", "defaultDateTimeFormat": "MMM d, y, H:mm",
"defaultLocale": "en" "defaultLocale": "en"
}, },
"decimalValues": {
"minIntegerDigits": 1,
"minFractionDigits": 0,
"maxFractionDigits": 2
},
"files": { "files": {
"excluded": [ "excluded": [
".DS_Store", ".DS_Store",

View File

@@ -127,11 +127,11 @@ export const appRoutes: Routes = [
] ]
}, },
{ {
path: 'date', path: 'pipes',
children: [ children: [
{ {
path: '', path: '',
loadChildren: 'app/components/date/date.module#AppDateModule' loadChildren: 'app/components/pipes/pipes.module#AppPipesModule'
} }
] ]
}, },

View File

@@ -74,7 +74,7 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
{ href: '/webscript', icon: 'extension', title: 'APP_LAYOUT.WEBSCRIPT' }, { href: '/webscript', icon: 'extension', title: 'APP_LAYOUT.WEBSCRIPT' },
{ href: '/tag', icon: 'local_offer', title: 'APP_LAYOUT.TAG' }, { href: '/tag', icon: 'local_offer', title: 'APP_LAYOUT.TAG' },
{ href: '/social', icon: 'thumb_up', title: 'APP_LAYOUT.SOCIAL' }, { href: '/social', icon: 'thumb_up', title: 'APP_LAYOUT.SOCIAL' },
{ href: '/date', icon: 'calendar_today', title: 'APP_LAYOUT.DATE' }, { href: '/pipes', icon: 'layers', title: 'APP_LAYOUT.PIPES' },
{ href: '/settings-layout', icon: 'settings', title: 'APP_LAYOUT.SETTINGS' }, { href: '/settings-layout', icon: 'settings', title: 'APP_LAYOUT.SETTINGS' },
{ href: '/config-editor', icon: 'code', title: 'APP_LAYOUT.CONFIG-EDITOR' }, { href: '/config-editor', icon: 'code', title: 'APP_LAYOUT.CONFIG-EDITOR' },
{ href: '/extendedSearch', icon: 'search', title: 'APP_LAYOUT.SEARCH' }, { href: '/extendedSearch', icon: 'search', title: 'APP_LAYOUT.SEARCH' },

View File

@@ -27,7 +27,8 @@ import {
CardViewSelectItemModel, CardViewSelectItemModel,
CardViewUpdateService, CardViewUpdateService,
CardViewMapItemModel, CardViewMapItemModel,
UpdateNotification UpdateNotification,
DecimalNumberPipe
} from '@alfresco/adf-core'; } from '@alfresco/adf-core';
import { of, Subject } from 'rxjs'; import { of, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators'; import { takeUntil } from 'rxjs/operators';
@@ -46,7 +47,8 @@ export class CardViewComponent implements OnInit, OnDestroy {
private onDestroy$ = new Subject<boolean>(); private onDestroy$ = new Subject<boolean>();
constructor(private cardViewUpdateService: CardViewUpdateService) { constructor(private cardViewUpdateService: CardViewUpdateService,
private decimalNumberPipe: DecimalNumberPipe) {
this.logs = []; this.logs = [];
this.createCard(); this.createCard();
} }
@@ -112,7 +114,8 @@ export class CardViewComponent implements OnInit, OnDestroy {
value: 9.9, value: 9.9,
key: 'float', key: 'float',
default: 0.0, default: 0.0,
editable: this.isEditable editable: this.isEditable,
pipes: [{ pipe: this.decimalNumberPipe}]
}), }),
new CardViewKeyValuePairsItemModel({ new CardViewKeyValuePairsItemModel({
label: 'CardView Key-Value Pairs Item', label: 'CardView Key-Value Pairs Item',

View File

@@ -1,32 +0,0 @@
<div class="adf-date-pipes-container">
<h2>Date Pipes</h2>
<mat-form-field class="adf-date-field">
<input matInput
placeholder="Format"
[(ngModel)]="format">
</mat-form-field>
<mat-form-field class="adf-date-field">
<mat-select placeholder="Locale dropdown" [(ngModel)]="locale">
<mat-option *ngFor="let language of languages" [value]="language.key">
{{language.label}}
</mat-option>
</mat-select>
</mat-form-field>
<h3>AdfLocalizedDate Pipe - Default</h3>
<div>{{ today | adfLocalizedDate }} </div>
<br>
<h3>AdfLocalizedDate Pipe - Custom format</h3>
<div>{{ today | adfLocalizedDate : format }} </div>
<br>
<h3>AdfLocalizedDate Pipe - Custom format and locale</h3>
<div>{{ today | adfLocalizedDate : format : locale }} </div>
<br>
<h3>AdfTimeAgo Pipe</h3>
<div>{{ today | adfTimeAgo }} </div>
<br>
<h3>AdfTimeAgo Pipe - Custom locale</h3>
<div>{{ today | adfTimeAgo : locale}} </div>
</div>

View File

@@ -1,7 +0,0 @@
.adf-date-pipes-container {
padding: 20px;
}
.adf-date-field {
margin: 20px;
}

View File

@@ -0,0 +1,109 @@
<h2>ADF Pipes</h2>
<mat-accordion>
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-panel-title>
Localized dates
</mat-panel-title>
<mat-panel-description>
adfLocalizedDate
</mat-panel-description>
</mat-expansion-panel-header>
<mat-form-field class="adf-input-field">
<input matInput placeholder="Format" [(ngModel)]="format">
</mat-form-field>
<mat-form-field class="adf-input-field">
<mat-select placeholder="Locale dropdown" [(ngModel)]="locale">
<mat-option *ngFor="let language of languages" [value]="language.key">
{{language.label}}
</mat-option>
</mat-select>
</mat-form-field>
<h3>AdfLocalizedDate Pipe - Default</h3>
<div>{{ today | adfLocalizedDate }} </div>
<br>
<h3>AdfLocalizedDate Pipe - Custom format</h3>
<div>{{ today | adfLocalizedDate : format }} </div>
<br>
<h3>AdfLocalizedDate Pipe - Custom format and locale</h3>
<div>{{ today | adfLocalizedDate : format : locale }} </div>
</mat-expansion-panel>
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-panel-title>
Time ago
</mat-panel-title>
<mat-panel-description>
adfTimeAgo
</mat-panel-description>
</mat-expansion-panel-header>
<mat-form-field class="adf-input-field">
<input matInput placeholder="Format" [(ngModel)]="format">
</mat-form-field>
<mat-form-field class="adf-input-field">
<mat-select placeholder="Locale dropdown" [(ngModel)]="locale">
<mat-option *ngFor="let language of languages" [value]="language.key">
{{language.label}}
</mat-option>
</mat-select>
</mat-form-field>
<h3>AdfTimeAgo Pipe - Default</h3>
<div>{{ today | adfTimeAgo }} </div>
<br>
<h3>AdfTimeAgo Pipe - Custom locale</h3>
<div>{{ today | adfTimeAgo : locale}} </div>
</mat-expansion-panel>
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-panel-title>
Decimal numbers
</mat-panel-title>
<mat-panel-description>
adfDecimalNumber
</mat-panel-description>
</mat-expansion-panel-header>
<mat-form-field class="adf-input-field">
<input matInput placeholder="Number" [(ngModel)]="number">
</mat-form-field>
<mat-form-field class="adf-input-field">
<input matInput placeholder="Min Integer Digits" [(ngModel)]="decimalValues.minIntegerDigits">
</mat-form-field>
<mat-form-field class="adf-input-field">
<input matInput placeholder="Min Fraction Digits" [(ngModel)]="decimalValues.minFractionDigits">
</mat-form-field>
<mat-form-field class="adf-input-field">
<input matInput placeholder="Max Fraction Digits" [(ngModel)]="decimalValues.maxFractionDigits">
</mat-form-field>
<mat-form-field class="adf-input-field">
<mat-select placeholder="Locale dropdown" [(ngModel)]="locale">
<mat-option *ngFor="let language of languages" [value]="language.key">
{{language.label}}
</mat-option>
</mat-select>
</mat-form-field>
<h3>AdfDecimalNumber Pipe - Default</h3>
<div>{{ number | adfDecimalNumber }} </div>
<br>
<h3>AdfDecimalNumber Pipe - Custom digits config</h3>
<div>{{ number | adfDecimalNumber : decimalValues }} </div>
<br>
<h3>AdfDecimalNumber Pipe - Custom locale</h3>
<div>{{ number | adfDecimalNumber : {} : locale }} </div>
<br>
<h3>AdfDecimalNumber Pipe - Custom digits config and locale</h3>
<div>{{ number | adfDecimalNumber : decimalValues : locale }} </div>
<br>
</mat-expansion-panel>
</mat-accordion>

View File

@@ -0,0 +1,7 @@
h2 {
padding: 20px;
}
.adf-input-field {
margin: 20px;
}

View File

@@ -19,15 +19,21 @@ import { Component } from '@angular/core';
import { AppConfigService } from '@alfresco/adf-core'; import { AppConfigService } from '@alfresco/adf-core';
@Component({ @Component({
selector: 'app-date-page', selector: 'app-pipes-page',
templateUrl: './date.component.html', templateUrl: './pipes.component.html',
styleUrls: ['date.component.scss'] styleUrls: ['pipes.component.scss']
}) })
export class DateComponent { export class PipesComponent {
today = new Date(); today = new Date();
locale: string; locale: string;
format: string; format: string;
number = 12345.56;
decimalValues = {
minIntegerDigits: undefined,
minFractionDigits: undefined,
maxFractionDigits: undefined
};
languages: any[]; languages: any[];
constructor(private appConfig: AppConfigService) { constructor(private appConfig: AppConfigService) {

View File

@@ -17,14 +17,14 @@
import { NgModule } from '@angular/core'; import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router'; import { Routes, RouterModule } from '@angular/router';
import { DateComponent } from './date.component'; import { PipesComponent } from './pipes.component';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { CoreModule } from '@alfresco/adf-core'; import { CoreModule } from '@alfresco/adf-core';
const routes: Routes = [ const routes: Routes = [
{ {
path: '', path: '',
component: DateComponent component: PipesComponent
} }
]; ];
@@ -34,6 +34,6 @@ const routes: Routes = [
CoreModule.forChild(), CoreModule.forChild(),
RouterModule.forChild(routes) RouterModule.forChild(routes)
], ],
declarations: [DateComponent] declarations: [PipesComponent]
}) })
export class AppDateModule {} export class AppPipesModule {}

View File

@@ -0,0 +1,53 @@
# [Decimal Number Pipe](../../../lib/core/pipes/decimal-number.pipe.ts "Defined in multi-value.pipe.ts")
Transforms a number to have a certain amount of digits in its integer part and also in its decimal part.
## Basic Usage
### Properties
| Name | Type | Default value | Description |
| ---------- | ---------------------------------------------------------------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------- |
| digitsInfo | [DecimalNumberModel](../../../lib/core/models/decimal-number.model.ts) | | A format to apply to the date value. [Date Pipe Formats.](https://angular.io/api/common/DatePipe#custom-format-options) |
| locale | string | 'en-US' | A locale id for the locale format rules to use. |
## Details
This pipe transforms a given number so it follows the set configuration for the pipe. You can change this configuration by changing the parameters in your `app.config.json`.
```json
"decimalValues": {
"minIntegerDigits": 1,
"minFractionDigits": 0,
"maxFractionDigits": 2
}
```
You can also overwrite this config by passing a [DecimalNumberModel](../../../lib/core/models/decimal-number.model.ts) as an argument for this pipe.
The number can be also localized so it applies commas and dots in the right place depending on the locale id in use.
#### Result
```ts
decimalNumberPipe.transform(1234.567);
//Returns '1,234.57'
decimalNumberPipe.transform(1234.567, digitsConfig, "it");
//Returns '1.234,57'
```
And now with a different config:
```ts
digitsConfig = {
minIntegerDigits: 6,
minFractionDigits: 4,
maxFractionDigits: 4
};
decimalNumberPipe.transform(1234.567, digitsConfig);
//Returns '001,234.5670'
```
More info: [Angular DecimalPipe](https://angular.io/api/common/DecimalPipe)

View File

@@ -10,6 +10,7 @@ Dates are not written the same around the world. That is where localizing a date
- [Adding language support](#adding-language-support) - [Adding language support](#adding-language-support)
- [Using the localized date pipe](#using-the-localized-date-pipe) - [Using the localized date pipe](#using-the-localized-date-pipe)
- [Using the time ago pipe](#using-the-time-ago-pipe) - [Using the time ago pipe](#using-the-time-ago-pipe)
- [Using the decimal number pipe](#using-the-decimal-number-pipe)
## Setting up the configuration in your app ## Setting up the configuration in your app
@@ -71,4 +72,19 @@ Converts a recent past date into a number of days ago.
Usage of the [time ago pipe](../core/pipes/time-ago.pipe.md). Usage of the [time ago pipe](../core/pipes/time-ago.pipe.md).
## Using the decimal number pipe
Localizes the punctuation marks of a given number.
<!-- {% raw %} -->
{{ number | adfDecimalNumber }}
<!-- {% endraw %} -->
`Input:` 1999.12
`Output (english locale):` 1,999.12
`Output (italian locale):` 1.999,12
Usage of the [decimal number pipe](../core/pipes/decimal-number.pipe.md).
Find more info about localization in the [Angular Docs](https://angular.io/guide/i18n#setting-up-the-locale-of-your-app). Find more info about localization in the [Angular Docs](https://angular.io/guide/i18n#setting-up-the-locale-of-your-app).

View File

@@ -27,7 +27,8 @@ import {
CardViewFloatItemModel, CardViewFloatItemModel,
LogService, LogService,
MultiValuePipe, MultiValuePipe,
AppConfigService AppConfigService,
DecimalNumberPipe
} from '@alfresco/adf-core'; } from '@alfresco/adf-core';
import { Property, CardViewGroup, OrganisedPropertyGroup } from '../interfaces/content-metadata.interfaces'; import { Property, CardViewGroup, OrganisedPropertyGroup } from '../interfaces/content-metadata.interfaces';
@@ -52,6 +53,7 @@ export class PropertyGroupTranslatorService {
constructor(private logService: LogService, constructor(private logService: LogService,
private multiValuePipe: MultiValuePipe, private multiValuePipe: MultiValuePipe,
private decimalNumberPipe: DecimalNumberPipe,
private appConfig: AppConfigService) { private appConfig: AppConfigService) {
this.valueSeparator = this.appConfig.get<string>('content-metadata.multi-value-pipe-separator'); this.valueSeparator = this.appConfig.get<string>('content-metadata.multi-value-pipe-separator');
} }
@@ -104,7 +106,9 @@ export class PropertyGroupTranslatorService {
case D_FLOAT: case D_FLOAT:
case D_DOUBLE: case D_DOUBLE:
cardViewItemProperty = new CardViewFloatItemModel(propertyDefinition); cardViewItemProperty = new CardViewFloatItemModel(Object.assign(propertyDefinition, {
pipes: [{ pipe: this.decimalNumberPipe }]
}));
break; break;
case D_DATE: case D_DATE:

View File

@@ -541,6 +541,29 @@
} }
} }
}, },
"decimalValues": {
"description": "Configuration of date formats in the app",
"type": "object",
"required": [
"minIntegerDigits",
"minFractionDigits",
"maxFractionDigits"
],
"properties": {
"minIntegerDigits": {
"description": "Minimum integer digits in number",
"type": "number"
},
"minFractionDigits": {
"description": "Minimum decimal digits in number",
"type": "number"
},
"maxFractionDigits": {
"description": "Maximum decimal digits in number",
"type": "number"
}
}
},
"files": { "files": {
"description": "Configuration of rules applied to file upload", "description": "Configuration of rules applied to file upload",
"type": "object", "type": "object",

View File

@@ -19,7 +19,7 @@ import { CardViewItem } from '../interfaces/card-view-item.interface';
import { DynamicComponentModel } from '../../services/dynamic-component-mapper.service'; import { DynamicComponentModel } from '../../services/dynamic-component-mapper.service';
import { CardViewTextItemModel } from './card-view-textitem.model'; import { CardViewTextItemModel } from './card-view-textitem.model';
import { CardViewTextItemProperties } from '../interfaces/card-view.interfaces'; import { CardViewTextItemProperties } from '../interfaces/card-view.interfaces';
import { CardViewItemFloatValidator } from '..//validators/card-view.validators'; import { CardViewItemFloatValidator } from '../validators/card-view.validators';
export class CardViewFloatItemModel extends CardViewTextItemModel implements CardViewItem, DynamicComponentModel { export class CardViewFloatItemModel extends CardViewTextItemModel implements CardViewItem, DynamicComponentModel {
type: string = 'float'; type: string = 'float';

View File

@@ -8,7 +8,7 @@
pattern="-?[0-9]*(\.[0-9]+)?" pattern="-?[0-9]*(\.[0-9]+)?"
[id]="field.id" [id]="field.id"
[required]="isRequired()" [required]="isRequired()"
[value]="field.value" [value]="displayValue"
[(ngModel)]="field.value" [(ngModel)]="field.value"
(ngModelChange)="onFieldChanged(field)" (ngModelChange)="onFieldChanged(field)"
[disabled]="field.readOnly" [disabled]="field.readOnly"

View File

@@ -22,7 +22,7 @@ describe('NumberWidgetComponent', () => {
let widget: NumberWidgetComponent; let widget: NumberWidgetComponent;
beforeEach(() => { beforeEach(() => {
widget = new NumberWidgetComponent(null); widget = new NumberWidgetComponent(null, null);
}); });
it('should exist', () => { it('should exist', () => {

View File

@@ -17,9 +17,10 @@
/* tslint:disable:component-selector no-input-rename */ /* tslint:disable:component-selector no-input-rename */
import { Component, ViewEncapsulation } from '@angular/core'; import { Component, ViewEncapsulation, OnInit } from '@angular/core';
import { FormService } from './../../../services/form.service'; import { FormService } from './../../../services/form.service';
import { baseHost , WidgetComponent } from './../widget.component'; import { baseHost , WidgetComponent } from './../widget.component';
import { DecimalNumberPipe } from '../../../../pipes/decimal-number.pipe';
@Component({ @Component({
selector: 'number-widget', selector: 'number-widget',
@@ -28,10 +29,21 @@ import { baseHost , WidgetComponent } from './../widget.component';
host: baseHost, host: baseHost,
encapsulation: ViewEncapsulation.None encapsulation: ViewEncapsulation.None
}) })
export class NumberWidgetComponent extends WidgetComponent { export class NumberWidgetComponent extends WidgetComponent implements OnInit {
constructor(public formService: FormService) { displayValue: number;
constructor(public formService: FormService,
private decimalNumberPipe: DecimalNumberPipe) {
super(formService); super(formService);
} }
ngOnInit() {
if (this.field.readOnly) {
this.displayValue = this.decimalNumberPipe.transform(this.field.value);
} else {
this.displayValue = this.field.value;
}
}
} }

View File

@@ -0,0 +1,30 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export class DecimalNumberModel {
minIntegerDigits: number;
minFractionDigits: number;
maxFractionDigits: number;
constructor(obj?: any) {
if (obj) {
this.minIntegerDigits = obj.minIntegerDigits;
this.minFractionDigits = obj.minFractionDigits;
this.maxFractionDigits = obj.maxFractionDigits;
}
}
}

View File

@@ -27,3 +27,4 @@ export * from './pagination.model';
export * from './oauth-config.model'; export * from './oauth-config.model';
export * from './request-pagination.model'; export * from './request-pagination.model';
export * from './notification.model'; export * from './notification.model';
export * from './decimal-number.model';

View File

@@ -0,0 +1,74 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { async, TestBed } from '@angular/core/testing';
import { AppConfigService } from '../app-config/app-config.service';
import { UserPreferencesService } from '../services/user-preferences.service';
import { of } from 'rxjs';
import { setupTestBed } from '../testing/setupTestBed';
import { CoreTestingModule } from '../testing/core.testing.module';
import { DecimalNumberPipe } from './decimal-number.pipe';
describe('DecimalNumberPipe', () => {
let pipe: DecimalNumberPipe;
let userPreferences: UserPreferencesService;
setupTestBed({
imports: [CoreTestingModule]
});
beforeEach(async(() => {
userPreferences = TestBed.get(UserPreferencesService);
spyOn(userPreferences, 'select').and.returnValue(of(''));
pipe = new DecimalNumberPipe(userPreferences, new AppConfigService(null));
}));
it('should return number localized and rounded following the default config', () => {
expect(pipe.transform(1234.567)).toBe('1,234.57');
});
it('should return number with at least the minimum of digints in the integer part', () => {
const decimalValues = {
minIntegerDigits: 6,
minFractionDigits: undefined,
maxFractionDigits: undefined
};
expect(pipe.transform(1234.567, decimalValues)).toBe('001,234.57');
});
it('should return number with at least the minimum of digints in the integer part', () => {
const decimalValues = {
minIntegerDigits: undefined,
minFractionDigits: 4,
maxFractionDigits: 10
};
expect(pipe.transform(1234.567, decimalValues)).toBe('1,234.5670');
});
it('should return number with at least the minimum of digints in the integer part', () => {
const decimalValues = {
minIntegerDigits: undefined,
minFractionDigits: 0,
maxFractionDigits: 1
};
expect(pipe.transform(1234.567, decimalValues)).toBe('1,234.6');
});
});

View File

@@ -0,0 +1,82 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { DecimalPipe } from '@angular/common';
import { Pipe, PipeTransform, OnDestroy } from '@angular/core';
import { AppConfigService } from '../app-config/app-config.service';
import { UserPreferencesService, UserPreferenceValues } from '../services/user-preferences.service';
import { DecimalNumberModel } from '../models/decimal-number.model';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Pipe({
name: 'adfDecimalNumber',
pure: false
})
export class DecimalNumberPipe implements PipeTransform, OnDestroy {
static DEFAULT_LOCALE = 'en-US';
static DEFAULT_MIN_INTEGER_DIGITS = 1;
static DEFAULT_MIN_FRACTION_DIGITS = 0;
static DEFAULT_MAX_FRACTION_DIGITS = 2;
defaultLocale: string = DecimalNumberPipe.DEFAULT_LOCALE;
defaultMinIntegerDigits: number = DecimalNumberPipe.DEFAULT_MIN_INTEGER_DIGITS;
defaultMinFractionDigits: number = DecimalNumberPipe.DEFAULT_MIN_FRACTION_DIGITS;
defaultMaxFractionDigits: number = DecimalNumberPipe.DEFAULT_MAX_FRACTION_DIGITS;
onDestroy$: Subject<boolean> = new Subject<boolean>();
constructor(public userPreferenceService?: UserPreferencesService,
public appConfig?: AppConfigService) {
if (this.userPreferenceService) {
this.userPreferenceService.select(UserPreferenceValues.Locale)
.pipe(
takeUntil(this.onDestroy$)
)
.subscribe((locale) => {
if (locale) {
this.defaultLocale = locale;
}
});
}
if (this.appConfig) {
this.defaultMinIntegerDigits = this.appConfig.get<number>('decimalValues.minIntegerDigits', DecimalNumberPipe.DEFAULT_MIN_INTEGER_DIGITS);
this.defaultMinFractionDigits = this.appConfig.get<number>('decimalValues.minFractionDigits', DecimalNumberPipe.DEFAULT_MIN_FRACTION_DIGITS);
this.defaultMaxFractionDigits = this.appConfig.get<number>('decimalValues.maxFractionDigits', DecimalNumberPipe.DEFAULT_MAX_FRACTION_DIGITS);
}
}
transform(value: any, digitsInfo?: DecimalNumberModel, locale?: string): any {
const actualMinIntegerDigits: number = digitsInfo && digitsInfo.minIntegerDigits ? digitsInfo.minIntegerDigits : this.defaultMinIntegerDigits;
const actualMinFractionDigits: number = digitsInfo && digitsInfo.minFractionDigits ? digitsInfo.minFractionDigits : this.defaultMinFractionDigits;
const actualMaxFractionDigits: number = digitsInfo && digitsInfo.maxFractionDigits ? digitsInfo.maxFractionDigits : this.defaultMaxFractionDigits;
const actualDigitsInfo = `${actualMinIntegerDigits}.${actualMinFractionDigits}-${actualMaxFractionDigits}`;
const actualLocale = locale || this.defaultLocale;
const datePipe: DecimalPipe = new DecimalPipe(actualLocale);
return datePipe.transform(value, actualDigitsInfo);
}
ngOnDestroy(): void {
this.onDestroy$.next(true);
this.onDestroy$.complete();
}
}

View File

@@ -29,6 +29,7 @@ import { FormatSpacePipe } from './format-space.pipe';
import { FileTypePipe } from './file-type.pipe'; import { FileTypePipe } from './file-type.pipe';
import { MultiValuePipe } from './multi-value.pipe'; import { MultiValuePipe } from './multi-value.pipe';
import { LocalizedDatePipe } from './localized-date.pipe'; import { LocalizedDatePipe } from './localized-date.pipe';
import { DecimalNumberPipe } from './decimal-number.pipe';
@NgModule({ @NgModule({
imports: [ imports: [
@@ -45,7 +46,8 @@ import { LocalizedDatePipe } from './localized-date.pipe';
FormatSpacePipe, FormatSpacePipe,
FileTypePipe, FileTypePipe,
MultiValuePipe, MultiValuePipe,
LocalizedDatePipe LocalizedDatePipe,
DecimalNumberPipe
], ],
providers: [ providers: [
FileSizePipe, FileSizePipe,
@@ -57,7 +59,8 @@ import { LocalizedDatePipe } from './localized-date.pipe';
FormatSpacePipe, FormatSpacePipe,
FileTypePipe, FileTypePipe,
MultiValuePipe, MultiValuePipe,
LocalizedDatePipe LocalizedDatePipe,
DecimalNumberPipe
], ],
exports: [ exports: [
FileSizePipe, FileSizePipe,
@@ -70,7 +73,8 @@ import { LocalizedDatePipe } from './localized-date.pipe';
FormatSpacePipe, FormatSpacePipe,
FileTypePipe, FileTypePipe,
MultiValuePipe, MultiValuePipe,
LocalizedDatePipe LocalizedDatePipe,
DecimalNumberPipe
] ]
}) })
export class PipeModule { export class PipeModule {

View File

@@ -24,5 +24,6 @@ export * from './user-initial.pipe';
export * from './full-name.pipe'; export * from './full-name.pipe';
export * from './multi-value.pipe'; export * from './multi-value.pipe';
export * from './localized-date.pipe'; export * from './localized-date.pipe';
export * from './decimal-number.pipe';
export * from './pipe.module'; export * from './pipe.module';