Skip to content

Commit

Permalink
perf(*): use inject instead constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
cipchk committed Jan 18, 2024
1 parent 4e7f334 commit f0c5aee
Show file tree
Hide file tree
Showing 13 changed files with 129 additions and 178 deletions.
2 changes: 1 addition & 1 deletion packages/abc/auto-focus/auto-focus.directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { timer } from 'rxjs';
standalone: true
})
export class AutoFocusDirective implements AfterViewInit {
private readonly el = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
private readonly el: HTMLElement = inject(ElementRef).nativeElement;
private readonly platform = inject(Platform);
private readonly d$ = inject(DestroyRef);

Expand Down
26 changes: 11 additions & 15 deletions packages/abc/avatar-list/avatar-list.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import {
ContentChildren,
Input,
OnChanges,
Optional,
QueryList,
ViewEncapsulation
ViewEncapsulation,
inject,
numberAttribute
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';

import { InputNumber, NumberInput } from '@delon/util/decorator';
import { NzAvatarComponent } from 'ng-zorro-antd/avatar';
import type { NgStyleInterface, NzSizeLDSType } from 'ng-zorro-antd/core/types';
import { NzTooltipDirective } from 'ng-zorro-antd/tooltip';
Expand All @@ -36,16 +36,17 @@ import { AvatarListItemComponent } from './avatar-list-item.component';
imports: [NgStyle, NgClass, NzAvatarComponent, NzTooltipDirective]
})
export class AvatarListComponent implements AfterViewInit, OnChanges {
static ngAcceptInputType_maxLength: NumberInput;
private readonly cdr = inject(ChangeDetectorRef);
private readonly directionality = inject(Directionality, { optional: true });
private dir$ = this.directionality?.change?.pipe(takeUntilDestroyed());

private inited = false;
@ContentChildren(AvatarListItemComponent, { descendants: false })
private _items!: QueryList<AvatarListItemComponent>;
private dir$ = this.directionality.change?.pipe(takeUntilDestroyed());
private readonly _items!: QueryList<AvatarListItemComponent>;

items: AvatarListItemComponent[] = [];
exceedCount = 0;
dir: Direction = 'ltr';
dir?: Direction = 'ltr';

cls = '';
avatarSize: NzSizeLDSType = 'default';
Expand All @@ -63,14 +64,9 @@ export class AvatarListComponent implements AfterViewInit, OnChanges {
break;
}
}
@Input() @InputNumber() maxLength = 0;
@Input({ transform: numberAttribute }) maxLength = 0;
@Input() excessItemsStyle: NgStyleInterface | null = null;

constructor(
private cdr: ChangeDetectorRef,
@Optional() private directionality: Directionality
) {}

private gen(): void {
const { _items } = this;
const maxLength = this.maxLength > 0 ? this.maxLength : _items.length;
Expand All @@ -82,8 +78,8 @@ export class AvatarListComponent implements AfterViewInit, OnChanges {
}

ngAfterViewInit(): void {
this.dir = this.directionality.value;
this.dir$.subscribe((direction: Direction) => {
this.dir = this.directionality?.value;
this.dir$?.subscribe((direction: Direction) => {
this.dir = direction;
this.cdr.detectChanges();
});
Expand Down
10 changes: 4 additions & 6 deletions packages/abc/cell/cell-host.directive.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Directive, Input, OnInit, Type, ViewContainerRef } from '@angular/core';
import { Directive, Input, OnInit, Type, ViewContainerRef, inject } from '@angular/core';

import { warn } from '@delon/util/other';

Expand All @@ -10,12 +10,10 @@ import { CellWidgetData } from './cell.types';
standalone: true
})
export class CellHostDirective implements OnInit {
@Input() data!: CellWidgetData;
private readonly srv = inject(CellService);
private readonly viewContainerRef = inject(ViewContainerRef);

constructor(
private srv: CellService,
private viewContainerRef: ViewContainerRef
) {}
@Input() data!: CellWidgetData;

ngOnInit(): void {
const widget = this.data.options!.widget!;
Expand Down
36 changes: 15 additions & 21 deletions packages/abc/cell/cell.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,22 @@ import {
Component,
ElementRef,
EventEmitter,
Inject,
Input,
OnChanges,
OnDestroy,
Output,
Renderer2,
SimpleChange,
ViewEncapsulation
ViewEncapsulation,
booleanAttribute,
inject
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import type { SafeValue } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';

import { updateHostClass } from '@delon/util/browser';
import { BooleanInput, InputBoolean } from '@delon/util/decorator';
import { WINDOW } from '@delon/util/token';
import { NzBadgeComponent } from 'ng-zorro-antd/badge';
import { NzCheckboxComponent } from 'ng-zorro-antd/checkbox';
Expand Down Expand Up @@ -126,8 +126,13 @@ import type { CellDefaultText, CellOptions, CellTextResult, CellValue, CellWidge
]
})
export class CellComponent implements OnChanges, OnDestroy {
static ngAcceptInputType_loading: BooleanInput;
static ngAcceptInputType_disabled: BooleanInput;
private readonly srv = inject(CellService);
private readonly router = inject(Router);
private readonly cdr = inject(ChangeDetectorRef);
private readonly renderer = inject(Renderer2);
private readonly imgSrv = inject(NzImageService);
private readonly win = inject(WINDOW);
private readonly el: HTMLElement = inject(ElementRef).nativeElement;

private destroy$?: Subscription;

Expand All @@ -139,8 +144,8 @@ export class CellComponent implements OnChanges, OnDestroy {
@Input() value?: CellValue;
@Output() readonly valueChange = new EventEmitter<NzSafeAny>();
@Input() options?: CellOptions;
@Input() @InputBoolean() loading = false;
@Input() @InputBoolean() disabled = false;
@Input({ transform: booleanAttribute }) loading = false;
@Input({ transform: booleanAttribute }) disabled = false;

get safeOpt(): CellOptions {
return this.res?.options ?? {};
Expand All @@ -157,17 +162,6 @@ export class CellComponent implements OnChanges, OnDestroy {
};
}

constructor(
private srv: CellService,
private router: Router,
private cdr: ChangeDetectorRef,
private el: ElementRef<HTMLElement>,
private renderer: Renderer2,
private imgSrv: NzImageService,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@Inject(WINDOW) private win: any
) {}

private updateValue(): void {
this.destroy$?.unsubscribe();
this.destroy$ = this.srv.get(this.value, this.options).subscribe(res => {
Expand All @@ -183,15 +177,15 @@ export class CellComponent implements OnChanges, OnDestroy {
private setClass(): void {
const { el, renderer } = this;
const { renderType, size, type } = this.safeOpt;
updateHostClass(el.nativeElement, renderer, {
updateHostClass(el, renderer, {
[`cell`]: true,
[`cell__${renderType}`]: renderType != null,
[`cell__${size}`]: size != null,
[`cell__has-unit`]: this._unit,
[`cell__has-default`]: this.showDefault,
[`cell__disabled`]: this.disabled
});
el.nativeElement.setAttribute('data-type', `${type}`);
el.setAttribute('data-type', `${type}`);
}

ngOnChanges(changes: { [p in keyof CellComponent]?: SimpleChange }): void {
Expand Down Expand Up @@ -219,7 +213,7 @@ export class CellComponent implements OnChanges, OnDestroy {
if (url == null) return;

if (/https?:\/\//g.test(url)) {
(this.win as Window).open(url, link?.target);
this.win.open(url, link?.target);
} else {
this.router.navigateByUrl(url);
}
Expand Down
12 changes: 5 additions & 7 deletions packages/abc/cell/cell.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable, Type } from '@angular/core';
import { Injectable, Type, inject } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { map, Observable, of } from 'rxjs';

Expand All @@ -22,6 +22,9 @@ import type {

@Injectable({ providedIn: 'root' })
export class CellService {
private readonly nzI18n = inject(NzI18nService);
private readonly currency = inject(CurrencyService);
private readonly dom = inject(DomSanitizer);
private globalOptions!: AlainCellConfig;
private widgets: { [key: string]: CellWidget } = {
date: {
Expand Down Expand Up @@ -63,12 +66,7 @@ export class CellService {
}
};

constructor(
configSrv: AlainConfigService,
private nzI18n: NzI18nService,
private currency: CurrencyService,
private dom: DomSanitizer
) {
constructor(configSrv: AlainConfigService) {
this.globalOptions = configSrv.merge('cell', {
date: { format: 'yyyy-MM-dd HH:mm:ss' },
img: { size: 32 },
Expand Down
22 changes: 10 additions & 12 deletions packages/abc/date-picker/range.directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ import {
ComponentRef,
Directive,
EventEmitter,
Host,
Input,
OnDestroy,
Optional,
Output,
TemplateRef,
ViewContainerRef
ViewContainerRef,
inject
} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

Expand All @@ -30,6 +29,10 @@ import { RangePickerShortcutTplComponent } from './range-shortcut.component';
export class RangePickerDirective implements OnDestroy, AfterViewInit {
static ngAcceptInputType_shortcut: AlainDateRangePickerShortcut | string | null;

private readonly dom = inject(DomSanitizer);
private readonly vcr = inject(ViewContainerRef);
private readonly nativeComp = inject(NzRangePickerComponent, { host: true, optional: true });

private defaultShortcuts: AlainDateRangePickerShortcut;
private _shortcut: AlainDateRangePickerShortcut | null = null;
private shortcutFactory: ComponentRef<RangePickerShortcutTplComponent> | null = null;
Expand Down Expand Up @@ -60,22 +63,17 @@ export class RangePickerDirective implements OnDestroy, AfterViewInit {
@Output() readonly ngModelEndChange = new EventEmitter<NzSafeAny>();

private get dp(): NzDatePickerComponent {
return this.nativeComp.datePicker;
return this.nativeComp!.datePicker;
}

private get srv(): DatePickerService {
return this.dp.datePickerService;
}

constructor(
private dom: DomSanitizer,
configSrv: AlainConfigService,
@Host() @Optional() private nativeComp: NzRangePickerComponent,
private vcr: ViewContainerRef
) {
constructor(configSrv: AlainConfigService) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
assert(
!!nativeComp,
!!this.nativeComp,
`It should be attached to nz-range-picker component, for example: '<nz-range-picker [(ngModel)]="i.start" extend [(ngModelEnd)]="i.end" shortcut></nz-range-picker>'`
);
}
Expand Down Expand Up @@ -175,7 +173,7 @@ export class RangePickerDirective implements OnDestroy, AfterViewInit {
};
extraFooter = instance.tpl;
}
this.nativeComp.datePicker.extraFooter = extraFooter;
this.nativeComp!.datePicker.extraFooter = extraFooter;
Promise.resolve().then(() => this.cd());
}

Expand Down
26 changes: 12 additions & 14 deletions packages/abc/down-file/down-file.directive.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { HttpResponse } from '@angular/common/http';
import { Directive, ElementRef, EventEmitter, Input, Output } from '@angular/core';
import { Directive, ElementRef, EventEmitter, Input, Output, inject } from '@angular/core';
import { finalize } from 'rxjs';

import { saveAs } from 'file-saver';

import { _HttpClient } from '@delon/theme';
import type { NzSafeAny } from 'ng-zorro-antd/core/types';

let isFileSaverSupported = false;
try {
isFileSaverSupported = !!new Blob();
} catch {}

@Directive({
selector: '[down-file]',
exportAs: 'downFile',
Expand All @@ -16,7 +21,8 @@ import type { NzSafeAny } from 'ng-zorro-antd/core/types';
standalone: true
})
export class DownFileDirective {
private isFileSaverSupported = true;
private readonly el: HTMLButtonElement = inject(ElementRef).nativeElement;
private readonly _http = inject(_HttpClient);
@Input('http-data') httpData: NzSafeAny;
@Input('http-body') httpBody: NzSafeAny;
@Input('http-method') httpMethod: string = 'get';
Expand All @@ -40,28 +46,20 @@ export class DownFileDirective {
return arr.reduce((_o, item) => item, {});
}

constructor(
private el: ElementRef<HTMLButtonElement>,
private _http: _HttpClient
) {
let isFileSaverSupported = false;
try {
isFileSaverSupported = !!new Blob();
} catch {}
this.isFileSaverSupported = isFileSaverSupported;
constructor() {
if (!isFileSaverSupported) {
el.nativeElement.classList.add(`down-file__not-support`);
this.el.classList.add(`down-file__not-support`);
}
}

private setDisabled(status: boolean): void {
const el = this.el.nativeElement;
const el = this.el;
el.disabled = status;
el.classList[status ? 'add' : 'remove'](`down-file__disabled`);
}

async _click(ev: MouseEvent): Promise<void> {
if (!this.isFileSaverSupported || (typeof this.pre === 'function' && !(await this.pre(ev)))) {
if (!isFileSaverSupported || (typeof this.pre === 'function' && !(await this.pre(ev)))) {
ev.stopPropagation();
ev.preventDefault();
return;
Expand Down
Loading

0 comments on commit f0c5aee

Please sign in to comment.