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 {
44 showCombinedNames = false; // Managed via user/workstation setting
46 _selected: OrgDisplay;
47 set selected(s: OrgDisplay) {
48 if (s !== this._selected) {
51 // orgChanged() does not fire when the value is cleared,
52 // so emit the onChange here for cleared values only.
53 if (!s) { // may be '' or null
54 this._selected = null;
55 this.onChange.emit(null);
60 get selected(): OrgDisplay {
61 return this._selected;
64 click$ = new Subject<string>();
65 valueFromSetting: number = null;
66 sortedOrgs: IdlObject[] = [];
68 // Disable the entire input
69 @Input() disabled: boolean;
71 @ViewChild('instance', { static: false }) instance: NgbTypeahead;
73 // Placeholder text for selector input
74 @Input() placeholder = '';
76 // ID to display in the DOM for this selector
77 @Input() domId = 'eg-org-select-' + OrgSelectComponent.domId++;
81 // Org unit field displayed in the selector
82 @Input() displayField = 'shortname';
84 // if no initialOrg is provided, none could be found via persist
85 // setting, and no fallbackoOrg is provided, apply a sane default.
86 // First tries workstation org unit, then user home org unit.
87 // An onChange event WILL be generated when a default is applied.
88 @Input() applyDefault = false;
90 @Input() readOnly = false;
92 @Input() required = false;
94 // List of org unit IDs to exclude from the selector
95 hidden: number[] = [];
96 @Input() set hideOrgs(ids: number[]) {
97 if (ids) { this.hidden = ids; }
100 // List of org unit IDs to disable in the selector
101 _disabledOrgs: number[] = [];
102 @Input() set disableOrgs(ids: number[]) {
103 if (ids) { this._disabledOrgs = ids; }
106 get disableOrgs(): number[] {
107 return this._disabledOrgs;
110 // Apply an org unit value at load time.
111 // These will NOT result in an onChange event.
112 @Input() initialOrg: IdlObject;
113 @Input() initialOrgId: number;
115 // Value is persisted via server setting with this key.
116 // Key is prepended with 'eg.orgselect.'
117 @Input() persistKey: string;
119 // If no initialOrg is provided and no value could be found
120 // from a persist setting, fall back to one of these values.
121 // These WILL result in an onChange event
122 @Input() fallbackOrg: IdlObject;
123 @Input() fallbackOrgId: number;
125 // Modify the selected org unit via data binding.
126 // This WILL NOT result in an onChange event firing.
127 @Input() set applyOrg(org: IdlObject) {
128 this.selected = org ? this.formatForDisplay(org) : null;
131 // Modify the selected org unit by ID via data binding.
132 // This WILL NOT result in an onChange event firing.
133 @Input() set applyOrgId(id: number) {
134 this.selected = id ? this.formatForDisplay(this.org.get(id)) : null;
137 // Limit org unit display to those where the logged in user
138 // has the following permissions.
139 permLimitOrgs: number[];
140 @Input() set limitPerms(perms: string[]) {
141 this.applyPermLimitOrgs(perms);
144 // Function which should return a string value representing
145 // a CSS class name to use for styling each org unit label
147 @Input() orgClassCallback: (orgId: number) => string;
149 // Emitted when the org unit value is changed via the selector.
150 // Does not fire on initialOrg
151 @Output() onChange = new EventEmitter<IdlObject>();
153 // Emitted once when the component is done fetching settings
154 // and applying its initial value. For apps that use the value
155 // of this selector to load data, this event can be used to reliably
156 // detect when the selector is done with all of its automated
157 // underground shuffling and landed on a value.
158 @Output() componentLoaded: EventEmitter<void> = new EventEmitter<void>();
160 // convenience method to get an IdlObject representing the current
161 // selected org unit. One way of invoking this is via a template
162 // reference variable.
163 selectedOrg(): IdlObject {
164 if (this.selected == null) {
167 return this.org.get(this.selected.id);
170 selectedOrgId(): number {
171 return this.selected ? this.selected.id : null;
175 private auth: AuthService,
176 private store: StoreService,
177 private serverStore: ServerStoreService,
178 private org: OrgService,
179 private perm: PermService
181 this.orgClassCallback = (orgId: number): string => '';
187 let promise = this.persistKey ?
188 this.getFromSetting() : Promise.resolve(null);
190 promise = promise.then(startupOrg => {
191 return this.serverStore.getItem('eg.orgselect.show_combined_names')
193 const sortField = show ? 'name' : this.displayField;
195 // Sort the tree and reabsorb to propagate the sorted
196 // nodes to the org.list() used by this component.
197 // Maintain our own copy of the org list in case the
198 // org service is sorted in a different manner by other
199 // parts of the code.
200 this.org.sortTree(sortField);
201 this.org.absorbTree();
202 this.sortedOrgs = this.org.list();
204 this.showCombinedNames = show;
206 .then(_ => startupOrg);
209 promise.then((startupOrgId: number) => {
214 // A value may have been applied while we were
215 // talking to the network.
216 startupOrgId = this.selected.id;
218 } else if (this.initialOrg) {
219 startupOrgId = this.initialOrg.id();
221 } else if (this.initialOrgId) {
222 startupOrgId = this.initialOrgId;
224 } else if (this.fallbackOrgId) {
225 startupOrgId = this.fallbackOrgId;
227 } else if (this.fallbackOrg) {
228 startupOrgId = this.org.get(this.fallbackOrg).id();
230 } else if (this.applyDefault && this.auth.user()) {
231 startupOrgId = this.auth.user().ws_ou();
237 startupOrg = this.org.get(startupOrgId);
238 this.selected = this.formatForDisplay(startupOrg);
241 this.markAsLoaded(startupOrg);
245 getDisplayLabel(org: IdlObject): string {
246 if (this.showCombinedNames) {
247 return `${org.name()} (${org.shortname()})`;
249 return org[this.displayField]();
253 getFromSetting(): Promise<number> {
255 const key = `eg.orgselect.${this.persistKey}`;
257 return this.serverStore.getItem(key).then(
258 value => this.valueFromSetting = value
262 // Indicate all load-time shuffling has completed.
263 markAsLoaded(onChangeOrg?: IdlObject) {
264 setTimeout(() => { // Avoid emitting mid-digest
265 this.componentLoaded.emit();
266 this.componentLoaded.complete();
267 if (onChangeOrg) { this.onChange.emit(onChangeOrg); }
272 applyPermLimitOrgs(perms: string[]) {
278 // handle lazy clients that pass null perm names
279 perms = perms.filter(p => p !== null && p !== undefined);
281 if (perms.length === 0) {
285 // NOTE: If permLimitOrgs is useful in a non-staff context
286 // we need to change this to support non-staff perm checks.
287 this.perm.hasWorkPermAt(perms, true).then(permMap => {
289 // safari-friendly version of Array.flat()
290 Object.values(permMap).reduce((acc, val) => acc.concat(val), []);
294 // Format for display in the selector drop-down and input.
295 formatForDisplay(org: IdlObject): OrgDisplay {
296 let label = this.getDisplayLabel(org);
297 if (!this.readOnly) {
298 label = PAD_SPACE.repeat(org.ou_type().depth()) + label;
303 disabled : this.disableOrgs.includes(org.id())
307 // Fired by the typeahead to inform us of a change.
308 orgChanged(selEvent: NgbTypeaheadSelectItemEvent) {
309 // console.debug('org unit change occurred ' + selEvent.item);
310 this.onChange.emit(this.org.get(selEvent.item.id));
312 if (this.persistKey && this.valueFromSetting !== selEvent.item.id) {
313 // persistKey is active. Update the persisted value when changed.
315 const key = `eg.orgselect.${this.persistKey}`;
316 this.valueFromSetting = selEvent.item.id;
317 this.serverStore.setItem(key, this.valueFromSetting);
321 // Remove the tree-padding spaces when matching.
322 formatter = (result: OrgDisplay) => result ? result.label.trim() : '';
324 // reset the state of the component
326 this.selected = null;
329 // NgbTypeahead doesn't offer a way to style the dropdown
330 // button directly, so we have to reach up and style it ourselves.
331 applyDisableStyle() {
332 this.disableOrgs.forEach(id => {
333 const node = document.getElementById(`${this.domId}-${id}`);
335 const button = node.parentNode as HTMLElement;
336 button.classList.add('disabled');
341 // Free-text values are not allowed.
343 if (typeof this.selected === 'string') {
344 this.selected = null;
348 filter = (text$: Observable<string>): Observable<OrgDisplay[]> => {
352 distinctUntilChanged(),
354 // Inject a specifier indicating the source of the
355 // action is a user click
356 this.click$.pipe(filter(() => !this.instance.isPopupOpen()))
357 .pipe(mapTo('_CLICK_'))
361 let orgs = this.sortedOrgs.filter(org =>
362 this.hidden.filter(id => org.id() === id).length === 0
365 if (this.permLimitOrgs) {
366 // Avoid showing org units where the user does
367 // not have the requested permission.
368 orgs = orgs.filter(org =>
369 this.permLimitOrgs.includes(org.id()));
372 if (term !== '_CLICK_') {
373 // For search-driven events, limit to the matching
375 orgs = orgs.filter(org => {
376 return term === '' || // show all
377 this.getDisplayLabel(org)
378 .toLowerCase().indexOf(term.toLowerCase()) > -1;
383 // Give the typeahead a chance to open before applying
384 // the disabled org unit styling.
385 setTimeout(() => this.applyDisableStyle());
387 return orgs.map(org => this.formatForDisplay(org));