2 * <eg-combobox [allowFreeText]="true" [entries]="comboboxEntryList"/>
3 * <!-- see also <eg-combobox-entry> -->
6 import {Component, OnInit, Input, Output, ViewChild,
7 TemplateRef, EventEmitter, ElementRef, forwardRef} from '@angular/core';
8 import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
9 import {Observable, of, Subject} from 'rxjs';
10 import {map, tap, reduce, mergeMap, mapTo, debounceTime, distinctUntilChanged, merge, filter} from 'rxjs/operators';
11 import {NgbTypeahead, NgbTypeaheadSelectItemEvent} from '@ng-bootstrap/ng-bootstrap';
12 import {StoreService} from '@eg/core/store.service';
13 import {IdlService} from '@eg/core/idl.service';
14 import {PcrudService} from '@eg/core/pcrud.service';
16 export interface ComboboxEntry {
18 // If no label is provided, the 'id' value is used.
24 selector: 'eg-combobox',
25 templateUrl: './combobox.component.html',
27 .icons {margin-left:-18px}
28 .material-icons {font-size: 16px;font-weight:bold}
31 provide: NG_VALUE_ACCESSOR,
32 useExisting: forwardRef(() => ComboboxComponent),
36 export class ComboboxComponent implements ControlValueAccessor, OnInit {
38 selected: ComboboxEntry;
39 click$: Subject<string>;
40 entrylist: ComboboxEntry[];
42 @ViewChild('instance', { static: true }) instance: NgbTypeahead;
44 // Applies a name attribute to the input.
46 @Input() name: string;
48 // Placeholder text for selector input
49 @Input() placeholder = '';
51 @Input() persistKey: string; // TODO
53 @Input() allowFreeText = false;
55 @Input() inputSize: number = null;
57 // Add a 'required' attribute to the input
59 @Input() set required(r: boolean) {
65 @Input() set disabled(d: boolean) {
69 // Entry ID of the default entry to select (optional)
70 // onChange() is NOT fired when applying the default value,
71 // unless startIdFiresOnChange is set to true.
72 @Input() startId: any = null;
73 @Input() startIdFiresOnChange: boolean;
75 // Allow the selected entry ID to be passed via the template
76 // This does NOT not emit onChange events.
77 @Input() set selectedId(id: any) {
79 if (this.entrylist.length) {
80 this.selected = this.entrylist.filter(e => e.id === id)[0];
84 // It's possible the selected ID lives in a set of entries
85 // that are yet to be provided.
91 get selectedId(): any {
92 return this.selected ? this.selected.id : null;
95 @Input() idlClass: string;
96 @Input() idlField: string;
97 @Input() idlIncludeLibraryInLabel: string;
98 @Input() asyncDataSource: (term: string) => Observable<ComboboxEntry>;
100 // If true, an async data search is allowed to fetch all
101 // values when given an empty term. This should be used only
102 // if the maximum number of entries returned by the data source
103 // is known to be no more than a couple hundred.
104 @Input() asyncSupportsEmptyTermClick: boolean;
106 // Useful for efficiently preventing duplicate async entries
107 asyncIds: {[idx: string]: boolean};
109 // True if a default selection has been made.
110 defaultSelectionApplied: boolean;
112 @Input() set entries(el: ComboboxEntry[]) {
115 if (this.entrylistMatches(el)) {
116 // Avoid reprocessing data we already have.
122 // new set of entries essentially means a new instance. reset.
123 this.defaultSelectionApplied = false;
124 this.applySelection();
126 // It's possible to provide an entrylist at load time, but
127 // fetch all future data via async data source. Track the
128 // values we already have so async lookup won't add them again.
129 // A new entry list wipes out any existing async values.
131 el.forEach(entry => this.asyncIds['' + entry.id] = true);
135 // When provided use this as the display template for each entry.
136 @Input() displayTemplate: TemplateRef<any>;
138 // Emitted when the value is changed via UI.
139 // When the UI value is cleared, null is emitted.
140 @Output() onChange: EventEmitter<ComboboxEntry>;
142 // Useful for massaging the match string prior to comparison
143 // and display. Default version trims leading/trailing spaces.
144 formatDisplayString: (e: ComboboxEntry) => string;
146 // Stub functions required by ControlValueAccessor
147 propagateChange = (_: any) => {};
148 propagateTouch = () => {};
151 private elm: ElementRef,
152 private store: StoreService,
153 private idl: IdlService,
154 private pcrud: PcrudService,
158 this.click$ = new Subject<string>();
159 this.onChange = new EventEmitter<ComboboxEntry>();
160 this.defaultSelectionApplied = false;
162 this.formatDisplayString = (result: ComboboxEntry) => {
163 const display = result.label || result.id;
164 return (display + '').trim();
170 const classDef = this.idl.classes[this.idlClass];
171 const pkeyField = classDef.pkey;
174 throw new Error(`IDL class ${this.idlClass} has no pkey field`);
177 if (!this.idlField) {
178 this.idlField = this.idl.getClassSelector(this.idlClass);
181 this.asyncDataSource = term => {
182 const field = this.idlField;
184 const extra_args = { order_by : {} };
185 args[field] = {'ilike': `%${term}%`}; // could -or search on label
186 extra_args['order_by'][this.idlClass] = field;
187 if (this.idlIncludeLibraryInLabel) {
188 extra_args['flesh'] = 1;
189 const flesh_fields: Object = {};
190 flesh_fields[this.idlClass] = [ this.idlIncludeLibraryInLabel ];
191 extra_args['flesh_fields'] = flesh_fields;
192 return this.pcrud.search(this.idlClass, args, extra_args).pipe(map(data => {
194 id: data[pkeyField](),
195 label: data[field]() + ' (' + data[this.idlIncludeLibraryInLabel]().shortname() + ')'
199 return this.pcrud.search(this.idlClass, args, extra_args).pipe(map(data => {
200 return {id: data[pkeyField](), label: data[field]()};
208 this.click$.next($event.target.value);
212 // Give the input a chance to focus then fire the click
213 // handler to force open the typeahead
214 this.elm.nativeElement.getElementsByTagName('input')[0].focus();
215 setTimeout(() => this.click$.next(''));
218 // Returns true if the 2 entries are equivalent.
219 entriesMatch(e1: ComboboxEntry, e2: ComboboxEntry): boolean {
223 e1.label === e2.label &&
224 e1.freetext === e2.freetext
228 // Returns true if the 2 lists are equivalent.
229 entrylistMatches(el: ComboboxEntry[]): boolean {
230 if (el.length === 0 && this.entrylist.length === 0) {
231 // Empty arrays are only equivalent if they are the same array,
232 // since the caller may provide an array that starts empty, but
233 // is later populated.
234 return el === this.entrylist;
236 if (el.length !== this.entrylist.length) {
239 for (let i = 0; i < el.length; i++) {
240 const mine = this.entrylist[i];
241 if (!mine || !this.entriesMatch(mine, el[i])) {
248 // Apply a default selection where needed
251 if (this.startId !== null &&
252 this.entrylist && !this.defaultSelectionApplied) {
255 this.entrylist.filter(e => e.id === this.startId)[0];
258 this.selected = entry;
259 this.defaultSelectionApplied = true;
260 if (this.startIdFiresOnChange) {
261 this.selectorChanged(
262 {item: this.selected, preventDefault: () => true});
268 // Called by combobox-entry.component
269 addEntry(entry: ComboboxEntry) {
270 this.entrylist.push(entry);
271 this.applySelection();
274 // Manually set the selected value by ID.
275 // This does NOT fire the onChange handler.
276 // DEPRECATED: use this.selectedId = abc or [selectedId]="abc" instead.
277 applyEntryId(entryId: any) {
278 this.selected = this.entrylist.filter(e => e.id === entryId)[0];
281 addAsyncEntry(entry: ComboboxEntry) {
282 // Avoid duplicate async entries
283 if (!this.asyncIds['' + entry.id]) {
284 this.asyncIds['' + entry.id] = true;
285 this.addEntry(entry);
289 hasEntry(entryId: any): boolean {
290 return this.entrylist.filter(e => e.id === entryId)[0] !== undefined;
294 // When the selected value is a string it means we have either
295 // no value (user cleared the input) or a free-text value.
297 if (typeof this.selected === 'string') {
299 if (this.allowFreeText && this.selected !== '') {
300 // Free text entered which does not match a known entry
301 // translate it into a dummy ComboboxEntry
304 label: this.selected,
310 this.selected = null;
313 // Manually fire the onchange since NgbTypeahead fails
314 // to fire the onchange when the value is cleared.
315 this.selectorChanged(
316 {item: this.selected, preventDefault: () => true});
318 this.propagateTouch();
321 // Fired by the typeahead to inform us of a change.
322 selectorChanged(selEvent: NgbTypeaheadSelectItemEvent) {
323 this.onChange.emit(selEvent.item);
324 this.propagateChange(selEvent.item);
327 // Adds matching async entries to the entry list
328 // and propagates the search term for pipelining.
329 addAsyncEntries(term: string): Observable<string> {
331 if (!term || !this.asyncDataSource) {
335 let searchTerm: string;
337 if (searchTerm === '_CLICK_') {
338 if (this.asyncSupportsEmptyTermClick) {
345 return new Observable(observer => {
346 this.asyncDataSource(searchTerm).subscribe(
347 (entry: ComboboxEntry) => this.addAsyncEntry(entry),
350 observer.next(searchTerm);
357 filter = (text$: Observable<string>): Observable<ComboboxEntry[]> => {
360 distinctUntilChanged(),
362 // Merge click actions in with the stream of text entry
364 // Inject a specifier indicating the source of the
365 // action is a user click instead of a text entry.
366 // This tells the filter to show all values in sync mode.
367 this.click$.pipe(filter(() =>
368 !this.instance.isPopupOpen()
369 )).pipe(mapTo('_CLICK_'))
372 // mergeMap coalesces an observable into our stream.
373 mergeMap(term => this.addAsyncEntries(term)),
374 map((term: string) => {
376 if (term === '' || term === '_CLICK_') {
377 if (!this.asyncDataSource) {
378 // In sync mode, a post-focus empty search or
379 // click event displays the whole list.
380 return this.entrylist;
384 // Filter entrylist whose labels substring-match the
386 return this.entrylist.filter(entry => {
387 const label = entry.label || entry.id;
388 return label.toLowerCase().indexOf(term.toLowerCase()) > -1;
394 writeValue(value: ComboboxEntry) {
395 if (value !== undefined && value !== null) {
396 this.startId = value.id;
397 this.applySelection();
401 registerOnChange(fn) {
402 this.propagateChange = fn;
405 registerOnTouched(fn) {
406 this.propagateTouch = fn;