]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/combobox/combobox.component.ts
LP1825851 Combobox display template option
[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') 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     // Add a 'required' attribute to the input
56     isRequired: boolean;
57     @Input() set required(r: boolean) {
58         this.isRequired = r;
59     }
60
61     // Disable the input
62     isDisabled: boolean;
63     @Input() set disabled(d: boolean) {
64         this.isDisabled = d;
65     }
66
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;
72
73     @Input() idlClass: string;
74     @Input() idlField: string;
75     @Input() asyncDataSource: (term: string) => Observable<ComboboxEntry>;
76
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;
82
83     // Useful for efficiently preventing duplicate async entries
84     asyncIds: {[idx: string]: boolean};
85
86     // True if a default selection has been made.
87     defaultSelectionApplied: boolean;
88
89     @Input() set entries(el: ComboboxEntry[]) {
90         if (el) {
91             this.entrylist = el;
92             this.applySelection();
93
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.
98             this.asyncIds = {};
99             el.forEach(entry => this.asyncIds['' + entry.id] = true);
100         }
101     }
102
103     // When provided use this as the display template for each entry.
104     @Input() displayTemplate: TemplateRef<any>;
105
106     // Emitted when the value is changed via UI.
107     // When the UI value is cleared, null is emitted.
108     @Output() onChange: EventEmitter<ComboboxEntry>;
109
110     // Useful for massaging the match string prior to comparison
111     // and display.  Default version trims leading/trailing spaces.
112     formatDisplayString: (e: ComboboxEntry) => string;
113
114     // Stub functions required by ControlValueAccessor
115     propagateChange = (_: any) => {};
116     propagateTouch = () => {};
117
118     constructor(
119       private elm: ElementRef,
120       private store: StoreService,
121       private idl: IdlService,
122       private pcrud: PcrudService,
123     ) {
124         this.entrylist = [];
125         this.asyncIds = {};
126         this.click$ = new Subject<string>();
127         this.onChange = new EventEmitter<ComboboxEntry>();
128         this.defaultSelectionApplied = false;
129
130         this.formatDisplayString = (result: ComboboxEntry) => {
131             const display = result.label || result.id;
132             return (display + '').trim();
133         };
134     }
135
136     ngOnInit() {
137         if (this.idlClass) {
138             const classDef = this.idl.classes[this.idlClass];
139             const pkeyField = classDef.pkey;
140
141             if (!pkeyField) {
142                 throw new Error(`IDL class ${this.idlClass} has no pkey field`);
143             }
144
145             if (!this.idlField) {
146                 this.idlField = classDef.field_map[classDef.pkey].selector || 'name';
147             }
148
149             this.asyncDataSource = term => {
150                 const field = this.idlField;
151                 const args = {};
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]()};
157                 }));
158             };
159         }
160     }
161
162     onClick($event) {
163         this.click$.next($event.target.value);
164     }
165
166     openMe($event) {
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(''));
171     }
172
173     // Apply a default selection where needed
174     applySelection() {
175
176         if (this.startId &&
177             this.entrylist && !this.defaultSelectionApplied) {
178
179             const entry =
180                 this.entrylist.filter(e => e.id === this.startId)[0];
181
182             if (entry) {
183                 this.selected = entry;
184                 this.defaultSelectionApplied = true;
185                 if (this.startIdFiresOnChange) {
186                     this.selectorChanged(
187                         {item: this.selected, preventDefault: () => true});
188                 }
189             }
190         }
191     }
192
193     // Called by combobox-entry.component
194     addEntry(entry: ComboboxEntry) {
195         this.entrylist.push(entry);
196         this.applySelection();
197     }
198
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];
203     }
204
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);
210         }
211     }
212
213     onBlur() {
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.
216
217         if (typeof this.selected === 'string') {
218
219             if (this.allowFreeText && this.selected !== '') {
220                 // Free text entered which does not match a known entry
221                 // translate it into a dummy ComboboxEntry
222                 this.selected = {
223                     id: null,
224                     label: this.selected,
225                     freetext: true
226                 };
227
228             } else {
229
230                 this.selected = null;
231             }
232
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});
237         }
238         this.propagateTouch();
239     }
240
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);
245     }
246
247     // Adds matching async entries to the entry list
248     // and propagates the search term for pipelining.
249     addAsyncEntries(term: string): Observable<string> {
250
251         if (!term || !this.asyncDataSource) {
252             return of(term);
253         }
254
255         let searchTerm: string;
256         searchTerm = term;
257         if (searchTerm === '_CLICK_' && this.asyncSupportsEmptyTermClick) {
258             searchTerm = '';
259         }
260
261         return new Observable(observer => {
262             this.asyncDataSource(searchTerm).subscribe(
263                 (entry: ComboboxEntry) => this.addAsyncEntry(entry),
264                 err => {},
265                 ()  => {
266                     observer.next(searchTerm);
267                     observer.complete();
268                 }
269             );
270         });
271     }
272
273     filter = (text$: Observable<string>): Observable<ComboboxEntry[]> => {
274         return text$.pipe(
275             debounceTime(200),
276             distinctUntilChanged(),
277
278             // Merge click actions in with the stream of text entry
279             merge(
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_'))
286             ),
287
288             // mergeMap coalesces an observable into our stream.
289             mergeMap(term => this.addAsyncEntries(term)),
290             map((term: string) => {
291
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;
297                     }
298                 }
299
300                 // Filter entrylist whose labels substring-match the
301                 // text entered.
302                 return this.entrylist.filter(entry => {
303                     const label = entry.label || entry.id;
304                     return label.toLowerCase().indexOf(term.toLowerCase()) > -1;
305                 });
306             })
307         );
308     }
309
310     writeValue(value: ComboboxEntry) {
311         if (value !== undefined && value !== null) {
312             this.startId = value.id;
313             this.applySelection();
314         }
315     }
316
317     registerOnChange(fn) {
318         this.propagateChange = fn;
319     }
320
321     registerOnTouched(fn) {
322         this.propagateTouch = fn;
323     }
324
325 }
326
327