]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/org-select/org-select.component.ts
LP1807523: Associating labels and inputs in angular fmeditor
[working/Evergreen.git] / Open-ILS / src / eg2 / src / app / share / org-select / org-select.component.ts
1 /** TODO PORT ME TO <eg-combobox> */
2 import {Component, OnInit, Input, Output, ViewChild, EventEmitter} from '@angular/core';
3 import {Observable} from 'rxjs/Observable';
4 import {map} from 'rxjs/operators/map';
5 import {mapTo} from 'rxjs/operators/mapTo';
6 import {debounceTime} from 'rxjs/operators/debounceTime';
7 import {distinctUntilChanged} from 'rxjs/operators/distinctUntilChanged';
8 import {merge} from 'rxjs/operators/merge';
9 import {filter} from 'rxjs/operators/filter';
10 import {Subject} from 'rxjs/Subject';
11 import {AuthService} from '@eg/core/auth.service';
12 import {StoreService} from '@eg/core/store.service';
13 import {OrgService} from '@eg/core/org.service';
14 import {IdlObject} from '@eg/core/idl.service';
15 import {PermService} from '@eg/core/perm.service';
16 import {NgbTypeahead, NgbTypeaheadSelectItemEvent} from '@ng-bootstrap/ng-bootstrap';
17
18 // Use a unicode char for spacing instead of ASCII=32 so the browser
19 // won't collapse the nested display entries down to a single space.
20 const PAD_SPACE = ' '; // U+2007
21
22 interface OrgDisplay {
23   id: number;
24   label: string;
25   disabled: boolean;
26 }
27
28 @Component({
29   selector: 'eg-org-select',
30   templateUrl: './org-select.component.html'
31 })
32 export class OrgSelectComponent implements OnInit {
33
34     selected: OrgDisplay;
35     hidden: number[] = [];
36     disabled: number[] = [];
37     click$ = new Subject<string>();
38     startOrg: IdlObject;
39
40     @ViewChild('instance') instance: NgbTypeahead;
41
42     // Placeholder text for selector input
43     @Input() placeholder = '';
44     @Input() stickySetting: string;
45
46     // ID to display in the DOM for this selector
47     @Input() domId = '';
48
49     // Org unit field displayed in the selector
50     @Input() displayField = 'shortname';
51
52     // Apply a default org unit value when none is set.
53     // First tries workstation org unit, then user home org unit.
54     // An onChange event WILL be generated when a default is applied.
55     @Input() applyDefault = false;
56
57     // List of org unit IDs to exclude from the selector
58     @Input() set hideOrgs(ids: number[]) {
59         if (ids) { this.hidden = ids; }
60     }
61
62     // List of org unit IDs to disable in the selector
63     @Input() set disableOrgs(ids: number[]) {
64         if (ids) { this.disabled = ids; }
65     }
66
67     // Apply an org unit value at load time.
68     // This will NOT result in an onChange event.
69     @Input() set initialOrg(org: IdlObject) {
70         if (org) { this.startOrg = org; }
71     }
72
73     // Apply an org unit value by ID at load time.
74     // This will NOT result in an onChange event.
75     @Input() set initialOrgId(id: number) {
76         if (id) { this.startOrg = this.org.get(id); }
77     }
78
79     // Modify the selected org unit via data binding.
80     // This WILL result in an onChange event firing.
81     @Input() set applyOrg(org: IdlObject) {
82         if (org) {
83             this.selected = this.formatForDisplay(org);
84         }
85     }
86
87     permLimitOrgs: number[];
88     @Input() set limitPerms(perms: string[]) {
89         this.applyPermLimitOrgs(perms);
90     }
91
92     // Modify the selected org unit by ID via data binding.
93     // This WILL result in an onChange event firing.
94     @Input() set applyOrgId(id: number) {
95         if (id) {
96             this.selected = this.formatForDisplay(this.org.get(id));
97         }
98     }
99
100     // Emitted when the org unit value is changed via the selector.
101     // Does not fire on initialOrg
102     @Output() onChange = new EventEmitter<IdlObject>();
103
104     constructor(
105       private auth: AuthService,
106       private store: StoreService,
107       private org: OrgService,
108       private perm: PermService
109     ) { }
110
111     ngOnInit() {
112
113         // Apply a default org unit if desired and possible.
114         if (!this.startOrg && this.applyDefault && this.auth.user()) {
115             // note: ws_ou defaults to home_ou on the server
116             // when when no workstation is used
117             this.startOrg = this.org.get(this.auth.user().ws_ou());
118             this.selected = this.formatForDisplay(
119                 this.org.get(this.auth.user().ws_ou())
120             );
121
122             // avoid notifying mid-digest
123             setTimeout(() => this.onChange.emit(this.startOrg), 0);
124         }
125
126         if (this.startOrg) {
127             this.selected = this.formatForDisplay(this.startOrg);
128         }
129     }
130
131     //
132     applyPermLimitOrgs(perms: string[]) {
133
134         if (!perms) {
135             return;
136         }
137
138         // handle lazy clients that pass null perm names
139         perms = perms.filter(p => p !== null && p !== undefined);
140
141         if (perms.length === 0) {
142             return;
143         }
144
145         // NOTE: If permLimitOrgs is useful in a non-staff context
146         // we need to change this to support non-staff perm checks.
147         this.perm.hasWorkPermAt(perms, true).then(permMap => {
148             this.permLimitOrgs =
149                 // safari-friendly version of Array.flat()
150                 Object.values(permMap).reduce((acc, val) => acc.concat(val), []);
151         });
152     }
153
154     // Format for display in the selector drop-down and input.
155     formatForDisplay(org: IdlObject): OrgDisplay {
156         return {
157             id : org.id(),
158             label : PAD_SPACE.repeat(org.ou_type().depth())
159               + org[this.displayField](),
160             disabled : false
161         };
162     }
163
164     // Fired by the typeahead to inform us of a change.
165     // TODO: this does not fire when the value is cleared :( -- implement
166     // change detection on this.selected to look specifically for NULL.
167     orgChanged(selEvent: NgbTypeaheadSelectItemEvent) {
168         // console.debug('org unit change occurred ' + selEvent.item);
169         this.onChange.emit(this.org.get(selEvent.item.id));
170     }
171
172     // Remove the tree-padding spaces when matching.
173     formatter = (result: OrgDisplay) => result.label.trim();
174
175     filter = (text$: Observable<string>): Observable<OrgDisplay[]> => {
176         return text$.pipe(
177             debounceTime(200),
178             distinctUntilChanged(),
179             merge(
180                 // Inject a specifier indicating the source of the
181                 // action is a user click
182                 this.click$.pipe(filter(() => !this.instance.isPopupOpen()))
183                 .pipe(mapTo('_CLICK_'))
184             ),
185             map(term => {
186
187                 let orgs = this.org.list().filter(org =>
188                     this.hidden.filter(id => org.id() === id).length === 0
189                 );
190
191                 if (this.permLimitOrgs) {
192                     // Avoid showing org units where the user does
193                     // not have the requested permission.
194                     orgs = orgs.filter(org =>
195                         this.permLimitOrgs.includes(org.id()));
196                 }
197
198                 if (term !== '_CLICK_') {
199                     // For search-driven events, limit to the matching
200                     // org units.
201                     orgs = orgs.filter(org => {
202                         return term === '' || // show all
203                             org[this.displayField]()
204                                 .toLowerCase().indexOf(term.toLowerCase()) > -1;
205
206                     });
207                 }
208
209                 return orgs.map(org => this.formatForDisplay(org));
210             })
211         );
212     }
213 }
214
215