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) {
78 if (id === undefined) { return; }
80 // clear on explicit null
81 if (id === null) { this.selected = null; }
83 if (this.entrylist.length) {
84 this.selected = this.entrylist.filter(e => e.id === id)[0];
88 // It's possible the selected ID lives in a set of entries
89 // that are yet to be provided.
94 get selectedId(): any {
95 return this.selected ? this.selected.id : null;
98 @Input() idlClass: string;
99 @Input() idlField: string;
100 @Input() idlIncludeLibraryInLabel: string;
101 @Input() asyncDataSource: (term: string) => Observable<ComboboxEntry>;
103 // If true, an async data search is allowed to fetch all
104 // values when given an empty term. This should be used only
105 // if the maximum number of entries returned by the data source
106 // is known to be no more than a couple hundred.
107 @Input() asyncSupportsEmptyTermClick: boolean;
109 // Useful for efficiently preventing duplicate async entries
110 asyncIds: {[idx: string]: boolean};
112 // True if a default selection has been made.
113 defaultSelectionApplied: boolean;
115 @Input() set entries(el: ComboboxEntry[]) {
118 if (this.entrylistMatches(el)) {
119 // Avoid reprocessing data we already have.
125 // new set of entries essentially means a new instance. reset.
126 this.defaultSelectionApplied = false;
127 this.applySelection();
129 // It's possible to provide an entrylist at load time, but
130 // fetch all future data via async data source. Track the
131 // values we already have so async lookup won't add them again.
132 // A new entry list wipes out any existing async values.
134 el.forEach(entry => this.asyncIds['' + entry.id] = true);
138 // When provided use this as the display template for each entry.
139 @Input() displayTemplate: TemplateRef<any>;
141 // Emitted when the value is changed via UI.
142 // When the UI value is cleared, null is emitted.
143 @Output() onChange: EventEmitter<ComboboxEntry>;
145 // Useful for massaging the match string prior to comparison
146 // and display. Default version trims leading/trailing spaces.
147 formatDisplayString: (e: ComboboxEntry) => string;
149 // Stub functions required by ControlValueAccessor
150 propagateChange = (_: any) => {};
151 propagateTouch = () => {};
154 private elm: ElementRef,
155 private store: StoreService,
156 private idl: IdlService,
157 private pcrud: PcrudService,
161 this.click$ = new Subject<string>();
162 this.onChange = new EventEmitter<ComboboxEntry>();
163 this.defaultSelectionApplied = false;
165 this.formatDisplayString = (result: ComboboxEntry) => {
166 const display = result.label || result.id;
167 return (display + '').trim();
173 const classDef = this.idl.classes[this.idlClass];
174 const pkeyField = classDef.pkey;
177 throw new Error(`IDL class ${this.idlClass} has no pkey field`);
180 if (!this.idlField) {
181 this.idlField = this.idl.getClassSelector(this.idlClass);
184 this.asyncDataSource = term => {
185 const field = this.idlField;
187 const extra_args = { order_by : {} };
188 args[field] = {'ilike': `%${term}%`}; // could -or search on label
189 extra_args['order_by'][this.idlClass] = field;
190 if (this.idlIncludeLibraryInLabel) {
191 extra_args['flesh'] = 1;
192 const flesh_fields: Object = {};
193 flesh_fields[this.idlClass] = [ this.idlIncludeLibraryInLabel ];
194 extra_args['flesh_fields'] = flesh_fields;
195 return this.pcrud.search(this.idlClass, args, extra_args).pipe(map(data => {
197 id: data[pkeyField](),
198 label: data[field]() + ' (' + data[this.idlIncludeLibraryInLabel]().shortname() + ')'
202 return this.pcrud.search(this.idlClass, args, extra_args).pipe(map(data => {
203 return {id: data[pkeyField](), label: data[field]()};
211 this.click$.next($event.target.value);
215 // Give the input a chance to focus then fire the click
216 // handler to force open the typeahead
217 this.elm.nativeElement.getElementsByTagName('input')[0].focus();
218 setTimeout(() => this.click$.next(''));
221 // Returns true if the 2 entries are equivalent.
222 entriesMatch(e1: ComboboxEntry, e2: ComboboxEntry): boolean {
226 e1.label === e2.label &&
227 e1.freetext === e2.freetext
231 // Returns true if the 2 lists are equivalent.
232 entrylistMatches(el: ComboboxEntry[]): boolean {
233 if (el.length === 0 && this.entrylist.length === 0) {
234 // Empty arrays are only equivalent if they are the same array,
235 // since the caller may provide an array that starts empty, but
236 // is later populated.
237 return el === this.entrylist;
239 if (el.length !== this.entrylist.length) {
242 for (let i = 0; i < el.length; i++) {
243 const mine = this.entrylist[i];
244 if (!mine || !this.entriesMatch(mine, el[i])) {
251 // Apply a default selection where needed
254 if (this.startId !== null &&
255 this.entrylist && !this.defaultSelectionApplied) {
258 this.entrylist.filter(e => e.id === this.startId)[0];
261 this.selected = entry;
262 this.defaultSelectionApplied = true;
263 if (this.startIdFiresOnChange) {
264 this.selectorChanged(
265 {item: this.selected, preventDefault: () => true});
271 // Called by combobox-entry.component
272 addEntry(entry: ComboboxEntry) {
273 this.entrylist.push(entry);
274 this.applySelection();
277 // Manually set the selected value by ID.
278 // This does NOT fire the onChange handler.
279 // DEPRECATED: use this.selectedId = abc or [selectedId]="abc" instead.
280 applyEntryId(entryId: any) {
281 this.selected = this.entrylist.filter(e => e.id === entryId)[0];
284 addAsyncEntry(entry: ComboboxEntry) {
285 // Avoid duplicate async entries
286 if (!this.asyncIds['' + entry.id]) {
287 this.asyncIds['' + entry.id] = true;
288 this.addEntry(entry);
292 hasEntry(entryId: any): boolean {
293 return this.entrylist.filter(e => e.id === entryId)[0] !== undefined;
297 // When the selected value is a string it means we have either
298 // no value (user cleared the input) or a free-text value.
300 if (typeof this.selected === 'string') {
302 if (this.allowFreeText && this.selected !== '') {
303 // Free text entered which does not match a known entry
304 // translate it into a dummy ComboboxEntry
307 label: this.selected,
313 this.selected = null;
316 // Manually fire the onchange since NgbTypeahead fails
317 // to fire the onchange when the value is cleared.
318 this.selectorChanged(
319 {item: this.selected, preventDefault: () => true});
321 this.propagateTouch();
324 // Fired by the typeahead to inform us of a change.
325 selectorChanged(selEvent: NgbTypeaheadSelectItemEvent) {
326 this.onChange.emit(selEvent.item);
327 this.propagateChange(selEvent.item);
330 // Adds matching async entries to the entry list
331 // and propagates the search term for pipelining.
332 addAsyncEntries(term: string): Observable<string> {
334 if (!term || !this.asyncDataSource) {
338 let searchTerm: string;
340 if (searchTerm === '_CLICK_') {
341 if (this.asyncSupportsEmptyTermClick) {
348 return new Observable(observer => {
349 this.asyncDataSource(searchTerm).subscribe(
350 (entry: ComboboxEntry) => this.addAsyncEntry(entry),
353 observer.next(searchTerm);
360 filter = (text$: Observable<string>): Observable<ComboboxEntry[]> => {
363 distinctUntilChanged(),
365 // Merge click actions in with the stream of text entry
367 // Inject a specifier indicating the source of the
368 // action is a user click instead of a text entry.
369 // This tells the filter to show all values in sync mode.
370 this.click$.pipe(filter(() =>
371 !this.instance.isPopupOpen()
372 )).pipe(mapTo('_CLICK_'))
375 // mergeMap coalesces an observable into our stream.
376 mergeMap(term => this.addAsyncEntries(term)),
377 map((term: string) => {
379 if (term === '' || term === '_CLICK_') {
380 if (!this.asyncDataSource) {
381 // In sync mode, a post-focus empty search or
382 // click event displays the whole list.
383 return this.entrylist;
387 // Filter entrylist whose labels substring-match the
389 return this.entrylist.filter(entry => {
390 const label = entry.label || entry.id;
391 return label.toLowerCase().indexOf(term.toLowerCase()) > -1;
397 writeValue(value: ComboboxEntry) {
398 if (value !== undefined && value !== null) {
399 this.startId = value.id;
400 this.applySelection();
404 registerOnChange(fn) {
405 this.propagateChange = fn;
408 registerOnTouched(fn) {
409 this.propagateTouch = fn;