Skip to content

Commit aa6176f

Browse files
authored
Add debounce to search box (#513)
* refactor: wip * feat: add debounce to output * refactor: addressing review comments * refactor: fix lint
1 parent c5ae452 commit aa6176f

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

projects/components/src/search-box/search-box.component.ts

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
1-
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
1+
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnChanges, Output } from '@angular/core';
22
import { IconType } from '@hypertrace/assets-library';
3+
import { SubscriptionLifecycle, TypedSimpleChanges } from '@hypertrace/common';
4+
import { Subject } from 'rxjs';
5+
import { debounceTime } from 'rxjs/operators';
36
import { IconSize } from '../icon/icon-size';
47

58
@Component({
69
selector: 'ht-search-box',
710
styleUrls: ['./search-box.component.scss'],
811
changeDetection: ChangeDetectionStrategy.OnPush,
12+
providers: [SubscriptionLifecycle],
913
template: `
1014
<div class="ht-search-box" [class.focused]="this.isFocused">
1115
<ht-icon icon="${IconType.Search}" size="${IconSize.Medium}" class="icon" (click)="onSubmit()"></ht-icon>
@@ -29,28 +33,45 @@ import { IconSize } from '../icon/icon-size';
2933
</div>
3034
`
3135
})
32-
export class SearchBoxComponent {
36+
export class SearchBoxComponent implements OnChanges {
3337
@Input()
3438
public placeholder: string = 'Search';
3539

3640
@Input()
3741
public value: string = '';
3842

43+
@Input()
44+
public debounceTime: number = 0;
45+
3946
@Output()
4047
public readonly valueChange: EventEmitter<string> = new EventEmitter();
4148

4249
@Output()
4350
// tslint:disable-next-line:no-output-native
4451
public readonly submit: EventEmitter<string> = new EventEmitter();
4552

53+
public constructor(private readonly subscriptionLifecycle: SubscriptionLifecycle) {}
54+
4655
public isFocused: boolean = false;
56+
private readonly debouncedValueSubject: Subject<string> = new Subject();
57+
58+
public ngOnChanges(changes: TypedSimpleChanges<this>): void {
59+
if (changes.debounceTime) {
60+
this.subscriptionLifecycle.unsubscribe();
61+
this.subscriptionLifecycle.add(
62+
this.debouncedValueSubject
63+
.pipe(debounceTime(this.debounceTime))
64+
.subscribe(value => this.valueChange.emit(value))
65+
);
66+
}
67+
}
4768

4869
public onSubmit(): void {
4970
this.submit.emit(this.value);
5071
}
5172

5273
public onValueChange(): void {
53-
this.valueChange.emit(this.value);
74+
this.debouncedValueSubject.next(this.value);
5475
}
5576

5677
public clearValue(): void {

0 commit comments

Comments
 (0)