-
Notifications
You must be signed in to change notification settings - Fork 21
/
obs-autocomplete-base.ts
174 lines (149 loc) · 5.36 KB
/
obs-autocomplete-base.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
// Base class with which to create an observable auto complete. This doesn't
// have any connection to how the result is rendered in the Dom, with what
// component set, and so on.
import { Input, OnDestroy } from '@angular/core';
import { FormControl, ControlValueAccessor } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { of } from 'rxjs/observable/of';
import { timer } from 'rxjs/observable/timer';
import { combineLatest } from 'rxjs/observable/combineLatest';
import { switchMap, startWith, catchError, map, filter, debounce, take, refCount, withLatestFrom } from 'rxjs/operators';
import { Subject } from 'rxjs/Subject';
import { publishReplay } from 'rxjs/operators/publishReplay';
import { distinctUntilChanged } from 'rxjs/operators/distinctUntilChanged';
import { OptionEntry, DataSource } from './types';
interface SearchResult {
search: string;
list?: OptionEntry[];
errorMessage?: string;
}
export class ObsAutocompleteBase implements ControlValueAccessor, OnDestroy {
@Input() debounceTime = 75;
@Input() set dataSource(ds: DataSource) { this.incomingDataSources.next(ds); }
// API provided to client component (for use in its template)
searchControl = new FormControl();
loading: Observable<boolean>;
list: Observable<OptionEntry[] | undefined>;
empty: Observable<boolean>;
errorMessage: Observable<string | undefined>;
focus() {
this.selectedValueSub = this.selectedValue.subscribe(this.checkAndPropagate.bind(this));
}
blur() {
this.onTouched();
if (this.selectedValueSub) {
this.selectedValueSub.unsubscribe();
}
setTimeout(() =>
this.selectedValue.pipe(take(1)).subscribe(this.checkAndPropagate.bind(this)));
}
displayWith(value: OptionEntry): string {
return value ? value.display : '';
}
// ---------------------------------------------------------------------
// Internals
// tslint:disable:member-ordering
private incomingValues = new Subject<any>();
private incomingDataSources = new BehaviorSubject<DataSource>({
displayValue: of,
search: () => of([])
});
private incomingDataSourcesSub: Subscription;
private outsideValue: any;
private selectedValueSub: Subscription;
private selectedValue: Observable<any>;
constructor() {
const searches: Observable<OptionEntry | string | null> =
this.searchControl.valueChanges.pipe(
startWith(this.searchControl.value),
distinctUntilChanged(),
debounce(_x => timer(this.debounceTime))
);
const options: Observable<SearchResult> = combineLatest(
searches,
this.incomingDataSources.pipe(filter(ds => !!ds)),
).pipe(
switchMap(([srch, ds]) => {
// Initial value is sometimes null
if (srch === null) {
srch = '';
}
if (typeof srch === 'string') {
const search: string = srch;
// Typing into input sends simple strings,
return ds.search(srch).pipe(
map(list => ({ search, list })),
catchError(errorMessage => of({ search, errorMessage })),
startWith({ search })
);
}
// selecting from Material Option list provides objects, so there is
// no need to call function to search for it.
const entry = srch as OptionEntry;
return of<SearchResult>({
search: srch.display,
list: [{ ...entry }]
});
}),
publishReplay(1),
refCount()
);
this.selectedValue = options.pipe(
filter(result => !!result.list),
map(result => {
const list = result.list || []; // appease TS
const entry = list.find(option => option.display === result.search);
return entry && entry.value || null;
}),
distinctUntilChanged()
);
this.loading = options.pipe(map(o => !o.list && !o.errorMessage));
this.list = options.pipe(map(o => o.list));
this.empty = options.pipe(map(o => o.list ? o.list.length === 0 : false));
this.errorMessage = options.pipe(map(o => o.errorMessage));
// a value is provided from outside; request the full entry
this.incomingDataSourcesSub = this.incomingValues
.pipe(
withLatestFrom(this.incomingDataSources),
switchMap<[any, DataSource], OptionEntry>(([value, ds]) => ds.displayValue(value))
)
.subscribe(value => this.searchControl.setValue(value));
}
// Implement ControlValueAccessor
writeValue(obj: any): void {
// Angular sometimes writes a value that didn't really change.
if (obj !== this.outsideValue) {
this.outsideValue = obj;
this.incomingValues.next(obj);
}
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
if (isDisabled) {
this.searchControl.disable();
} else {
this.searchControl.enable();
}
}
ngOnDestroy(): void {
if (this.incomingDataSourcesSub) {
this.incomingDataSourcesSub.unsubscribe();
}
}
private onChange = (_: any) => { };
private onTouched = () => { };
private checkAndPropagate(value: any) {
// Only send a change if there really is one.
if (value !== this.outsideValue) {
this.outsideValue = value;
this.onChange(value);
}
}
}