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

perf(abc:auto-focus): perf code #1753

Merged
merged 2 commits into from
Jan 18, 2024
Merged
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
50 changes: 22 additions & 28 deletions packages/abc/auto-focus/auto-focus.directive.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,37 @@
import { Platform } from '@angular/cdk/platform';
import { AfterViewInit, ChangeDetectorRef, Directive, ElementRef, Input, OnDestroy } from '@angular/core';

import { BooleanInput, InputBoolean, InputNumber, NumberInput } from '@delon/util/decorator';
import type { NzSafeAny } from 'ng-zorro-antd/core/types';
import {
AfterViewInit,
DestroyRef,
Directive,
ElementRef,
Input,
booleanAttribute,
inject,
numberAttribute
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { timer } from 'rxjs';

@Directive({
selector: '[auto-focus], input[autofocus="autofocus"], textarea[autofocus="autofocus"]',
exportAs: 'autoFocus',
standalone: true
})
export class AutoFocusDirective implements AfterViewInit, OnDestroy {
static ngAcceptInputType_enabled: BooleanInput;
static ngAcceptInputType_delay: NumberInput;

private _focusoutTimeout: NzSafeAny;
@Input() @InputBoolean() enabled = true;
@Input() @InputNumber() delay = 300;
export class AutoFocusDirective implements AfterViewInit {
private readonly el = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
private readonly platform = inject(Platform);
private readonly d$ = inject(DestroyRef);

constructor(
private el: ElementRef<HTMLElement>,
private cdr: ChangeDetectorRef,
private platform: Platform
) {}
@Input({ transform: booleanAttribute }) enabled = true;
@Input({ transform: numberAttribute }) delay = 300;

ngAfterViewInit(): void {
const el = this.el.nativeElement;
const el = this.el;
if (!this.platform.isBrowser || !(el instanceof HTMLElement) || !this.enabled) {
return;
}
this._focusoutTimeout = setTimeout(() => {
el.focus({ preventScroll: false });
this.cdr.markForCheck();
}, this.delay);
}

ngOnDestroy(): void {
if (this._focusoutTimeout) {
clearTimeout(this._focusoutTimeout);
this._focusoutTimeout = null;
}
timer(this.delay)
.pipe(takeUntilDestroyed(this.d$))
.subscribe(() => el.focus({ preventScroll: false }));
}
}
Loading