2 * <eg-combobox [allowFreeText]="true" [entries]="comboboxEntryList"/>
3 * <!-- see also <eg-combobox-entry> -->
6 import {Component, OnInit, Input, Output, ViewChild,
7 Directive, ViewChildren, QueryList, AfterViewInit,
8 OnChanges, SimpleChanges,
9 TemplateRef, EventEmitter, ElementRef, forwardRef} from '@angular/core';
10 import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
11 import {Observable, of, Subject} from 'rxjs';
12 import {map, tap, reduce, mergeMap, mapTo, debounceTime, distinctUntilChanged, merge, filter} from 'rxjs/operators';
13 import {NgbTypeahead, NgbTypeaheadSelectItemEvent} from '@ng-bootstrap/ng-bootstrap';
14 import {StoreService} from '@eg/core/store.service';
15 import {IdlService, IdlObject} from '@eg/core/idl.service';
16 import {PcrudService} from '@eg/core/pcrud.service';
17 import {OrgService} from '@eg/core/org.service';
19 export interface ComboboxEntry {
21 // If no label is provided, the 'id' value is used.
24 userdata?: any; // opaque external value; ignored by this component.
29 selector: 'ng-template[egIdlClass]'
31 export class IdlClassTemplateDirective {
32 @Input() egIdlClass: string;
33 constructor(public template: TemplateRef<any>) {}
37 selector: 'eg-combobox',
38 templateUrl: './combobox.component.html',
40 .icons {margin-left:-18px}
41 .material-icons {font-size: 16px;font-weight:bold}
44 provide: NG_VALUE_ACCESSOR,
45 useExisting: forwardRef(() => ComboboxComponent),
49 export class ComboboxComponent implements ControlValueAccessor, OnInit, AfterViewInit, OnChanges {
51 selected: ComboboxEntry;
52 click$: Subject<string>;
53 entrylist: ComboboxEntry[];
55 @ViewChild('instance', { static: true }) instance: NgbTypeahead;
56 @ViewChild('defaultDisplayTemplate', { static: true}) defaultDisplayTemplate: TemplateRef<any>;
57 @ViewChildren(IdlClassTemplateDirective) idlClassTemplates: QueryList<IdlClassTemplateDirective>;
59 // Applies a name attribute to the input.
61 @Input() name: string;
63 // Placeholder text for selector input
64 @Input() placeholder = '';
66 @Input() persistKey: string; // TODO
68 @Input() allowFreeText = false;
70 @Input() inputSize: number = null;
72 // Add a 'required' attribute to the input
74 @Input() set required(r: boolean) {
80 @Input() set disabled(d: boolean) {
84 // Entry ID of the default entry to select (optional)
85 // onChange() is NOT fired when applying the default value,
86 // unless startIdFiresOnChange is set to true.
87 @Input() startId: any = null;
88 @Input() idlClass: string;
89 @Input() startIdFiresOnChange: boolean;
91 // Allow the selected entry ID to be passed via the template
92 // This does NOT not emit onChange events.
93 @Input() set selectedId(id: any) {
94 if (id === undefined) { return; }
96 // clear on explicit null
97 if (id === null) { this.selected = null; }
99 if (this.entrylist.length) {
100 this.selected = this.entrylist.filter(e => e.id === id)[0];
103 if (!this.selected) {
104 // It's possible the selected ID lives in a set of entries
105 // that are yet to be provided.
108 this.pcrud.retrieve(this.idlClass, id)
112 label: this.getFmRecordLabel(rec),
115 this.selected = this.entrylist.filter(e => e.id === id)[0];
121 get selectedId(): any {
122 return this.selected ? this.selected.id : null;
125 @Input() idlField: string;
126 @Input() idlIncludeLibraryInLabel: string;
127 @Input() asyncDataSource: (term: string) => Observable<ComboboxEntry>;
129 // If true, an async data search is allowed to fetch all
130 // values when given an empty term. This should be used only
131 // if the maximum number of entries returned by the data source
132 // is known to be no more than a couple hundred.
133 @Input() asyncSupportsEmptyTermClick: boolean;
135 // Useful for efficiently preventing duplicate async entries
136 asyncIds: {[idx: string]: boolean};
138 // True if a default selection has been made.
139 defaultSelectionApplied: boolean;
141 @Input() set entries(el: ComboboxEntry[]) {
144 if (this.entrylistMatches(el)) {
145 // Avoid reprocessing data we already have.
151 // new set of entries essentially means a new instance. reset.
152 this.defaultSelectionApplied = false;
153 this.applySelection();
155 // It's possible to provide an entrylist at load time, but
156 // fetch all future data via async data source. Track the
157 // values we already have so async lookup won't add them again.
158 // A new entry list wipes out any existing async values.
160 el.forEach(entry => this.asyncIds['' + entry.id] = true);
164 // When provided use this as the display template for each entry.
165 @Input() displayTemplate: TemplateRef<any>;
167 // Emitted when the value is changed via UI.
168 // When the UI value is cleared, null is emitted.
169 @Output() onChange: EventEmitter<ComboboxEntry>;
171 // Useful for massaging the match string prior to comparison
172 // and display. Default version trims leading/trailing spaces.
173 formatDisplayString: (e: ComboboxEntry) => string;
175 idlDisplayTemplateMap: { [key: string]: TemplateRef<any> } = {};
176 getFmRecordLabel: (fm: IdlObject) => string;
178 // Stub functions required by ControlValueAccessor
179 propagateChange = (_: any) => {};
180 propagateTouch = () => {};
183 private elm: ElementRef,
184 private store: StoreService,
185 private idl: IdlService,
186 private pcrud: PcrudService,
187 private org: OrgService,
191 this.click$ = new Subject<string>();
192 this.onChange = new EventEmitter<ComboboxEntry>();
193 this.defaultSelectionApplied = false;
195 this.formatDisplayString = (result: ComboboxEntry) => {
196 const display = result.label || result.id;
197 return (display + '').trim();
200 this.getFmRecordLabel = (fm: IdlObject) => {
201 // FIXME: it would be cleaner if we could somehow use
202 // the per-IDL-class ng-templates directly
203 switch (this.idlClass) {
205 return fm.code() + ' (' + fm.year() + ')';
208 return fm.name() + ' (' + this.getOrgShortname(fm.owning_lib()) + ')';
211 const field = this.idlField;
212 if (this.idlIncludeLibraryInLabel) {
213 return fm[field]() + ' (' + fm[this.idlIncludeLibraryInLabel]().shortname() + ')';
223 const classDef = this.idl.classes[this.idlClass];
224 const pkeyField = classDef.pkey;
227 throw new Error(`IDL class ${this.idlClass} has no pkey field`);
230 if (!this.idlField) {
231 this.idlField = this.idl.getClassSelector(this.idlClass);
234 this.asyncDataSource = term => {
235 const field = this.idlField;
237 const extra_args = { order_by : {} };
238 args[field] = {'ilike': `%${term}%`}; // could -or search on label
239 extra_args['order_by'][this.idlClass] = field;
240 extra_args['limit'] = 100;
241 if (this.idlIncludeLibraryInLabel) {
242 extra_args['flesh'] = 1;
243 const flesh_fields: Object = {};
244 flesh_fields[this.idlClass] = [ this.idlIncludeLibraryInLabel ];
245 extra_args['flesh_fields'] = flesh_fields;
246 return this.pcrud.search(this.idlClass, args, extra_args).pipe(map(data => {
248 id: data[pkeyField](),
249 label: this.getFmRecordLabel(data),
254 return this.pcrud.search(this.idlClass, args, extra_args).pipe(map(data => {
255 return {id: data[pkeyField](), label: this.getFmRecordLabel(data), fm: data};
263 this.idlDisplayTemplateMap = this.idlClassTemplates.reduce((acc, cur) => {
264 acc[cur.egIdlClass] = cur.template;
269 ngOnChanges(changes: SimpleChanges) {
270 let firstTime = true;
271 Object.keys(changes).forEach(key => {
272 if (!changes[key].firstChange) {
277 if ('idlClass' in changes) {
278 if (!('idlField' in changes)) {
279 // let ngOnInit reset it to the
280 // selector of the new IDL class
281 this.idlField = null;
284 this.entrylist.length = 0;
285 this.selected = null;
292 this.click$.next($event.target.value);
295 getResultTemplate(): TemplateRef<any> {
296 if (this.displayTemplate) {
297 return this.displayTemplate;
299 if (this.idlClass in this.idlDisplayTemplateMap) {
300 return this.idlDisplayTemplateMap[this.idlClass];
302 return this.defaultDisplayTemplate;
305 getOrgShortname(ou: any) {
306 if (typeof ou === 'object') {
307 return ou.shortname();
309 return this.org.get(ou).shortname();
314 // Give the input a chance to focus then fire the click
315 // handler to force open the typeahead
316 this.elm.nativeElement.getElementsByTagName('input')[0].focus();
317 setTimeout(() => this.click$.next(''));
320 // Returns true if the 2 entries are equivalent.
321 entriesMatch(e1: ComboboxEntry, e2: ComboboxEntry): boolean {
325 e1.label === e2.label &&
326 e1.freetext === e2.freetext
330 // Returns true if the 2 lists are equivalent.
331 entrylistMatches(el: ComboboxEntry[]): boolean {
332 if (el.length === 0 && this.entrylist.length === 0) {
333 // Empty arrays are only equivalent if they are the same array,
334 // since the caller may provide an array that starts empty, but
335 // is later populated.
336 return el === this.entrylist;
338 if (el.length !== this.entrylist.length) {
341 for (let i = 0; i < el.length; i++) {
342 const mine = this.entrylist[i];
343 if (!mine || !this.entriesMatch(mine, el[i])) {
350 // Apply a default selection where needed
353 if (this.startId !== null &&
354 this.entrylist && !this.defaultSelectionApplied) {
357 this.entrylist.filter(e => e.id === this.startId)[0];
360 this.selected = entry;
361 this.defaultSelectionApplied = true;
362 if (this.startIdFiresOnChange) {
363 this.selectorChanged(
364 {item: this.selected, preventDefault: () => true});
370 // Called by combobox-entry.component
371 addEntry(entry: ComboboxEntry) {
372 this.entrylist.push(entry);
373 this.applySelection();
376 // Manually set the selected value by ID.
377 // This does NOT fire the onChange handler.
378 // DEPRECATED: use this.selectedId = abc or [selectedId]="abc" instead.
379 applyEntryId(entryId: any) {
380 this.selected = this.entrylist.filter(e => e.id === entryId)[0];
383 addAsyncEntry(entry: ComboboxEntry) {
384 // Avoid duplicate async entries
385 if (!this.asyncIds['' + entry.id]) {
386 this.asyncIds['' + entry.id] = true;
387 this.addEntry(entry);
391 hasEntry(entryId: any): boolean {
392 return this.entrylist.filter(e => e.id === entryId)[0] !== undefined;
396 // When the selected value is a string it means we have either
397 // no value (user cleared the input) or a free-text value.
399 if (typeof this.selected === 'string') {
401 if (this.allowFreeText && this.selected !== '') {
402 // Free text entered which does not match a known entry
403 // translate it into a dummy ComboboxEntry
406 label: this.selected,
412 this.selected = null;
415 // Manually fire the onchange since NgbTypeahead fails
416 // to fire the onchange when the value is cleared.
417 this.selectorChanged(
418 {item: this.selected, preventDefault: () => true});
420 this.propagateTouch();
423 // Fired by the typeahead to inform us of a change.
424 selectorChanged(selEvent: NgbTypeaheadSelectItemEvent) {
425 this.onChange.emit(selEvent.item);
426 this.propagateChange(selEvent.item);
429 // Adds matching async entries to the entry list
430 // and propagates the search term for pipelining.
431 addAsyncEntries(term: string): Observable<string> {
433 if (!term || !this.asyncDataSource) {
437 let searchTerm: string;
439 if (searchTerm === '_CLICK_') {
440 if (this.asyncSupportsEmptyTermClick) {
447 return new Observable(observer => {
448 this.asyncDataSource(searchTerm).subscribe(
449 (entry: ComboboxEntry) => this.addAsyncEntry(entry),
452 observer.next(searchTerm);
459 filter = (text$: Observable<string>): Observable<ComboboxEntry[]> => {
462 distinctUntilChanged(),
464 // Merge click actions in with the stream of text entry
466 // Inject a specifier indicating the source of the
467 // action is a user click instead of a text entry.
468 // This tells the filter to show all values in sync mode.
469 this.click$.pipe(filter(() =>
470 !this.instance.isPopupOpen()
471 )).pipe(mapTo('_CLICK_'))
474 // mergeMap coalesces an observable into our stream.
475 mergeMap(term => this.addAsyncEntries(term)),
476 map((term: string) => {
478 // Display no values when the input is empty and no
479 // click action occurred.
480 if (term === '') { return []; }
482 // In sync-data mode, a click displays the full list.
483 if (term === '_CLICK_' && !this.asyncDataSource) {
484 return this.entrylist;
487 // Filter entrylist whose labels substring-match the
489 return this.entrylist.filter(entry => {
490 const label = entry.label || entry.id;
491 return label.toLowerCase().indexOf(term.toLowerCase()) > -1;
497 writeValue(value: ComboboxEntry) {
498 if (value !== undefined && value !== null) {
499 this.startId = value.id;
500 this.applySelection();
504 registerOnChange(fn) {
505 this.propagateChange = fn;
508 registerOnTouched(fn) {
509 this.propagateTouch = fn;