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.
21 userdata?: any; // opaque external value; ignored by this component.
25 selector: 'eg-combobox',
26 templateUrl: './combobox.component.html',
28 .icons {margin-left:-18px}
29 .material-icons {font-size: 16px;font-weight:bold}
32 provide: NG_VALUE_ACCESSOR,
33 useExisting: forwardRef(() => ComboboxComponent),
37 export class ComboboxComponent implements ControlValueAccessor, OnInit {
39 selected: ComboboxEntry;
40 click$: Subject<string>;
41 entrylist: ComboboxEntry[];
43 @ViewChild('instance', { static: true }) instance: NgbTypeahead;
45 // Applies a name attribute to the input.
47 @Input() name: string;
49 // Placeholder text for selector input
50 @Input() placeholder = '';
52 @Input() persistKey: string; // TODO
54 @Input() allowFreeText = false;
56 @Input() inputSize: number = null;
58 // Add a 'required' attribute to the input
60 @Input() set required(r: boolean) {
66 @Input() set disabled(d: boolean) {
70 // Entry ID of the default entry to select (optional)
71 // onChange() is NOT fired when applying the default value,
72 // unless startIdFiresOnChange is set to true.
73 @Input() startId: any = null;
74 @Input() idlClass: string;
75 @Input() startIdFiresOnChange: boolean;
77 // Allow the selected entry ID to be passed via the template
78 // This does NOT not emit onChange events.
79 @Input() set selectedId(id: any) {
80 if (id === undefined) { return; }
82 // clear on explicit null
83 if (id === null) { this.selected = null; }
85 if (this.entrylist.length) {
86 this.selected = this.entrylist.filter(e => e.id === id)[0];
90 // It's possible the selected ID lives in a set of entries
91 // that are yet to be provided.
94 this.pcrud.retrieve(this.idlClass, id)
98 label: rec[this.idlField]()
100 this.selected = this.entrylist.filter(e => e.id === id)[0];
106 get selectedId(): any {
107 return this.selected ? this.selected.id : null;
110 @Input() idlField: string;
111 @Input() idlIncludeLibraryInLabel: string;
112 @Input() asyncDataSource: (term: string) => Observable<ComboboxEntry>;
114 // If true, an async data search is allowed to fetch all
115 // values when given an empty term. This should be used only
116 // if the maximum number of entries returned by the data source
117 // is known to be no more than a couple hundred.
118 @Input() asyncSupportsEmptyTermClick: boolean;
120 // Useful for efficiently preventing duplicate async entries
121 asyncIds: {[idx: string]: boolean};
123 // True if a default selection has been made.
124 defaultSelectionApplied: boolean;
126 @Input() set entries(el: ComboboxEntry[]) {
129 if (this.entrylistMatches(el)) {
130 // Avoid reprocessing data we already have.
136 // new set of entries essentially means a new instance. reset.
137 this.defaultSelectionApplied = false;
138 this.applySelection();
140 // It's possible to provide an entrylist at load time, but
141 // fetch all future data via async data source. Track the
142 // values we already have so async lookup won't add them again.
143 // A new entry list wipes out any existing async values.
145 el.forEach(entry => this.asyncIds['' + entry.id] = true);
149 // When provided use this as the display template for each entry.
150 @Input() displayTemplate: TemplateRef<any>;
152 // Emitted when the value is changed via UI.
153 // When the UI value is cleared, null is emitted.
154 @Output() onChange: EventEmitter<ComboboxEntry>;
156 // Useful for massaging the match string prior to comparison
157 // and display. Default version trims leading/trailing spaces.
158 formatDisplayString: (e: ComboboxEntry) => string;
160 // Stub functions required by ControlValueAccessor
161 propagateChange = (_: any) => {};
162 propagateTouch = () => {};
165 private elm: ElementRef,
166 private store: StoreService,
167 private idl: IdlService,
168 private pcrud: PcrudService,
172 this.click$ = new Subject<string>();
173 this.onChange = new EventEmitter<ComboboxEntry>();
174 this.defaultSelectionApplied = false;
176 this.formatDisplayString = (result: ComboboxEntry) => {
177 const display = result.label || result.id;
178 return (display + '').trim();
184 const classDef = this.idl.classes[this.idlClass];
185 const pkeyField = classDef.pkey;
188 throw new Error(`IDL class ${this.idlClass} has no pkey field`);
191 if (!this.idlField) {
192 this.idlField = this.idl.getClassSelector(this.idlClass);
195 this.asyncDataSource = term => {
196 const field = this.idlField;
198 const extra_args = { order_by : {} };
199 args[field] = {'ilike': `%${term}%`}; // could -or search on label
200 extra_args['order_by'][this.idlClass] = field;
201 if (this.idlIncludeLibraryInLabel) {
202 extra_args['flesh'] = 1;
203 const flesh_fields: Object = {};
204 flesh_fields[this.idlClass] = [ this.idlIncludeLibraryInLabel ];
205 extra_args['flesh_fields'] = flesh_fields;
206 return this.pcrud.search(this.idlClass, args, extra_args).pipe(map(data => {
208 id: data[pkeyField](),
209 label: data[field]() + ' (' + data[this.idlIncludeLibraryInLabel]().shortname() + ')'
213 return this.pcrud.search(this.idlClass, args, extra_args).pipe(map(data => {
214 return {id: data[pkeyField](), label: data[field]()};
222 this.click$.next($event.target.value);
226 // Give the input a chance to focus then fire the click
227 // handler to force open the typeahead
228 this.elm.nativeElement.getElementsByTagName('input')[0].focus();
229 setTimeout(() => this.click$.next(''));
232 // Returns true if the 2 entries are equivalent.
233 entriesMatch(e1: ComboboxEntry, e2: ComboboxEntry): boolean {
237 e1.label === e2.label &&
238 e1.freetext === e2.freetext
242 // Returns true if the 2 lists are equivalent.
243 entrylistMatches(el: ComboboxEntry[]): boolean {
244 if (el.length === 0 && this.entrylist.length === 0) {
245 // Empty arrays are only equivalent if they are the same array,
246 // since the caller may provide an array that starts empty, but
247 // is later populated.
248 return el === this.entrylist;
250 if (el.length !== this.entrylist.length) {
253 for (let i = 0; i < el.length; i++) {
254 const mine = this.entrylist[i];
255 if (!mine || !this.entriesMatch(mine, el[i])) {
262 // Apply a default selection where needed
265 if (this.startId !== null &&
266 this.entrylist && !this.defaultSelectionApplied) {
269 this.entrylist.filter(e => e.id === this.startId)[0];
272 this.selected = entry;
273 this.defaultSelectionApplied = true;
274 if (this.startIdFiresOnChange) {
275 this.selectorChanged(
276 {item: this.selected, preventDefault: () => true});
282 // Called by combobox-entry.component
283 addEntry(entry: ComboboxEntry) {
284 this.entrylist.push(entry);
285 this.applySelection();
288 // Manually set the selected value by ID.
289 // This does NOT fire the onChange handler.
290 // DEPRECATED: use this.selectedId = abc or [selectedId]="abc" instead.
291 applyEntryId(entryId: any) {
292 this.selected = this.entrylist.filter(e => e.id === entryId)[0];
295 addAsyncEntry(entry: ComboboxEntry) {
296 // Avoid duplicate async entries
297 if (!this.asyncIds['' + entry.id]) {
298 this.asyncIds['' + entry.id] = true;
299 this.addEntry(entry);
303 hasEntry(entryId: any): boolean {
304 return this.entrylist.filter(e => e.id === entryId)[0] !== undefined;
308 // When the selected value is a string it means we have either
309 // no value (user cleared the input) or a free-text value.
311 if (typeof this.selected === 'string') {
313 if (this.allowFreeText && this.selected !== '') {
314 // Free text entered which does not match a known entry
315 // translate it into a dummy ComboboxEntry
318 label: this.selected,
324 this.selected = null;
327 // Manually fire the onchange since NgbTypeahead fails
328 // to fire the onchange when the value is cleared.
329 this.selectorChanged(
330 {item: this.selected, preventDefault: () => true});
332 this.propagateTouch();
335 // Fired by the typeahead to inform us of a change.
336 selectorChanged(selEvent: NgbTypeaheadSelectItemEvent) {
337 this.onChange.emit(selEvent.item);
338 this.propagateChange(selEvent.item);
341 // Adds matching async entries to the entry list
342 // and propagates the search term for pipelining.
343 addAsyncEntries(term: string): Observable<string> {
345 if (!term || !this.asyncDataSource) {
349 let searchTerm: string;
351 if (searchTerm === '_CLICK_') {
352 if (this.asyncSupportsEmptyTermClick) {
359 return new Observable(observer => {
360 this.asyncDataSource(searchTerm).subscribe(
361 (entry: ComboboxEntry) => this.addAsyncEntry(entry),
364 observer.next(searchTerm);
371 filter = (text$: Observable<string>): Observable<ComboboxEntry[]> => {
374 distinctUntilChanged(),
376 // Merge click actions in with the stream of text entry
378 // Inject a specifier indicating the source of the
379 // action is a user click instead of a text entry.
380 // This tells the filter to show all values in sync mode.
381 this.click$.pipe(filter(() =>
382 !this.instance.isPopupOpen()
383 )).pipe(mapTo('_CLICK_'))
386 // mergeMap coalesces an observable into our stream.
387 mergeMap(term => this.addAsyncEntries(term)),
388 map((term: string) => {
390 // Display no values when the input is empty and no
391 // click action occurred.
392 if (term === '') { return []; }
394 // In sync-data mode, a click displays the full list.
395 if (term === '_CLICK_' && !this.asyncDataSource) {
396 return this.entrylist;
399 // Filter entrylist whose labels substring-match the
401 return this.entrylist.filter(entry => {
402 const label = entry.label || entry.id;
403 return label.toLowerCase().indexOf(term.toLowerCase()) > -1;
409 writeValue(value: ComboboxEntry) {
410 if (value !== undefined && value !== null) {
411 this.startId = value.id;
412 this.applySelection();
416 registerOnChange(fn) {
417 this.propagateChange = fn;
420 registerOnTouched(fn) {
421 this.propagateTouch = fn;