-
Notifications
You must be signed in to change notification settings - Fork 222
/
Copy pathselect-base.ts
441 lines (351 loc) · 14.7 KB
/
select-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
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
import {
ViewChild, HostBinding, ElementRef, HostListener, Input, ContentChildren, QueryList,
AfterContentInit, TemplateRef, ViewContainerRef, ContentChild, EventEmitter, Output, OnDestroy, Renderer2
} from "@angular/core";
import { Subscription } from "rxjs/Subscription";
import { DropdownService, SuiDropdownMenu } from "../../dropdown/index";
import { SearchService, LookupFn, FilterFn } from "../../search/index";
import { Util, ITemplateRefContext, HandledEvent, KeyCode, IFocusEvent } from "../../../misc/util/index";
import { ISelectLocaleValues, RecursivePartial, SuiLocalizationService } from "../../../behaviors/localization/index";
import { SuiSelectOption } from "../components/select-option";
import { SuiSelectSearch } from "../directives/select-search";
export interface IOptionContext<T> extends ITemplateRefContext<T> {
query?:string;
}
// We use generic type T to specify the type of the options we are working with,
// and U to specify the type of the property of the option used as the value.
export abstract class SuiSelectBase<T, U> implements AfterContentInit, OnDestroy {
public dropdownService:DropdownService;
public searchService:SearchService<T, U>;
@ViewChild(SuiDropdownMenu)
protected _menu:SuiDropdownMenu;
// Keep track of all of the rendered select options. (Rendered by the user using *ngFor).
@ContentChildren(SuiSelectOption, { descendants: true })
protected _renderedOptions:QueryList<SuiSelectOption<T>>;
// Keep track of all of the subscriptions to the selected events on the rendered options.
private _renderedSubscriptions:Subscription[];
// Method used to compare the type of property of the option used as the value.
private _compareWith:(o1:U, o2:U) => boolean;
// Sets the Semantic UI classes on the host element.
@HostBinding("class.ui")
@HostBinding("class.dropdown")
private _selectClasses:boolean;
@HostBinding("class.active")
public get isActive():boolean {
return this.dropdownService.isOpen;
}
@HostBinding("class.visible")
public get isVisible():boolean {
return this._menu.isVisible;
}
@Input()
public isSearchable:boolean;
public isSearchExternal:boolean;
@HostBinding("class.search")
private get _searchClass():boolean {
return this.isSearchable && !this.isSearchExternal;
}
@HostBinding("class.loading")
public get isSearching():boolean {
return this.searchService.isSearching;
}
@ViewChild(SuiSelectSearch)
private _internalSearch?:SuiSelectSearch;
@ContentChild(SuiSelectSearch)
private _manualSearch?:SuiSelectSearch;
public get searchInput():SuiSelectSearch | undefined {
return this._manualSearch || this._internalSearch;
}
@Input("tabindex")
private _tabIndex?:number;
@HostBinding("attr.tabindex")
public get tabIndex():number {
if (this.isDisabled) {
// If disabled, remove from tabindex.
return -1;
}
if (this.dropdownService.isOpen && this.isSearchExternal) {
// If open & in menu search, remove from tabindex (as input always autofocusses).
return -1;
}
if (this._tabIndex != undefined) {
// If custom tabindex, default to that.
return this._tabIndex;
}
if (this._searchClass) {
// If search input enabled, tab goes to input.
return -1;
}
// Otherwise, return default of 0.
return 0;
}
@HostBinding("class.disabled")
@Input()
public get isDisabled():boolean {
return this.dropdownService.isDisabled;
}
public set isDisabled(value:boolean) {
this.dropdownService.isDisabled = !!value;
}
@Input()
public set options(options:T[]) {
if (options) {
this.searchService.options = options;
this.optionsUpdateHook();
}
}
@Input()
public set optionsFilter(filter:FilterFn<T> | undefined) {
if (filter) {
this.searchService.optionsFilter = filter;
this.optionsUpdateHook();
}
}
@Input()
public set optionsLookup(lookup:LookupFn<T, U> | undefined) {
if (lookup) {
this.searchService.optionsLookup = lookup;
this.optionsUpdateHook();
}
}
@Input()
public set compareWith(fn:(o1:U, o2:U) => boolean) {
if (fn) {
this._compareWith = fn;
}
}
public get filteredOptions():T[] {
return this.searchService.results;
}
// Deprecated
public get availableOptions():T[] {
return this.filteredOptions;
}
public get query():string | undefined {
return this.isSearchable ? this.searchService.query : undefined;
}
public set query(query:string | undefined) {
if (query != undefined) {
this.queryUpdateHook();
this.updateQuery(query);
// Update the rendered text as query has changed.
this._renderedOptions.forEach(ro => this.initialiseRenderedOption(ro));
if (this.searchInput) {
this.searchInput.query = query;
}
}
}
@Input()
public get labelField():string | undefined {
return this.searchService.optionsField;
}
public set labelField(field:string | undefined) {
this.searchService.optionsField = field;
}
public get labelGetter():(obj:T) => string {
// Helper function to retrieve the label from an item.
return (obj:T) => {
const label = Util.Object.readValue<T, string>(obj, this.labelField);
if (label != undefined) {
return label.toString();
}
return "";
};
}
@Input()
public valueField:string;
public get valueGetter():(obj:T) => U {
// Helper function to retrieve the value from an item.
return (obj:T) => Util.Object.readValue<T, U>(obj, this.valueField);
}
@Input()
public optionTemplate:TemplateRef<IOptionContext<T>>;
private _optionFormatter?:(o:T, q?:string) => string;
public get configuredFormatter():(option:T) => string {
if (this._optionFormatter) {
return o => this._optionFormatter!(o, this.isSearchable ? this.query : undefined);
} else if (this.searchService.optionsLookup) {
return o => this.labelGetter(o);
} else {
return o => this.searchService.highlightMatches(this.labelGetter(o), this.query || "");
}
}
@Input()
public set optionFormatter(formatter:((option:T, query?:string) => string) | undefined) {
this._optionFormatter = formatter;
}
private _localeValues:ISelectLocaleValues;
public localeOverrides:RecursivePartial<ISelectLocaleValues>;
public get localeValues():ISelectLocaleValues {
return this._localizationService.override<"select">(this._localeValues, this.localeOverrides);
}
@Input()
public icon:string;
@Input()
public transition:string;
@Input()
public transitionDuration:number;
@Output("touched")
public onTouched:EventEmitter<void>;
private _documentKeyDownListener:() => void;
constructor(private _element:ElementRef, renderer:Renderer2, protected _localizationService:SuiLocalizationService) {
this.dropdownService = new DropdownService();
// We do want an empty query to return all results.
this.searchService = new SearchService<T, U>(true);
this.isSearchable = false;
this.onLocaleUpdate();
this._localizationService.onLanguageUpdate.subscribe(() => this.onLocaleUpdate());
this._renderedSubscriptions = [];
this.icon = "dropdown";
this.transition = "slide down";
this.transitionDuration = 200;
this.onTouched = new EventEmitter<void>();
this._documentKeyDownListener = renderer.listen("document", "keydown", (e:KeyboardEvent) => this.onDocumentKeyDown(e));
this._selectClasses = true;
}
public ngAfterContentInit():void {
this._menu.service = this.dropdownService;
// We manually specify the menu items to the menu because the @ContentChildren doesn't pick up our dynamically rendered items.
this._menu.items = this._renderedOptions;
if (this._manualSearch) {
this.isSearchable = true;
this.isSearchExternal = true;
}
if (this.searchInput) {
this.searchInput.onQueryUpdated.subscribe((q:string) => this.query = q);
this.searchInput.onQueryKeyDown.subscribe((e:KeyboardEvent) => this.onQueryInputKeydown(e));
}
// We must call this immediately as changes doesn't fire when you subscribe.
this.onAvailableOptionsRendered();
this._renderedOptions.changes.subscribe(() => this.onAvailableOptionsRendered());
}
private onLocaleUpdate():void {
this._localeValues = this._localizationService.get().select;
}
// Hook is here since Typescript doesn't yet support overriding getters & setters while still calling the superclass.
protected optionsUpdateHook():void {}
// Hook is here since Typescript doesn't yet support overriding getters & setters while still calling the superclass.
protected queryUpdateHook():void {}
protected updateQuery(query:string):void {
// Update the query then open the dropdown, as after keyboard input it should always be open.
this.searchService.updateQuery(query, () =>
this.dropdownService.setOpenState(true));
}
protected resetQuery(delayed:boolean = true):void {
// The search delay is set to the transition duration to ensure results
// aren't rendered as the select closes as that causes a sudden flash.
if (delayed) {
this.searchService.searchDelay = this._menu.menuTransitionDuration;
this.searchService.updateQueryDelayed("");
} else {
this.searchService.updateQuery("");
}
if (this.searchInput) {
this.searchInput.query = "";
}
}
protected onAvailableOptionsRendered():void {
// Unsubscribe from all previous subscriptions to avoid memory leaks on large selects.
this._renderedSubscriptions.forEach(rs => rs.unsubscribe());
this._renderedSubscriptions = [];
this._renderedOptions.forEach(ro => {
// Slightly delay initialisation to avoid change after checked errors. TODO - look into avoiding this!
setTimeout(() => this.initialiseRenderedOption(ro));
this._renderedSubscriptions.push(ro.onSelected.subscribe(() => this.selectOption(ro.value)));
});
// If no options have been provided, autogenerate them from the rendered ones.
if (this.searchService.options.length === 0 && !this.searchService.optionsLookup) {
this.options = this._renderedOptions.map(ro => ro.value);
}
}
protected initialiseRenderedOption(option:SuiSelectOption<T>):void {
option.usesTemplate = !!this.optionTemplate;
option.formatter = this.configuredFormatter;
if (option.usesTemplate) {
this.drawTemplate(option.templateSibling, option.value);
}
option.changeDetector.markForCheck();
}
public abstract selectOption(option:T):void;
protected findOption(options:T[], value:U):T | undefined {
if (this._compareWith) {
return options.find(o => this._compareWith(value, this.valueGetter(o)));
}
// Tries to find an option in options array
return options.find(o => value === this.valueGetter(o));
}
public onCaretClick(e:HandledEvent):void {
if (!e.eventHandled) {
e.eventHandled = true;
if (!this.dropdownService.isAnimating) {
this.dropdownService.setOpenState(!this.dropdownService.isOpen);
this.focus();
}
}
}
@HostListener("click", ["$event"])
public onClick(e:HandledEvent):void {
if (!e.eventHandled && !this.dropdownService.isAnimating) {
e.eventHandled = true;
// If the dropdown is searchable, clicking should keep it open, otherwise we toggle the open state.
this.dropdownService.setOpenState(this.isSearchable ? true : !this.dropdownService.isOpen);
// Immediately focus the search input whenever clicking on the select.
this.focus();
}
}
@HostListener("focusin")
private onFocusIn():void {
if (!this.dropdownService.isOpen && !this.dropdownService.isAnimating) {
this.dropdownService.setOpenState(true);
this.focus();
}
}
@HostListener("focusout", ["$event"])
private onFocusOut(e:IFocusEvent):void {
if (!this._element.nativeElement.contains(e.relatedTarget)) {
this.dropdownService.setOpenState(false);
this.onTouched.emit();
}
}
@HostListener("keypress", ["$event"])
public onKeyPress(e:KeyboardEvent):void {
if (e.keyCode === KeyCode.Enter) {
// Enables support for focussing and opening with the keyboard alone.
// Using directly because Renderer2 doesn't have invokeElementMethod method anymore.
this._element.nativeElement.click();
}
}
public onDocumentKeyDown(e:KeyboardEvent):void {
if (this._element.nativeElement.contains(e.target) &&
!this.dropdownService.isOpen &&
e.keyCode === KeyCode.Down) {
// Enables support for focussing and opening with the keyboard alone.
// Using directly because Renderer2 doesn't have invokeElementMethod method anymore.
this._element.nativeElement.click();
e.preventDefault();
}
}
public onQueryInputKeydown(event:KeyboardEvent):void {}
protected focus():void {
if (this.isSearchable && this.searchInput) {
// Focusses the search input only when searchable.
// Using directly because Renderer2 doesn't have invokeElementMethod method anymore.
this.searchInput.focus();
} else {
this._element.nativeElement.focus();
}
}
// Helper that draws the provided template beside the provided ViewContainerRef.
protected drawTemplate(siblingRef:ViewContainerRef, value:T):void {
siblingRef.clear();
// Use of `$implicit` means use of <ng-template let-option> syntax is supported.
siblingRef.createEmbeddedView(this.optionTemplate, {
$implicit: value,
query: this.query
});
}
public ngOnDestroy():void {
this._renderedSubscriptions.forEach(s => s.unsubscribe());
this._documentKeyDownListener();
}
}