1 /** TODO PORT ME TO <eg-combobox> */
2 import {Component, OnInit, Input, Output, ViewChild, EventEmitter} from '@angular/core';
3 import {Observable, Subject} from 'rxjs';
4 import {map, mapTo, debounceTime, distinctUntilChanged, merge, filter} from 'rxjs/operators';
5 import {AuthService} from '@eg/core/auth.service';
6 import {StoreService} from '@eg/core/store.service';
7 import {ServerStoreService} from '@eg/core/server-store.service';
8 import {OrgService} from '@eg/core/org.service';
9 import {IdlObject} from '@eg/core/idl.service';
10 import {PermService} from '@eg/core/perm.service';
11 import {NgbTypeahead, NgbTypeaheadSelectItemEvent} from '@ng-bootstrap/ng-bootstrap';
15 * The following precedence is used when applying a load-time value
17 * 1. initialOrg / initialOrgId
18 * 2. Value from server setting specificed with persistKey (fires onload).
19 * 3. Value from fallbackOrg / fallbackOrgId (fires onload).
20 * 4. Default applyed when applyDefault is set (fires onload).
22 * Users can detect when the component has completed its load-time
23 * machinations by subscribing to the componentLoaded Output which
24 * fires exactly once when loading is completed.
27 // Use a unicode char for spacing instead of ASCII=32 so the browser
28 // won't collapse the nested display entries down to a single space.
29 const PAD_SPACE = ' '; // U+2007
31 interface OrgDisplay {
38 selector: 'eg-org-select',
39 templateUrl: './org-select.component.html'
41 export class OrgSelectComponent implements OnInit {
45 click$ = new Subject<string>();
46 valueFromSetting: number = null;
47 sortedOrgs: IdlObject[] = [];
49 // Disable the entire input
50 @Input() disabled: boolean;
52 @ViewChild('instance', { static: false }) instance: NgbTypeahead;
54 // Placeholder text for selector input
55 @Input() placeholder = '';
57 // ID to display in the DOM for this selector
58 @Input() domId = 'eg-org-select-' + OrgSelectComponent.domId++;
60 // Org unit field displayed in the selector
61 @Input() displayField = 'shortname';
63 // if no initialOrg is provided, none could be found via persist
64 // setting, and no fallbackoOrg is provided, apply a sane default.
65 // First tries workstation org unit, then user home org unit.
66 // An onChange event WILL be generated when a default is applied.
67 @Input() applyDefault = false;
69 @Input() readOnly = false;
71 // List of org unit IDs to exclude from the selector
72 hidden: number[] = [];
73 @Input() set hideOrgs(ids: number[]) {
74 if (ids) { this.hidden = ids; }
77 // List of org unit IDs to disable in the selector
78 _disabledOrgs: number[] = [];
79 @Input() set disableOrgs(ids: number[]) {
80 if (ids) { this._disabledOrgs = ids; }
83 get disableOrgs(): number[] {
84 return this._disabledOrgs;
87 // Apply an org unit value at load time.
88 // These will NOT result in an onChange event.
89 @Input() initialOrg: IdlObject;
90 @Input() initialOrgId: number;
92 // Value is persisted via server setting with this key.
93 // Key is prepended with 'eg.orgselect.'
94 @Input() persistKey: string;
96 // If no initialOrg is provided and no value could be found
97 // from a persist setting, fall back to one of these values.
98 // These WILL result in an onChange event
99 @Input() fallbackOrg: IdlObject;
100 @Input() fallbackOrgId: number;
102 // Modify the selected org unit via data binding.
103 // This WILL NOT result in an onChange event firing.
104 @Input() set applyOrg(org: IdlObject) {
105 this.selected = org ? this.formatForDisplay(org) : null;
108 // Modify the selected org unit by ID via data binding.
109 // This WILL NOT result in an onChange event firing.
110 @Input() set applyOrgId(id: number) {
111 this.selected = id ? this.formatForDisplay(this.org.get(id)) : null;
114 // Limit org unit display to those where the logged in user
115 // has the following permissions.
116 permLimitOrgs: number[];
117 @Input() set limitPerms(perms: string[]) {
118 this.applyPermLimitOrgs(perms);
121 // Emitted when the org unit value is changed via the selector.
122 // Does not fire on initialOrg
123 @Output() onChange = new EventEmitter<IdlObject>();
125 // Emitted once when the component is done fetching settings
126 // and applying its initial value. For apps that use the value
127 // of this selector to load data, this event can be used to reliably
128 // detect when the selector is done with all of its automated
129 // underground shuffling and landed on a value.
130 @Output() componentLoaded: EventEmitter<void> = new EventEmitter<void>();
132 // convenience method to get an IdlObject representing the current
133 // selected org unit. One way of invoking this is via a template
134 // reference variable.
135 selectedOrg(): IdlObject {
136 if (this.selected == null) {
139 return this.org.get(this.selected.id);
143 private auth: AuthService,
144 private store: StoreService,
145 private serverStore: ServerStoreService,
146 private org: OrgService,
147 private perm: PermService
152 // Sort the tree and reabsorb to propagate the sorted nodes to
153 // the org.list() used by this component. Maintain our own
154 // copy of the org list in case the org service is sorted in a
155 // different manner by other parts of the code.
156 this.org.sortTree(this.displayField);
157 this.org.absorbTree();
158 this.sortedOrgs = this.org.list();
160 const promise = this.persistKey ?
161 this.getFromSetting() : Promise.resolve(null);
163 promise.then((startupOrgId: number) => {
168 // A value may have been applied while we were
169 // talking to the network.
170 startupOrgId = this.selected.id;
172 } else if (this.initialOrg) {
173 startupOrgId = this.initialOrg.id();
175 } else if (this.initialOrgId) {
176 startupOrgId = this.initialOrgId;
178 } else if (this.fallbackOrgId) {
179 startupOrgId = this.fallbackOrgId;
181 } else if (this.fallbackOrg) {
182 startupOrgId = this.org.get(this.fallbackOrg).id();
184 } else if (this.applyDefault && this.auth.user()) {
185 startupOrgId = this.auth.user().ws_ou();
191 startupOrg = this.org.get(startupOrgId);
192 this.selected = this.formatForDisplay(startupOrg);
195 this.markAsLoaded(startupOrg);
199 getFromSetting(): Promise<number> {
201 const key = `eg.orgselect.${this.persistKey}`;
203 return this.serverStore.getItem(key).then(
204 value => this.valueFromSetting = value
208 // Indicate all load-time shuffling has completed.
209 markAsLoaded(onChangeOrg?: IdlObject) {
210 setTimeout(() => { // Avoid emitting mid-digest
211 this.componentLoaded.emit();
212 this.componentLoaded.complete();
213 if (onChangeOrg) { this.onChange.emit(onChangeOrg); }
218 applyPermLimitOrgs(perms: string[]) {
224 // handle lazy clients that pass null perm names
225 perms = perms.filter(p => p !== null && p !== undefined);
227 if (perms.length === 0) {
231 // NOTE: If permLimitOrgs is useful in a non-staff context
232 // we need to change this to support non-staff perm checks.
233 this.perm.hasWorkPermAt(perms, true).then(permMap => {
235 // safari-friendly version of Array.flat()
236 Object.values(permMap).reduce((acc, val) => acc.concat(val), []);
240 // Format for display in the selector drop-down and input.
241 formatForDisplay(org: IdlObject): OrgDisplay {
242 let label = org[this.displayField]();
243 if (!this.readOnly) {
244 label = PAD_SPACE.repeat(org.ou_type().depth()) + label;
249 disabled : this.disableOrgs.includes(org.id())
253 // Fired by the typeahead to inform us of a change.
254 // TODO: this does not fire when the value is cleared :( -- implement
255 // change detection on this.selected to look specifically for NULL.
256 orgChanged(selEvent: NgbTypeaheadSelectItemEvent) {
257 // console.debug('org unit change occurred ' + selEvent.item);
258 this.onChange.emit(this.org.get(selEvent.item.id));
260 if (this.persistKey && this.valueFromSetting !== selEvent.item.id) {
261 // persistKey is active. Update the persisted value when changed.
263 const key = `eg.orgselect.${this.persistKey}`;
264 this.valueFromSetting = selEvent.item.id;
265 this.serverStore.setItem(key, this.valueFromSetting);
269 // Remove the tree-padding spaces when matching.
270 formatter = (result: OrgDisplay) => result ? result.label.trim() : '';
272 // reset the state of the component
274 this.selected = null;
277 // NgbTypeahead doesn't offer a way to style the dropdown
278 // button directly, so we have to reach up and style it ourselves.
279 applyDisableStyle() {
280 this.disableOrgs.forEach(id => {
281 const node = document.getElementById(`${this.domId}-${id}`);
283 const button = node.parentNode as HTMLElement;
284 button.classList.add('disabled');
289 filter = (text$: Observable<string>): Observable<OrgDisplay[]> => {
293 distinctUntilChanged(),
295 // Inject a specifier indicating the source of the
296 // action is a user click
297 this.click$.pipe(filter(() => !this.instance.isPopupOpen()))
298 .pipe(mapTo('_CLICK_'))
302 let orgs = this.sortedOrgs.filter(org =>
303 this.hidden.filter(id => org.id() === id).length === 0
306 if (this.permLimitOrgs) {
307 // Avoid showing org units where the user does
308 // not have the requested permission.
309 orgs = orgs.filter(org =>
310 this.permLimitOrgs.includes(org.id()));
313 if (term !== '_CLICK_') {
314 // For search-driven events, limit to the matching
316 orgs = orgs.filter(org => {
317 return term === '' || // show all
318 org[this.displayField]()
319 .toLowerCase().indexOf(term.toLowerCase()) > -1;
324 // Give the typeahead a chance to open before applying
325 // the disabled org unit styling.
326 setTimeout(() => this.applyDisableStyle());
328 return orgs.map(org => this.formatForDisplay(org));