]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/combobox/combobox.component.ts
LP1850555 Angular Item (Copy) Location Select Component
[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   userdata?: any; // opaque external value; ignored by this component.
22 }
23
24 @Component({
25   selector: 'eg-combobox',
26   templateUrl: './combobox.component.html',
27   styles: [`
28     .icons {margin-left:-18px}
29     .material-icons {font-size: 16px;font-weight:bold}
30   `],
31   providers: [{
32     provide: NG_VALUE_ACCESSOR,
33     useExisting: forwardRef(() => ComboboxComponent),
34     multi: true
35   }]
36 })
37 export class ComboboxComponent implements ControlValueAccessor, OnInit {
38
39     selected: ComboboxEntry;
40     click$: Subject<string>;
41     entrylist: ComboboxEntry[];
42
43     @ViewChild('instance', { static: true }) instance: NgbTypeahead;
44
45     // Applies a name attribute to the input.
46     // Useful in forms.
47     @Input() name: string;
48
49     // Placeholder text for selector input
50     @Input() placeholder = '';
51
52     @Input() persistKey: string; // TODO
53
54     @Input() allowFreeText = false;
55
56     @Input() inputSize: number = null;
57
58     // Add a 'required' attribute to the input
59     isRequired: boolean;
60     @Input() set required(r: boolean) {
61         this.isRequired = r;
62     }
63
64     // Disable the input
65     isDisabled: boolean;
66     @Input() set disabled(d: boolean) {
67         this.isDisabled = d;
68     }
69
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;
75
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; }
80
81         // clear on explicit null
82         if (id === null) { this.selected = null; }
83
84         if (this.entrylist.length) {
85             this.selected = this.entrylist.filter(e => e.id === id)[0];
86         }
87
88         if (!this.selected) {
89             // It's possible the selected ID lives in a set of entries
90             // that are yet to be provided.
91             this.startId = id;
92         }
93     }
94
95     get selectedId(): any {
96         return this.selected ? this.selected.id : null;
97     }
98
99     @Input() idlClass: string;
100     @Input() idlField: string;
101     @Input() idlIncludeLibraryInLabel: string;
102     @Input() asyncDataSource: (term: string) => Observable<ComboboxEntry>;
103
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;
109
110     // Useful for efficiently preventing duplicate async entries
111     asyncIds: {[idx: string]: boolean};
112
113     // True if a default selection has been made.
114     defaultSelectionApplied: boolean;
115
116     @Input() set entries(el: ComboboxEntry[]) {
117         if (el) {
118
119             if (this.entrylistMatches(el)) {
120                 // Avoid reprocessing data we already have.
121                 return;
122             }
123
124             this.entrylist = el;
125
126             // new set of entries essentially means a new instance. reset.
127             this.defaultSelectionApplied = false;
128             this.applySelection();
129
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.
134             this.asyncIds = {};
135             el.forEach(entry => this.asyncIds['' + entry.id] = true);
136         }
137     }
138
139     // When provided use this as the display template for each entry.
140     @Input() displayTemplate: TemplateRef<any>;
141
142     // Emitted when the value is changed via UI.
143     // When the UI value is cleared, null is emitted.
144     @Output() onChange: EventEmitter<ComboboxEntry>;
145
146     // Useful for massaging the match string prior to comparison
147     // and display.  Default version trims leading/trailing spaces.
148     formatDisplayString: (e: ComboboxEntry) => string;
149
150     // Stub functions required by ControlValueAccessor
151     propagateChange = (_: any) => {};
152     propagateTouch = () => {};
153
154     constructor(
155       private elm: ElementRef,
156       private store: StoreService,
157       private idl: IdlService,
158       private pcrud: PcrudService,
159     ) {
160         this.entrylist = [];
161         this.asyncIds = {};
162         this.click$ = new Subject<string>();
163         this.onChange = new EventEmitter<ComboboxEntry>();
164         this.defaultSelectionApplied = false;
165
166         this.formatDisplayString = (result: ComboboxEntry) => {
167             const display = result.label || result.id;
168             return (display + '').trim();
169         };
170     }
171
172     ngOnInit() {
173         if (this.idlClass) {
174             const classDef = this.idl.classes[this.idlClass];
175             const pkeyField = classDef.pkey;
176
177             if (!pkeyField) {
178                 throw new Error(`IDL class ${this.idlClass} has no pkey field`);
179             }
180
181             if (!this.idlField) {
182                 this.idlField = this.idl.getClassSelector(this.idlClass);
183             }
184
185             this.asyncDataSource = term => {
186                 const field = this.idlField;
187                 const args = {};
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 => {
197                         return {
198                             id: data[pkeyField](),
199                             label: data[field]() + ' (' + data[this.idlIncludeLibraryInLabel]().shortname() + ')'
200                         };
201                     }));
202                 } else {
203                     return this.pcrud.search(this.idlClass, args, extra_args).pipe(map(data => {
204                         return {id: data[pkeyField](), label: data[field]()};
205                     }));
206                 }
207             };
208         }
209     }
210
211     onClick($event) {
212         this.click$.next($event.target.value);
213     }
214
215     openMe($event) {
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(''));
220     }
221
222     // Returns true if the 2 entries are equivalent.
223     entriesMatch(e1: ComboboxEntry, e2: ComboboxEntry): boolean {
224         return (
225             e1 && e2 &&
226             e1.id === e2.id &&
227             e1.label === e2.label &&
228             e1.freetext === e2.freetext
229         );
230     }
231
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;
239         }
240         if (el.length !== this.entrylist.length) {
241             return false;
242         }
243         for (let i = 0; i < el.length; i++) {
244             const mine = this.entrylist[i];
245             if (!mine || !this.entriesMatch(mine, el[i])) {
246                 return false;
247             }
248         }
249         return true;
250     }
251
252     // Apply a default selection where needed
253     applySelection() {
254
255         if (this.startId !== null &&
256             this.entrylist && !this.defaultSelectionApplied) {
257
258             const entry =
259                 this.entrylist.filter(e => e.id === this.startId)[0];
260
261             if (entry) {
262                 this.selected = entry;
263                 this.defaultSelectionApplied = true;
264                 if (this.startIdFiresOnChange) {
265                     this.selectorChanged(
266                         {item: this.selected, preventDefault: () => true});
267                 }
268             }
269         }
270     }
271
272     // Called by combobox-entry.component
273     addEntry(entry: ComboboxEntry) {
274         this.entrylist.push(entry);
275         this.applySelection();
276     }
277
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];
283     }
284
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);
290         }
291     }
292
293     hasEntry(entryId: any): boolean {
294         return this.entrylist.filter(e => e.id === entryId)[0] !== undefined;
295     }
296
297     onBlur() {
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.
300
301         if (typeof this.selected === 'string') {
302
303             if (this.allowFreeText && this.selected !== '') {
304                 // Free text entered which does not match a known entry
305                 // translate it into a dummy ComboboxEntry
306                 this.selected = {
307                     id: null,
308                     label: this.selected,
309                     freetext: true
310                 };
311
312             } else {
313
314                 this.selected = null;
315             }
316
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});
321         }
322         this.propagateTouch();
323     }
324
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);
329     }
330
331     // Adds matching async entries to the entry list
332     // and propagates the search term for pipelining.
333     addAsyncEntries(term: string): Observable<string> {
334
335         if (!term || !this.asyncDataSource) {
336             return of(term);
337         }
338
339         let searchTerm: string;
340         searchTerm = term;
341         if (searchTerm === '_CLICK_') {
342             if (this.asyncSupportsEmptyTermClick) {
343                 searchTerm = '';
344             } else {
345                 return of();
346             }
347         }
348
349         return new Observable(observer => {
350             this.asyncDataSource(searchTerm).subscribe(
351                 (entry: ComboboxEntry) => this.addAsyncEntry(entry),
352                 err => {},
353                 ()  => {
354                     observer.next(searchTerm);
355                     observer.complete();
356                 }
357             );
358         });
359     }
360
361     filter = (text$: Observable<string>): Observable<ComboboxEntry[]> => {
362         return text$.pipe(
363             debounceTime(200),
364             distinctUntilChanged(),
365
366             // Merge click actions in with the stream of text entry
367             merge(
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_'))
374             ),
375
376             // mergeMap coalesces an observable into our stream.
377             mergeMap(term => this.addAsyncEntries(term)),
378             map((term: string) => {
379
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;
385                     }
386                 }
387
388                 // Filter entrylist whose labels substring-match the
389                 // text entered.
390                 return this.entrylist.filter(entry => {
391                     const label = entry.label || entry.id;
392                     return label.toLowerCase().indexOf(term.toLowerCase()) > -1;
393                 });
394             })
395         );
396     }
397
398     writeValue(value: ComboboxEntry) {
399         if (value !== undefined && value !== null) {
400             this.startId = value.id;
401             this.applySelection();
402         }
403     }
404
405     registerOnChange(fn) {
406         this.propagateChange = fn;
407     }
408
409     registerOnTouched(fn) {
410         this.propagateTouch = fn;
411     }
412
413 }
414
415