1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | import { Event, Emitter } from '../../common/event';
|
18 | import { Disposable, DisposableCollection } from '../../common/disposable';
|
19 |
|
20 | import debounce = require('lodash.debounce');
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | export interface SearchBoxDebounceOptions {
|
26 |
|
27 | |
28 |
|
29 |
|
30 | readonly delay: number;
|
31 |
|
32 | }
|
33 |
|
34 | export namespace SearchBoxDebounceOptions {
|
35 |
|
36 | |
37 |
|
38 |
|
39 | export const DEFAULT: SearchBoxDebounceOptions = {
|
40 | delay: 200
|
41 | };
|
42 |
|
43 | }
|
44 |
|
45 |
|
46 |
|
47 |
|
48 | export class SearchBoxDebounce implements Disposable {
|
49 |
|
50 | protected readonly disposables = new DisposableCollection();
|
51 | protected readonly emitter = new Emitter<string | undefined>();
|
52 | protected readonly handler: () => void;
|
53 |
|
54 | protected state: string | undefined;
|
55 |
|
56 | constructor(protected readonly options: SearchBoxDebounceOptions) {
|
57 | this.disposables.push(this.emitter);
|
58 | this.handler = debounce(() => this.fireChanged(this.state), this.options.delay).bind(this);
|
59 | }
|
60 |
|
61 | append(input: string | undefined): string | undefined {
|
62 | if (input === undefined) {
|
63 | this.reset();
|
64 | return undefined;
|
65 | }
|
66 | if (this.state === undefined) {
|
67 | this.state = input;
|
68 | } else {
|
69 | if (input === '\b') {
|
70 | this.state = this.state.length === 1 ? '' : this.state.substr(0, this.state.length - 1);
|
71 | } else {
|
72 | this.state += input;
|
73 | }
|
74 | }
|
75 | this.handler();
|
76 | return this.state;
|
77 | }
|
78 |
|
79 | get onChanged(): Event<string | undefined> {
|
80 | return this.emitter.event;
|
81 | }
|
82 |
|
83 | dispose(): void {
|
84 | this.disposables.dispose();
|
85 | }
|
86 |
|
87 | protected fireChanged(value: string | undefined): void {
|
88 | this.emitter.fire(value);
|
89 | }
|
90 |
|
91 | protected reset(): void {
|
92 | this.state = undefined;
|
93 | this.fireChanged(undefined);
|
94 | }
|
95 |
|
96 | }
|