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') 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 // Add a 'required' attribute to the input
57 @Input() set required(r: boolean) {
63 @Input() set disabled(d: boolean) {
67 // Entry ID of the default entry to select (optional)
68 // onChange() is NOT fired when applying the default value,
69 // unless startIdFiresOnChange is set to true.
70 @Input() startId: any;
71 @Input() startIdFiresOnChange: boolean;
73 @Input() idlClass: string;
74 @Input() idlField: string;
75 @Input() asyncDataSource: (term: string) => Observable<ComboboxEntry>;
77 // If true, an async data search is allowed to fetch all
78 // values when given an empty term. This should be used only
79 // if the maximum number of entries returned by the data source
80 // is known to be no more than a couple hundred.
81 @Input() asyncSupportsEmptyTermClick: boolean;
83 // Useful for efficiently preventing duplicate async entries
84 asyncIds: {[idx: string]: boolean};
86 // True if a default selection has been made.
87 defaultSelectionApplied: boolean;
89 @Input() set entries(el: ComboboxEntry[]) {
92 this.applySelection();
94 // It's possible to provide an entrylist at load time, but
95 // fetch all future data via async data source. Track the
96 // values we already have so async lookup won't add them again.
97 // A new entry list wipes out any existing async values.
99 el.forEach(entry => this.asyncIds['' + entry.id] = true);
103 // When provided use this as the display template for each entry.
104 @Input() displayTemplate: TemplateRef<any>;
106 // Emitted when the value is changed via UI.
107 // When the UI value is cleared, null is emitted.
108 @Output() onChange: EventEmitter<ComboboxEntry>;
110 // Useful for massaging the match string prior to comparison
111 // and display. Default version trims leading/trailing spaces.
112 formatDisplayString: (e: ComboboxEntry) => string;
114 // Stub functions required by ControlValueAccessor
115 propagateChange = (_: any) => {};
116 propagateTouch = () => {};
119 private elm: ElementRef,
120 private store: StoreService,
121 private idl: IdlService,
122 private pcrud: PcrudService,
126 this.click$ = new Subject<string>();
127 this.onChange = new EventEmitter<ComboboxEntry>();
128 this.defaultSelectionApplied = false;
130 this.formatDisplayString = (result: ComboboxEntry) => {
131 const display = result.label || result.id;
132 return (display + '').trim();
138 const classDef = this.idl.classes[this.idlClass];
139 const pkeyField = classDef.pkey;
142 throw new Error(`IDL class ${this.idlClass} has no pkey field`);
145 if (!this.idlField) {
146 this.idlField = classDef.field_map[classDef.pkey].selector || 'name';
149 this.asyncDataSource = term => {
150 const field = this.idlField;
152 const extra_args = { order_by : {} };
153 args[field] = {'ilike': `%${term}%`}; // could -or search on label
154 extra_args['order_by'][this.idlClass] = field;
155 return this.pcrud.search(this.idlClass, args, extra_args).pipe(map(data => {
156 return {id: data[pkeyField](), label: data[field]()};
163 this.click$.next($event.target.value);
167 // Give the input a chance to focus then fire the click
168 // handler to force open the typeahead
169 this.elm.nativeElement.getElementsByTagName('input')[0].focus();
170 setTimeout(() => this.click$.next(''));
173 // Apply a default selection where needed
177 this.entrylist && !this.defaultSelectionApplied) {
180 this.entrylist.filter(e => e.id === this.startId)[0];
183 this.selected = entry;
184 this.defaultSelectionApplied = true;
185 if (this.startIdFiresOnChange) {
186 this.selectorChanged(
187 {item: this.selected, preventDefault: () => true});
193 // Called by combobox-entry.component
194 addEntry(entry: ComboboxEntry) {
195 this.entrylist.push(entry);
196 this.applySelection();
199 // Manually set the selected value by ID.
200 // This does NOT fire the onChange handler.
201 applyEntryId(entryId: any) {
202 this.selected = this.entrylist.filter(e => e.id === entryId)[0];
205 addAsyncEntry(entry: ComboboxEntry) {
206 // Avoid duplicate async entries
207 if (!this.asyncIds['' + entry.id]) {
208 this.asyncIds['' + entry.id] = true;
209 this.addEntry(entry);
214 // When the selected value is a string it means we have either
215 // no value (user cleared the input) or a free-text value.
217 if (typeof this.selected === 'string') {
219 if (this.allowFreeText && this.selected !== '') {
220 // Free text entered which does not match a known entry
221 // translate it into a dummy ComboboxEntry
224 label: this.selected,
230 this.selected = null;
233 // Manually fire the onchange since NgbTypeahead fails
234 // to fire the onchange when the value is cleared.
235 this.selectorChanged(
236 {item: this.selected, preventDefault: () => true});
238 this.propagateTouch();
241 // Fired by the typeahead to inform us of a change.
242 selectorChanged(selEvent: NgbTypeaheadSelectItemEvent) {
243 this.onChange.emit(selEvent.item);
244 this.propagateChange(selEvent.item);
247 // Adds matching async entries to the entry list
248 // and propagates the search term for pipelining.
249 addAsyncEntries(term: string): Observable<string> {
251 if (!term || !this.asyncDataSource) {
255 let searchTerm: string;
257 if (searchTerm === '_CLICK_' && this.asyncSupportsEmptyTermClick) {
261 return new Observable(observer => {
262 this.asyncDataSource(searchTerm).subscribe(
263 (entry: ComboboxEntry) => this.addAsyncEntry(entry),
266 observer.next(searchTerm);
273 filter = (text$: Observable<string>): Observable<ComboboxEntry[]> => {
276 distinctUntilChanged(),
278 // Merge click actions in with the stream of text entry
280 // Inject a specifier indicating the source of the
281 // action is a user click instead of a text entry.
282 // This tells the filter to show all values in sync mode.
283 this.click$.pipe(filter(() =>
284 !this.instance.isPopupOpen()
285 )).pipe(mapTo('_CLICK_'))
288 // mergeMap coalesces an observable into our stream.
289 mergeMap(term => this.addAsyncEntries(term)),
290 map((term: string) => {
292 if (term === '' || term === '_CLICK_') {
293 if (!this.asyncDataSource) {
294 // In sync mode, a post-focus empty search or
295 // click event displays the whole list.
296 return this.entrylist;
300 // Filter entrylist whose labels substring-match the
302 return this.entrylist.filter(entry => {
303 const label = entry.label || entry.id;
304 return label.toLowerCase().indexOf(term.toLowerCase()) > -1;
310 writeValue(value: ComboboxEntry) {
311 if (value !== undefined && value !== null) {
312 this.startId = value.id;
313 this.applySelection();
317 registerOnChange(fn) {
318 this.propagateChange = fn;
321 registerOnTouched(fn) {
322 this.propagateTouch = fn;