]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/combobox/combobox.component.ts
2664112c78beaaf09eaa6e8545479137349b5d2d
[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     hasEntry(entryId: any): boolean {
214         return this.entrylist.filter(e => e.id === entryId)[0] !== undefined;
215     }
216
217     onBlur() {
218         // When the selected value is a string it means we have either
219         // no value (user cleared the input) or a free-text value.
220
221         if (typeof this.selected === 'string') {
222
223             if (this.allowFreeText && this.selected !== '') {
224                 // Free text entered which does not match a known entry
225                 // translate it into a dummy ComboboxEntry
226                 this.selected = {
227                     id: null,
228                     label: this.selected,
229                     freetext: true
230                 };
231
232             } else {
233
234                 this.selected = null;
235             }
236
237             // Manually fire the onchange since NgbTypeahead fails
238             // to fire the onchange when the value is cleared.
239             this.selectorChanged(
240                 {item: this.selected, preventDefault: () => true});
241         }
242         this.propagateTouch();
243     }
244
245     // Fired by the typeahead to inform us of a change.
246     selectorChanged(selEvent: NgbTypeaheadSelectItemEvent) {
247         this.onChange.emit(selEvent.item);
248         this.propagateChange(selEvent.item);
249     }
250
251     // Adds matching async entries to the entry list
252     // and propagates the search term for pipelining.
253     addAsyncEntries(term: string): Observable<string> {
254
255         if (!term || !this.asyncDataSource) {
256             return of(term);
257         }
258
259         let searchTerm: string;
260         searchTerm = term;
261         if (searchTerm === '_CLICK_' && this.asyncSupportsEmptyTermClick) {
262             searchTerm = '';
263         }
264
265         return new Observable(observer => {
266             this.asyncDataSource(searchTerm).subscribe(
267                 (entry: ComboboxEntry) => this.addAsyncEntry(entry),
268                 err => {},
269                 ()  => {
270                     observer.next(searchTerm);
271                     observer.complete();
272                 }
273             );
274         });
275     }
276
277     filter = (text$: Observable<string>): Observable<ComboboxEntry[]> => {
278         return text$.pipe(
279             debounceTime(200),
280             distinctUntilChanged(),
281
282             // Merge click actions in with the stream of text entry
283             merge(
284                 // Inject a specifier indicating the source of the
285                 // action is a user click instead of a text entry.
286                 // This tells the filter to show all values in sync mode.
287                 this.click$.pipe(filter(() =>
288                     !this.instance.isPopupOpen()
289                 )).pipe(mapTo('_CLICK_'))
290             ),
291
292             // mergeMap coalesces an observable into our stream.
293             mergeMap(term => this.addAsyncEntries(term)),
294             map((term: string) => {
295
296                 if (term === '' || term === '_CLICK_') {
297                     if (!this.asyncDataSource) {
298                         // In sync mode, a post-focus empty search or
299                         // click event displays the whole list.
300                         return this.entrylist;
301                     }
302                 }
303
304                 // Filter entrylist whose labels substring-match the
305                 // text entered.
306                 return this.entrylist.filter(entry => {
307                     const label = entry.label || entry.id;
308                     return label.toLowerCase().indexOf(term.toLowerCase()) > -1;
309                 });
310             })
311         );
312     }
313
314     writeValue(value: ComboboxEntry) {
315         if (value !== undefined && value !== null) {
316             this.startId = value.id;
317             this.applySelection();
318         }
319     }
320
321     registerOnChange(fn) {
322         this.propagateChange = fn;
323     }
324
325     registerOnTouched(fn) {
326         this.propagateTouch = fn;
327     }
328
329 }
330
331