/
typeahead.ts
407 lines (353 loc) · 13.3 KB
/
typeahead.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import {
ChangeDetectorRef,
ComponentFactoryResolver,
ComponentRef,
Directive,
ElementRef,
EventEmitter,
forwardRef,
Inject,
Injector,
Input,
NgZone,
OnDestroy,
OnInit,
Output,
Renderer2,
TemplateRef,
ViewContainerRef,
ApplicationRef
} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {DOCUMENT} from '@angular/common';
import {BehaviorSubject, fromEvent, Observable, Subject, Subscription} from 'rxjs';
import {map, switchMap, tap} from 'rxjs/operators';
import {Live} from '../util/accessibility/live';
import {ngbAutoClose} from '../util/autoclose';
import {Key} from '../util/key';
import {PopupService} from '../util/popup';
import {PlacementArray, positionElements} from '../util/positioning';
import {isDefined, toString} from '../util/util';
import {NgbTypeaheadConfig} from './typeahead-config';
import {NgbTypeaheadWindow, ResultTemplateContext} from './typeahead-window';
const NGB_TYPEAHEAD_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NgbTypeahead),
multi: true
};
/**
* An event emitted right before an item is selected from the result list.
*/
export interface NgbTypeaheadSelectItemEvent {
/**
* The item from the result list about to be selected.
*/
item: any;
/**
* Calling this function will prevent item selection from happening.
*/
preventDefault: () => void;
}
let nextWindowId = 0;
/**
* A directive providing a simple way of creating powerful typeaheads from any text input.
*/
@Directive({
selector: 'input[ngbTypeahead]',
exportAs: 'ngbTypeahead',
host: {
'(blur)': 'handleBlur()',
'[class.open]': 'isPopupOpen()',
'(keydown)': 'handleKeyDown($event)',
'[autocomplete]': 'autocomplete',
'autocapitalize': 'off',
'autocorrect': 'off',
'role': 'combobox',
'aria-multiline': 'false',
'[attr.aria-autocomplete]': 'showHint ? "both" : "list"',
'[attr.aria-activedescendant]': 'activeDescendant',
'[attr.aria-owns]': 'isPopupOpen() ? popupId : null',
'[attr.aria-expanded]': 'isPopupOpen()'
},
providers: [NGB_TYPEAHEAD_VALUE_ACCESSOR]
})
export class NgbTypeahead implements ControlValueAccessor,
OnInit, OnDestroy {
private _popupService: PopupService<NgbTypeaheadWindow>;
private _subscription: Subscription;
private _closed$ = new Subject();
private _inputValueBackup: string;
private _valueChanges: Observable<string>;
private _resubscribeTypeahead: BehaviorSubject<any>;
private _windowRef: ComponentRef<NgbTypeaheadWindow>;
private _zoneSubscription: any;
/**
* The value for the `autocomplete` attribute for the `<input>` element.
*
* Defaults to `"off"` to disable the native browser autocomplete, but you can override it if necessary.
*
* @since 2.1.0
*/
@Input() autocomplete = 'off';
/**
* A selector specifying the element the typeahead popup will be appended to.
*
* Currently only supports `"body"`.
*/
@Input() container: string;
/**
* If `true`, model values will not be restricted only to items selected from the popup.
*/
@Input() editable: boolean;
/**
* If `true`, the first item in the result list will always stay focused while typing.
*/
@Input() focusFirst: boolean;
/**
* The function that converts an item from the result list to a `string` to display in the `<input>` field.
*
* It is called when the user selects something in the popup or the model value changes, so the input needs to
* be updated.
*/
@Input() inputFormatter: (item: any) => string;
/**
* The function that converts a stream of text values from the `<input>` element to the stream of the array of items
* to display in the typeahead popup.
*
* If the resulting observable emits a non-empty array - the popup will be shown. If it emits an empty array - the
* popup will be closed.
*
* See the [basic example](#/components/typeahead/examples#basic) for more details.
*
* Note that the `this` argument is `undefined` so you need to explicitly bind it to a desired "this" target.
*/
@Input() ngbTypeahead: (text: Observable<string>) => Observable<any[]>;
/**
* The function that converts an item from the result list to a `string` to display in the popup.
*
* Must be provided, if your `ngbTypeahead` returns something other than `Observable<string[]>`.
*
* Alternatively for more complex markup in the popup you should use `resultTemplate`.
*/
@Input() resultFormatter: (item: any) => string;
/**
* The template to override the way resulting items are displayed in the popup.
*
* See the [ResultTemplateContext](#/components/typeahead/api#ResultTemplateContext) for the template context.
*
* Also see the [template for results demo](#/components/typeahead/examples#template) for more details.
*/
@Input() resultTemplate: TemplateRef<ResultTemplateContext>;
/**
* If `true`, will show the hint in the `<input>` when an item in the result list matches.
*/
@Input() showHint: boolean;
/**
* The preferred placement of the typeahead.
*
* Possible values are `"top"`, `"top-left"`, `"top-right"`, `"bottom"`, `"bottom-left"`,
* `"bottom-right"`, `"left"`, `"left-top"`, `"left-bottom"`, `"right"`, `"right-top"`,
* `"right-bottom"`
*
* Accepts an array of strings or a string with space separated possible values.
*
* The default order of preference is `"bottom-left bottom-right top-left top-right"`
*
* Please see the [positioning overview](#/positioning) for more details.
*/
@Input() placement: PlacementArray = 'bottom-left';
/**
* An event emitted right before an item is selected from the result list.
*
* Event payload is of type [`NgbTypeaheadSelectItemEvent`](#/components/typeahead/api#NgbTypeaheadSelectItemEvent).
*/
@Output() selectItem = new EventEmitter<NgbTypeaheadSelectItemEvent>();
activeDescendant: string;
popupId = `ngb-typeahead-${nextWindowId++}`;
private _onTouched = () => {};
private _onChange = (_: any) => {};
constructor(
private _elementRef: ElementRef<HTMLInputElement>, private _viewContainerRef: ViewContainerRef,
private _renderer: Renderer2, private _injector: Injector, componentFactoryResolver: ComponentFactoryResolver,
config: NgbTypeaheadConfig, ngZone: NgZone, private _live: Live, @Inject(DOCUMENT) private _document: any,
private _ngZone: NgZone, private _changeDetector: ChangeDetectorRef, private _applicationRef: ApplicationRef) {
this.container = config.container;
this.editable = config.editable;
this.focusFirst = config.focusFirst;
this.showHint = config.showHint;
this.placement = config.placement;
this._valueChanges = fromEvent<Event>(_elementRef.nativeElement, 'input')
.pipe(map($event => ($event.target as HTMLInputElement).value));
this._resubscribeTypeahead = new BehaviorSubject(null);
this._popupService = new PopupService<NgbTypeaheadWindow>(
NgbTypeaheadWindow, _injector, _viewContainerRef, _renderer, componentFactoryResolver, _applicationRef);
this._zoneSubscription = ngZone.onStable.subscribe(() => {
if (this.isPopupOpen()) {
positionElements(
this._elementRef.nativeElement, this._windowRef.location.nativeElement, this.placement,
this.container === 'body');
}
});
}
ngOnInit(): void {
const inputValues$ = this._valueChanges.pipe(tap(value => {
this._inputValueBackup = this.showHint ? value : null;
this._onChange(this.editable ? value : undefined);
}));
const results$ = inputValues$.pipe(this.ngbTypeahead);
const userInput$ = this._resubscribeTypeahead.pipe(switchMap(() => results$));
this._subscription = this._subscribeToUserInput(userInput$);
}
ngOnDestroy(): void {
this._closePopup();
this._unsubscribeFromUserInput();
this._zoneSubscription.unsubscribe();
}
registerOnChange(fn: (value: any) => any): void { this._onChange = fn; }
registerOnTouched(fn: () => any): void { this._onTouched = fn; }
writeValue(value) {
this._writeInputValue(this._formatItemForInput(value));
if (this.showHint) {
this._inputValueBackup = value;
}
}
setDisabledState(isDisabled: boolean): void {
this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
}
/**
* Dismisses typeahead popup window
*/
dismissPopup() {
if (this.isPopupOpen()) {
this._resubscribeTypeahead.next(null);
this._closePopup();
if (this.showHint && this._inputValueBackup !== null) {
this._writeInputValue(this._inputValueBackup);
}
this._changeDetector.markForCheck();
}
}
/**
* Returns true if the typeahead popup window is displayed
*/
isPopupOpen() { return this._windowRef != null; }
handleBlur() {
this._resubscribeTypeahead.next(null);
this._onTouched();
}
handleKeyDown(event: KeyboardEvent) {
if (!this.isPopupOpen()) {
return;
}
// tslint:disable-next-line:deprecation
switch (event.which) {
case Key.ArrowDown:
event.preventDefault();
this._windowRef.instance.next();
this._showHint();
break;
case Key.ArrowUp:
event.preventDefault();
this._windowRef.instance.prev();
this._showHint();
break;
case Key.Enter:
case Key.Tab:
const result = this._windowRef.instance.getActive();
if (isDefined(result)) {
event.preventDefault();
event.stopPropagation();
this._selectResult(result);
}
this._closePopup();
break;
}
}
private _openPopup() {
if (!this.isPopupOpen()) {
this._inputValueBackup = this._elementRef.nativeElement.value;
this._windowRef = this._popupService.open();
this._windowRef.instance.id = this.popupId;
this._windowRef.instance.selectEvent.subscribe((result: any) => this._selectResultClosePopup(result));
this._windowRef.instance.activeChangeEvent.subscribe((activeId: string) => this.activeDescendant = activeId);
if (this.container === 'body') {
window.document.querySelector(this.container).appendChild(this._windowRef.location.nativeElement);
}
this._changeDetector.markForCheck();
ngbAutoClose(
this._ngZone, this._document, 'outside', () => this.dismissPopup(), this._closed$,
[this._elementRef.nativeElement, this._windowRef.location.nativeElement]);
}
}
private _closePopup() {
this._closed$.next();
this._popupService.close();
this._windowRef = null;
this.activeDescendant = undefined;
}
private _selectResult(result: any) {
let defaultPrevented = false;
this.selectItem.emit({item: result, preventDefault: () => { defaultPrevented = true; }});
this._resubscribeTypeahead.next(null);
if (!defaultPrevented) {
this.writeValue(result);
this._onChange(result);
}
}
private _selectResultClosePopup(result: any) {
this._selectResult(result);
this._closePopup();
}
private _showHint() {
if (this.showHint && this._windowRef.instance.hasActive() && this._inputValueBackup != null) {
const userInputLowerCase = this._inputValueBackup.toLowerCase();
const formattedVal = this._formatItemForInput(this._windowRef.instance.getActive());
if (userInputLowerCase === formattedVal.substr(0, this._inputValueBackup.length).toLowerCase()) {
this._writeInputValue(this._inputValueBackup + formattedVal.substr(this._inputValueBackup.length));
this._elementRef.nativeElement['setSelectionRange'].apply(
this._elementRef.nativeElement, [this._inputValueBackup.length, formattedVal.length]);
} else {
this._writeInputValue(formattedVal);
}
}
}
private _formatItemForInput(item: any): string {
return item != null && this.inputFormatter ? this.inputFormatter(item) : toString(item);
}
private _writeInputValue(value: string): void {
this._renderer.setProperty(this._elementRef.nativeElement, 'value', toString(value));
}
private _subscribeToUserInput(userInput$: Observable<any[]>): Subscription {
return userInput$.subscribe((results) => {
if (!results || results.length === 0) {
this._closePopup();
} else {
this._openPopup();
this._windowRef.instance.focusFirst = this.focusFirst;
this._windowRef.instance.results = results;
this._windowRef.instance.term = this._elementRef.nativeElement.value;
if (this.resultFormatter) {
this._windowRef.instance.formatter = this.resultFormatter;
}
if (this.resultTemplate) {
this._windowRef.instance.resultTemplate = this.resultTemplate;
}
this._windowRef.instance.resetActive();
// The observable stream we are subscribing to might have async steps
// and if a component containing typeahead is using the OnPush strategy
// the change detection turn wouldn't be invoked automatically.
this._windowRef.changeDetectorRef.detectChanges();
this._showHint();
}
// live announcer
const count = results ? results.length : 0;
this._live.say(count === 0 ? 'No results available' : `${count} result${count === 1 ? '' : 's'} available`);
});
}
private _unsubscribeFromUserInput() {
if (this._subscription) {
this._subscription.unsubscribe();
}
this._subscription = null;
}
}