]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/combobox/combobox.component.ts
LP1852782 Angular MARC enriched editor (first batch)
[working/Evergreen.git] / Open-ILS / src / eg2 / src / app / share / combobox / combobox.component.ts
1 /**
2  * <eg-combobox [allowFreeText]="true" [entries]="comboboxEntryList"/>
3  *  <!-- see also <eg-combobox-entry> -->
4  * </eg-combobox>
5  */
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';
15
16 export interface ComboboxEntry {
17   id: any;
18   // If no label is provided, the 'id' value is used.
19   label?: string;
20   freetext?: boolean;
21 }
22
23 @Component({
24   selector: 'eg-combobox',
25   templateUrl: './combobox.component.html',
26   styles: [`
27     .icons {margin-left:-18px}
28     .material-icons {font-size: 16px;font-weight:bold}
29   `],
30   providers: [{
31     provide: NG_VALUE_ACCESSOR,
32     useExisting: forwardRef(() => ComboboxComponent),
33     multi: true
34   }]
35 })
36 export class ComboboxComponent implements ControlValueAccessor, OnInit {
37
38     selected: ComboboxEntry;
39     click$: Subject<string>;
40     entrylist: ComboboxEntry[];
41
42     @ViewChild('instance', { static: true }) instance: NgbTypeahead;
43
44     // Applies a name attribute to the input.
45     // Useful in forms.
46     @Input() name: string;
47
48     // Placeholder text for selector input
49     @Input() placeholder = '';
50
51     @Input() persistKey: string; // TODO
52
53     @Input() allowFreeText = false;
54
55     @Input() inputSize: number = null;
56
57     // Add a 'required' attribute to the input
58     isRequired: boolean;
59     @Input() set required(r: boolean) {
60         this.isRequired = r;
61     }
62
63     // Disable the input
64     isDisabled: boolean;
65     @Input() set disabled(d: boolean) {
66         this.isDisabled = d;
67     }
68
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;
74
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) {
79             if (this.entrylist.length) {
80                 this.selected = this.entrylist.filter(e => e.id === id)[0];
81             }
82
83             if (!this.selected) {
84                 // It's possible the selected ID lives in a set of entries
85                 // that are yet to be provided.
86                 this.startId = id;
87             }
88         }
89     }
90
91     get selectedId(): any {
92         return this.selected ? this.selected.id : null;
93     }
94
95     @Input() idlClass: string;
96     @Input() idlField: string;
97     @Input() idlIncludeLibraryInLabel: string;
98     @Input() asyncDataSource: (term: string) => Observable<ComboboxEntry>;
99
100     // If true, an async data search is allowed to fetch all
101     // values when given an empty term. This should be used only
102     // if the maximum number of entries returned by the data source
103     // is known to be no more than a couple hundred.
104     @Input() asyncSupportsEmptyTermClick: boolean;
105
106     // Useful for efficiently preventing duplicate async entries
107     asyncIds: {[idx: string]: boolean};
108
109     // True if a default selection has been made.
110     defaultSelectionApplied: boolean;
111
112     @Input() set entries(el: ComboboxEntry[]) {
113         if (el) {
114
115             if (this.entrylistMatches(el)) {
116                 // Avoid reprocessing data we already have.
117                 return;
118             }
119
120             this.entrylist = el;
121
122             // new set of entries essentially means a new instance. reset.
123             this.defaultSelectionApplied = false;
124             this.applySelection();
125
126             // It's possible to provide an entrylist at load time, but
127             // fetch all future data via async data source.  Track the
128             // values we already have so async lookup won't add them again.
129             // A new entry list wipes out any existing async values.
130             this.asyncIds = {};
131             el.forEach(entry => this.asyncIds['' + entry.id] = true);
132         }
133     }
134
135     // When provided use this as the display template for each entry.
136     @Input() displayTemplate: TemplateRef<any>;
137
138     // Emitted when the value is changed via UI.
139     // When the UI value is cleared, null is emitted.
140     @Output() onChange: EventEmitter<ComboboxEntry>;
141
142     // Useful for massaging the match string prior to comparison
143     // and display.  Default version trims leading/trailing spaces.
144     formatDisplayString: (e: ComboboxEntry) => string;
145
146     // Stub functions required by ControlValueAccessor
147     propagateChange = (_: any) => {};
148     propagateTouch = () => {};
149
150     constructor(
151       private elm: ElementRef,
152       private store: StoreService,
153       private idl: IdlService,
154       private pcrud: PcrudService,
155     ) {
156         this.entrylist = [];
157         this.asyncIds = {};
158         this.click$ = new Subject<string>();
159         this.onChange = new EventEmitter<ComboboxEntry>();
160         this.defaultSelectionApplied = false;
161
162         this.formatDisplayString = (result: ComboboxEntry) => {
163             const display = result.label || result.id;
164             return (display + '').trim();
165         };
166     }
167
168     ngOnInit() {
169         if (this.idlClass) {
170             const classDef = this.idl.classes[this.idlClass];
171             const pkeyField = classDef.pkey;
172
173             if (!pkeyField) {
174                 throw new Error(`IDL class ${this.idlClass} has no pkey field`);
175             }
176
177             if (!this.idlField) {
178                 this.idlField = this.idl.getClassSelector(this.idlClass);
179             }
180
181             this.asyncDataSource = term => {
182                 const field = this.idlField;
183                 const args = {};
184                 const extra_args = { order_by : {} };
185                 args[field] = {'ilike': `%${term}%`}; // could -or search on label
186                 extra_args['order_by'][this.idlClass] = field;
187                 if (this.idlIncludeLibraryInLabel) {
188                     extra_args['flesh'] = 1;
189                     const flesh_fields: Object = {};
190                     flesh_fields[this.idlClass] = [ this.idlIncludeLibraryInLabel ];
191                     extra_args['flesh_fields'] = flesh_fields;
192                     return this.pcrud.search(this.idlClass, args, extra_args).pipe(map(data => {
193                         return {
194                             id: data[pkeyField](),
195                             label: data[field]() + ' (' + data[this.idlIncludeLibraryInLabel]().shortname() + ')'
196                         };
197                     }));
198                 } else {
199                     return this.pcrud.search(this.idlClass, args, extra_args).pipe(map(data => {
200                         return {id: data[pkeyField](), label: data[field]()};
201                     }));
202                 }
203             };
204         }
205     }
206
207     onClick($event) {
208         this.click$.next($event.target.value);
209     }
210
211     openMe($event) {
212         // Give the input a chance to focus then fire the click
213         // handler to force open the typeahead
214         this.elm.nativeElement.getElementsByTagName('input')[0].focus();
215         setTimeout(() => this.click$.next(''));
216     }
217
218     // Returns true if the 2 entries are equivalent.
219     entriesMatch(e1: ComboboxEntry, e2: ComboboxEntry): boolean {
220         return (
221             e1 && e2 &&
222             e1.id === e2.id &&
223             e1.label === e2.label &&
224             e1.freetext === e2.freetext
225         );
226     }
227
228     // Returns true if the 2 lists are equivalent.
229     entrylistMatches(el: ComboboxEntry[]): boolean {
230         if (el.length === 0 && this.entrylist.length === 0) {
231             // Empty arrays are only equivalent if they are the same array,
232             // since the caller may provide an array that starts empty, but
233             // is later populated.
234             return el === this.entrylist;
235         }
236         if (el.length !== this.entrylist.length) {
237             return false;
238         }
239         for (let i = 0; i < el.length; i++) {
240             const mine = this.entrylist[i];
241             if (!mine || !this.entriesMatch(mine, el[i])) {
242                 return false;
243             }
244         }
245         return true;
246     }
247
248     // Apply a default selection where needed
249     applySelection() {
250
251         if (this.startId !== null &&
252             this.entrylist && !this.defaultSelectionApplied) {
253
254             const entry =
255                 this.entrylist.filter(e => e.id === this.startId)[0];
256
257             if (entry) {
258                 this.selected = entry;
259                 this.defaultSelectionApplied = true;
260                 if (this.startIdFiresOnChange) {
261                     this.selectorChanged(
262                         {item: this.selected, preventDefault: () => true});
263                 }
264             }
265         }
266     }
267
268     // Called by combobox-entry.component
269     addEntry(entry: ComboboxEntry) {
270         this.entrylist.push(entry);
271         this.applySelection();
272     }
273
274     // Manually set the selected value by ID.
275     // This does NOT fire the onChange handler.
276     // DEPRECATED: use this.selectedId = abc or [selectedId]="abc" instead.
277     applyEntryId(entryId: any) {
278         this.selected = this.entrylist.filter(e => e.id === entryId)[0];
279     }
280
281     addAsyncEntry(entry: ComboboxEntry) {
282         // Avoid duplicate async entries
283         if (!this.asyncIds['' + entry.id]) {
284             this.asyncIds['' + entry.id] = true;
285             this.addEntry(entry);
286         }
287     }
288
289     hasEntry(entryId: any): boolean {
290         return this.entrylist.filter(e => e.id === entryId)[0] !== undefined;
291     }
292
293     onBlur() {
294         // When the selected value is a string it means we have either
295         // no value (user cleared the input) or a free-text value.
296
297         if (typeof this.selected === 'string') {
298
299             if (this.allowFreeText && this.selected !== '') {
300                 // Free text entered which does not match a known entry
301                 // translate it into a dummy ComboboxEntry
302                 this.selected = {
303                     id: null,
304                     label: this.selected,
305                     freetext: true
306                 };
307
308             } else {
309
310                 this.selected = null;
311             }
312
313             // Manually fire the onchange since NgbTypeahead fails
314             // to fire the onchange when the value is cleared.
315             this.selectorChanged(
316                 {item: this.selected, preventDefault: () => true});
317         }
318         this.propagateTouch();
319     }
320
321     // Fired by the typeahead to inform us of a change.
322     selectorChanged(selEvent: NgbTypeaheadSelectItemEvent) {
323         this.onChange.emit(selEvent.item);
324         this.propagateChange(selEvent.item);
325     }
326
327     // Adds matching async entries to the entry list
328     // and propagates the search term for pipelining.
329     addAsyncEntries(term: string): Observable<string> {
330
331         if (!term || !this.asyncDataSource) {
332             return of(term);
333         }
334
335         let searchTerm: string;
336         searchTerm = term;
337         if (searchTerm === '_CLICK_') {
338             if (this.asyncSupportsEmptyTermClick) {
339                 searchTerm = '';
340             } else {
341                 return of();
342             }
343         }
344
345         return new Observable(observer => {
346             this.asyncDataSource(searchTerm).subscribe(
347                 (entry: ComboboxEntry) => this.addAsyncEntry(entry),
348                 err => {},
349                 ()  => {
350                     observer.next(searchTerm);
351                     observer.complete();
352                 }
353             );
354         });
355     }
356
357     filter = (text$: Observable<string>): Observable<ComboboxEntry[]> => {
358         return text$.pipe(
359             debounceTime(200),
360             distinctUntilChanged(),
361
362             // Merge click actions in with the stream of text entry
363             merge(
364                 // Inject a specifier indicating the source of the
365                 // action is a user click instead of a text entry.
366                 // This tells the filter to show all values in sync mode.
367                 this.click$.pipe(filter(() =>
368                     !this.instance.isPopupOpen()
369                 )).pipe(mapTo('_CLICK_'))
370             ),
371
372             // mergeMap coalesces an observable into our stream.
373             mergeMap(term => this.addAsyncEntries(term)),
374             map((term: string) => {
375
376                 if (term === '' || term === '_CLICK_') {
377                     if (!this.asyncDataSource) {
378                         // In sync mode, a post-focus empty search or
379                         // click event displays the whole list.
380                         return this.entrylist;
381                     }
382                 }
383
384                 // Filter entrylist whose labels substring-match the
385                 // text entered.
386                 return this.entrylist.filter(entry => {
387                     const label = entry.label || entry.id;
388                     return label.toLowerCase().indexOf(term.toLowerCase()) > -1;
389                 });
390             })
391         );
392     }
393
394     writeValue(value: ComboboxEntry) {
395         if (value !== undefined && value !== null) {
396             this.startId = value.id;
397             this.applySelection();
398         }
399     }
400
401     registerOnChange(fn) {
402         this.propagateChange = fn;
403     }
404
405     registerOnTouched(fn) {
406         this.propagateTouch = fn;
407     }
408
409 }
410
411