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() startIdFiresOnChange: boolean;
76 // Allow the selected entry ID to be passed via the template
77 // This does NOT not emit onChange events.
78 @Input() set selectedId(id: any) {
79 if (id === undefined) { return; }
81 // clear on explicit null
82 if (id === null) { this.selected = null; }
84 if (this.entrylist.length) {
85 this.selected = this.entrylist.filter(e => e.id === id)[0];
89 // It's possible the selected ID lives in a set of entries
90 // that are yet to be provided.
95 get selectedId(): any {
96 return this.selected ? this.selected.id : null;
99 @Input() idlClass: string;
100 @Input() idlField: string;
101 @Input() idlIncludeLibraryInLabel: string;
102 @Input() asyncDataSource: (term: string) => Observable<ComboboxEntry>;
104 // If true, an async data search is allowed to fetch all
105 // values when given an empty term. This should be used only
106 // if the maximum number of entries returned by the data source
107 // is known to be no more than a couple hundred.
108 @Input() asyncSupportsEmptyTermClick: boolean;
110 // Useful for efficiently preventing duplicate async entries
111 asyncIds: {[idx: string]: boolean};
113 // True if a default selection has been made.
114 defaultSelectionApplied: boolean;
116 @Input() set entries(el: ComboboxEntry[]) {
119 if (this.entrylistMatches(el)) {
120 // Avoid reprocessing data we already have.
126 // new set of entries essentially means a new instance. reset.
127 this.defaultSelectionApplied = false;
128 this.applySelection();
130 // It's possible to provide an entrylist at load time, but
131 // fetch all future data via async data source. Track the
132 // values we already have so async lookup won't add them again.
133 // A new entry list wipes out any existing async values.
135 el.forEach(entry => this.asyncIds['' + entry.id] = true);
139 // When provided use this as the display template for each entry.
140 @Input() displayTemplate: TemplateRef<any>;
142 // Emitted when the value is changed via UI.
143 // When the UI value is cleared, null is emitted.
144 @Output() onChange: EventEmitter<ComboboxEntry>;
146 // Useful for massaging the match string prior to comparison
147 // and display. Default version trims leading/trailing spaces.
148 formatDisplayString: (e: ComboboxEntry) => string;
150 // Stub functions required by ControlValueAccessor
151 propagateChange = (_: any) => {};
152 propagateTouch = () => {};
155 private elm: ElementRef,
156 private store: StoreService,
157 private idl: IdlService,
158 private pcrud: PcrudService,
162 this.click$ = new Subject<string>();
163 this.onChange = new EventEmitter<ComboboxEntry>();
164 this.defaultSelectionApplied = false;
166 this.formatDisplayString = (result: ComboboxEntry) => {
167 const display = result.label || result.id;
168 return (display + '').trim();
174 const classDef = this.idl.classes[this.idlClass];
175 const pkeyField = classDef.pkey;
178 throw new Error(`IDL class ${this.idlClass} has no pkey field`);
181 if (!this.idlField) {
182 this.idlField = this.idl.getClassSelector(this.idlClass);
185 this.asyncDataSource = term => {
186 const field = this.idlField;
188 const extra_args = { order_by : {} };
189 args[field] = {'ilike': `%${term}%`}; // could -or search on label
190 extra_args['order_by'][this.idlClass] = field;
191 if (this.idlIncludeLibraryInLabel) {
192 extra_args['flesh'] = 1;
193 const flesh_fields: Object = {};
194 flesh_fields[this.idlClass] = [ this.idlIncludeLibraryInLabel ];
195 extra_args['flesh_fields'] = flesh_fields;
196 return this.pcrud.search(this.idlClass, args, extra_args).pipe(map(data => {
198 id: data[pkeyField](),
199 label: data[field]() + ' (' + data[this.idlIncludeLibraryInLabel]().shortname() + ')'
203 return this.pcrud.search(this.idlClass, args, extra_args).pipe(map(data => {
204 return {id: data[pkeyField](), label: data[field]()};
212 this.click$.next($event.target.value);
216 // Give the input a chance to focus then fire the click
217 // handler to force open the typeahead
218 this.elm.nativeElement.getElementsByTagName('input')[0].focus();
219 setTimeout(() => this.click$.next(''));
222 // Returns true if the 2 entries are equivalent.
223 entriesMatch(e1: ComboboxEntry, e2: ComboboxEntry): boolean {
227 e1.label === e2.label &&
228 e1.freetext === e2.freetext
232 // Returns true if the 2 lists are equivalent.
233 entrylistMatches(el: ComboboxEntry[]): boolean {
234 if (el.length === 0 && this.entrylist.length === 0) {
235 // Empty arrays are only equivalent if they are the same array,
236 // since the caller may provide an array that starts empty, but
237 // is later populated.
238 return el === this.entrylist;
240 if (el.length !== this.entrylist.length) {
243 for (let i = 0; i < el.length; i++) {
244 const mine = this.entrylist[i];
245 if (!mine || !this.entriesMatch(mine, el[i])) {
252 // Apply a default selection where needed
255 if (this.startId !== null &&
256 this.entrylist && !this.defaultSelectionApplied) {
259 this.entrylist.filter(e => e.id === this.startId)[0];
262 this.selected = entry;
263 this.defaultSelectionApplied = true;
264 if (this.startIdFiresOnChange) {
265 this.selectorChanged(
266 {item: this.selected, preventDefault: () => true});
272 // Called by combobox-entry.component
273 addEntry(entry: ComboboxEntry) {
274 this.entrylist.push(entry);
275 this.applySelection();
278 // Manually set the selected value by ID.
279 // This does NOT fire the onChange handler.
280 // DEPRECATED: use this.selectedId = abc or [selectedId]="abc" instead.
281 applyEntryId(entryId: any) {
282 this.selected = this.entrylist.filter(e => e.id === entryId)[0];
285 addAsyncEntry(entry: ComboboxEntry) {
286 // Avoid duplicate async entries
287 if (!this.asyncIds['' + entry.id]) {
288 this.asyncIds['' + entry.id] = true;
289 this.addEntry(entry);
293 hasEntry(entryId: any): boolean {
294 return this.entrylist.filter(e => e.id === entryId)[0] !== undefined;
298 // When the selected value is a string it means we have either
299 // no value (user cleared the input) or a free-text value.
301 if (typeof this.selected === 'string') {
303 if (this.allowFreeText && this.selected !== '') {
304 // Free text entered which does not match a known entry
305 // translate it into a dummy ComboboxEntry
308 label: this.selected,
314 this.selected = null;
317 // Manually fire the onchange since NgbTypeahead fails
318 // to fire the onchange when the value is cleared.
319 this.selectorChanged(
320 {item: this.selected, preventDefault: () => true});
322 this.propagateTouch();
325 // Fired by the typeahead to inform us of a change.
326 selectorChanged(selEvent: NgbTypeaheadSelectItemEvent) {
327 this.onChange.emit(selEvent.item);
328 this.propagateChange(selEvent.item);
331 // Adds matching async entries to the entry list
332 // and propagates the search term for pipelining.
333 addAsyncEntries(term: string): Observable<string> {
335 if (!term || !this.asyncDataSource) {
339 let searchTerm: string;
341 if (searchTerm === '_CLICK_') {
342 if (this.asyncSupportsEmptyTermClick) {
349 return new Observable(observer => {
350 this.asyncDataSource(searchTerm).subscribe(
351 (entry: ComboboxEntry) => this.addAsyncEntry(entry),
354 observer.next(searchTerm);
361 filter = (text$: Observable<string>): Observable<ComboboxEntry[]> => {
364 distinctUntilChanged(),
366 // Merge click actions in with the stream of text entry
368 // Inject a specifier indicating the source of the
369 // action is a user click instead of a text entry.
370 // This tells the filter to show all values in sync mode.
371 this.click$.pipe(filter(() =>
372 !this.instance.isPopupOpen()
373 )).pipe(mapTo('_CLICK_'))
376 // mergeMap coalesces an observable into our stream.
377 mergeMap(term => this.addAsyncEntries(term)),
378 map((term: string) => {
380 if (term === '' || term === '_CLICK_') {
381 if (!this.asyncDataSource) {
382 // In sync mode, a post-focus empty search or
383 // click event displays the whole list.
384 return this.entrylist;
388 // Filter entrylist whose labels substring-match the
390 return this.entrylist.filter(entry => {
391 const label = entry.label || entry.id;
392 return label.toLowerCase().indexOf(term.toLowerCase()) > -1;
398 writeValue(value: ComboboxEntry) {
399 if (value !== undefined && value !== null) {
400 this.startId = value.id;
401 this.applySelection();
405 registerOnChange(fn) {
406 this.propagateChange = fn;
409 registerOnTouched(fn) {
410 this.propagateTouch = fn;