UNPKG

2.93 kBPlain TextView Raw
1// *****************************************************************************
2// Copyright (C) 2018 TypeFox and others.
3//
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License v. 2.0 which is available at
6// http://www.eclipse.org/legal/epl-2.0.
7//
8// This Source Code may also be made available under the following Secondary
9// Licenses when the conditions for such availability set forth in the Eclipse
10// Public License v. 2.0 are satisfied: GNU General Public License, version 2
11// with the GNU Classpath Exception which is available at
12// https://www.gnu.org/software/classpath/license.html.
13//
14// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
15// *****************************************************************************
16
17import { Event, Emitter } from '../../common/event';
18import { Disposable, DisposableCollection } from '../../common/disposable';
19
20import debounce = require('lodash.debounce');
21
22/**
23 * Options for the search term debounce.
24 */
25export interface SearchBoxDebounceOptions {
26
27 /**
28 * The delay (in milliseconds) before the debounce notifies clients about its content change.
29 */
30 readonly delay: number;
31
32}
33
34export namespace SearchBoxDebounceOptions {
35
36 /**
37 * The default debounce option.
38 */
39 export const DEFAULT: SearchBoxDebounceOptions = {
40 delay: 200
41 };
42
43}
44
45/**
46 * It notifies the clients, once if the underlying search term has changed after a given amount of delay.
47 */
48export 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}