2 import {timer as observableTimer, Observable, of} from 'rxjs';
3 import {Component, OnInit, ViewChild, Input, TemplateRef} from '@angular/core';
4 import {ProgressDialogComponent} from '@eg/share/dialog/progress.component';
5 import {ToastService} from '@eg/share/toast/toast.service';
6 import {StringService} from '@eg/share/string/string.service';
7 import {map, take} from 'rxjs/operators';
8 import {GridDataSource, GridColumn, GridRowFlairEntry} from '@eg/share/grid/grid';
9 import {IdlService, IdlObject} from '@eg/core/idl.service';
10 import {PcrudService} from '@eg/core/pcrud.service';
11 import {OrgService} from '@eg/core/org.service';
12 import {Pager} from '@eg/share/util/pager';
13 import {DateSelectComponent} from '@eg/share/date-select/date-select.component';
14 import {PrintService} from '@eg/share/print/print.service';
15 import {ComboboxEntry} from '@eg/share/combobox/combobox.component';
16 import {FmRecordEditorComponent} from '@eg/share/fm-editor/fm-editor.component';
17 import {NgbDate} from '@ng-bootstrap/ng-bootstrap';
18 import {FormGroup, FormControl} from '@angular/forms';
19 import {ConfirmDialogComponent} from '@eg/share/dialog/confirm.component';
20 import {FormatService} from '@eg/core/format.service';
21 import {StringComponent} from '@eg/share/string/string.component';
22 import {GridComponent} from '@eg/share/grid/grid.component';
23 import * as Moment from 'moment-timezone';
26 templateUrl: 'sandbox.component.html',
27 styles: ['.date-time-input.ng-invalid {border: 5px purple solid;}',
28 '.date-time-input.ng-valid {border: 5px green solid; animation: slide 5s linear 1s infinite alternate;}',
29 '@keyframes slide {0% {margin-left:0px;} 50% {margin-left:200px;}']
31 export class SandboxComponent implements OnInit {
33 @ViewChild('progressDialog')
34 private progressDialog: ProgressDialogComponent;
36 @ViewChild('dateSelect')
37 private dateSelector: DateSelectComponent;
39 @ViewChild('printTemplate')
40 private printTemplate: TemplateRef<any>;
42 @ViewChild('fmRecordEditor')
43 private fmRecordEditor: FmRecordEditorComponent;
45 @ViewChild('numConfirmDialog')
46 private numConfirmDialog: ConfirmDialogComponent;
50 @ViewChild('bresvEditor')
51 private bresvEditor: FmRecordEditorComponent;
54 // @ViewChild('helloStr') private helloStr: StringComponent;
56 gridDataSource: GridDataSource = new GridDataSource();
58 cbEntries: ComboboxEntry[];
59 // supplier of async combobox data
60 cbAsyncSource: (term: string) => Observable<ComboboxEntry>;
62 btSource: GridDataSource = new GridDataSource();
63 acpSource: GridDataSource = new GridDataSource();
64 editSelected: (rows: IdlObject[]) => void;
65 @ViewChild('acpGrid') acpGrid: GridComponent;
66 @ViewChild('acpEditDialog') editDialog: FmRecordEditorComponent;
67 @ViewChild('successString') successString: StringComponent;
68 @ViewChild('updateFailedString') updateFailedString: StringComponent;
69 world = 'world'; // for local template version
70 btGridTestContext: any = {hello : this.world};
77 @Input() set testString(str: string) {
85 dynamicTitleText: string;
87 badOrgForm: FormGroup;
89 ranganathan: FormGroup;
91 dateObject: Date = new Date();
93 simpleCombo: ComboboxEntry;
94 kingdom: ComboboxEntry;
96 complimentEvergreen: (rows: IdlObject[]) => void;
97 notOneSelectedRow: (rows: IdlObject[]) => boolean;
99 // selector field value on metarecord object
102 // cross-tab communications example
103 private sbChannel: any;
104 sbChannelText: string;
106 myTimeForm: FormGroup;
109 private idl: IdlService,
110 private org: OrgService,
111 private pcrud: PcrudService,
112 private strings: StringService,
113 private toast: ToastService,
114 private format: FormatService,
115 private printer: PrintService
117 // BroadcastChannel is not yet defined in PhantomJS and elsewhere
118 this.sbChannel = (typeof BroadcastChannel === 'undefined') ?
119 {} : new BroadcastChannel('eg.sbChannel');
120 this.sbChannel.onmessage = (e) => this.sbChannelHandler(e);
124 this.badOrgForm = new FormGroup({
125 'badOrgSelector': new FormControl(
126 {'id': 4, 'includeAncestors': false, 'includeDescendants': true}, (c: FormControl) => {
127 // An Angular custom validator
128 if (c.value.orgIds && c.value.orgIds.length > 5) {
129 return { tooMany: 'That\'s too many fancy libraries!' };
136 this.ranganathan = new FormGroup({
137 'law': new FormControl('second', (c: FormControl) => {
138 // An Angular custom validator
139 if ('wrong' === c.value.id || c.value.freetext) {
140 return { notALaw: 'That\'s not a real law of library science!' };
147 this.badOrgForm.get('badOrgSelector').valueChanges.subscribe(bad => {
148 this.toast.danger('The fanciest libraries are: ' + JSON.stringify(bad.orgIds));
151 this.ranganathan.get('law').valueChanges.subscribe(l => {
152 this.toast.success('You chose: ' + l.label);
155 this.kingdom = {id: 'Bacteria', label: 'Bacteria'};
157 this.gridDataSource.data = [
158 {name: 'Jane', state: 'AZ'},
159 {name: 'Al', state: 'CA'},
160 {name: 'The Tick', state: 'TX'}
163 this.pcrud.retrieveAll('cmrcfld', {order_by: {cmrcfld: 'name'}})
164 .subscribe(format => {
165 if (!this.cbEntries) { this.cbEntries = []; }
166 this.cbEntries.push({id: format.id(), label: format.name()});
169 this.cbAsyncSource = term => {
170 return this.pcrud.search(
172 {name: {'ilike': `%${term}%`}}, // could -or search on label
173 {order_by: {cmrcfld: 'name'}}
174 ).pipe(map(marcField => {
175 return {id: marcField.id(), label: marcField.name()};
179 this.btSource.getRows = (pager: Pager, sort: any[]) => {
181 const orderBy: any = {cbt: 'name'};
183 orderBy.cbt = sort[0].name + ' ' + sort[0].dir;
186 return this.pcrud.retrieveAll('cbt', {
187 offset: pager.offset,
191 // example of inline fleshing
192 cbt.owner(this.org.get(cbt.owner()));
193 cbt.datetime_test = new Date();
199 this.acpSource.getRows = (pager: Pager, sort: any[]) => {
200 const orderBy: any = {acp: 'id'};
202 orderBy.acp = sort[0].name + ' ' + sort[0].dir;
205 // base query to grab everything
206 const base: Object = {};
207 base[this.idl.classes['acp'].pkey] = {'!=' : null};
208 const query: any = new Array();
211 // and add any filters
212 Object.keys(this.acpSource.filters).forEach(key => {
213 Object.keys(this.acpSource.filters[key]).forEach(key2 => {
214 query.push(this.acpSource.filters[key][key2]);
217 return this.pcrud.search('acp',
220 flesh_fields: {acp: ['location', 'status']},
221 offset: pager.offset,
227 this.editSelected = (idlThings: IdlObject[]) => {
229 // Edit each IDL thing one at a time
230 const editOneThing = (thing: IdlObject) => {
231 if (!thing) { return; }
233 this.showEditDialog(thing).then(
234 () => editOneThing(idlThings.shift()));
237 editOneThing(idlThings.shift());
239 this.acpGrid.onRowActivate.subscribe(
240 (acpRec: IdlObject) => { this.showEditDialog(acpRec); }
243 this.complimentEvergreen = (rows: IdlObject[]) => alert('Evergreen is great!');
244 this.notOneSelectedRow = (rows: IdlObject[]) => (rows.length !== 1);
246 this.pcrud.retrieve('bre', 1, {}, {fleshSelectors: true})
248 // Format service will automatically find the selector
249 // value to display from our fleshed metarecord field.
250 this.aMetarecord = this.format.transform({
251 value: bib.metarecord(),
253 idlField: 'metarecord'
257 const b = this.idl.create('bresv');
258 b.cancel_time('2019-03-25T11:07:59-0400');
259 this.bresvEditor.mode = 'create';
260 this.bresvEditor.record = b;
262 this.myTimeForm = new FormGroup({
263 'datetime': new FormControl(Moment([]), (c: FormControl) => {
264 // An Angular custom validator
265 if (c.value.year() < 2019) {
266 return { tooLongAgo: 'That\'s before 2019' };
274 sbChannelHandler = msg => {
275 setTimeout(() => { this.sbChannelText = msg.data.msg; });
278 sendMessage($event) {
279 this.sbChannel.postMessage({msg : $event.target.value});
282 // Example of click handler for row action
283 complimentEvergreen2(rows: IdlObject[]) {
284 alert('I know, right?');
288 this.fmRecordEditor.open({size: 'lg'}).subscribe(
289 pcrudResult => console.debug('Record editor performed action'),
290 err => console.error(err),
291 () => console.debug('Dialog closed')
295 btGridRowClassCallback(row: any): string {
296 if (row.id() === 1) {
297 return 'text-uppercase font-weight-bold text-danger';
301 btGridRowFlairCallback(row: any): GridRowFlairEntry {
302 const flair = {icon: null, title: null};
303 if (row.id() === 2) {
304 flair.icon = 'priority_high';
305 flair.title = 'I Am ID 2';
306 } else if (row.id() === 3) {
307 flair.icon = 'not_interested';
312 // apply to all 'name' columns regardless of row
313 btGridCellClassCallback(row: any, col: GridColumn): string {
314 if (col.name === 'name') {
315 if (row.id() === 7) {
316 return 'text-lowercase font-weight-bold text-info';
318 return 'text-uppercase font-weight-bold text-success';
324 template: this.printTemplate,
325 contextData: {world : this.world},
326 printContext: 'default'
330 text: '<b>hello</b>',
331 printContext: 'default'
337 template: this.printTemplate,
338 contextData: {world : this.world},
339 printContext: 'default',
345 console.log('HERE WITH ' + date);
346 this.testDate = date;
350 this.progressDialog.open();
352 // every 250ms emit x*10 for 0-10
353 observableTimer(0, 250).pipe(
357 val => this.progressDialog.update({value: val, max: 100}),
359 () => this.progressDialog.close()
364 this.toast.success('HELLO TOAST TEST');
365 setTimeout(() => this.toast.danger('DANGER TEST AHHH!'), 4000);
369 this.strings.interpolate('staff.sandbox.test', {name : 'janey'})
370 .then(txt => this.toast.success(txt));
373 this.strings.interpolate('staff.sandbox.test', {name : 'johnny'})
374 .then(txt => this.toast.success(txt));
378 confirmNumber(num: number): void {
379 this.numThings = num;
380 console.log(this.numThings);
381 this.numConfirmDialog.open();
384 showEditDialog(idlThing: IdlObject): Promise<any> {
385 this.editDialog.mode = 'update';
386 this.editDialog.recId = idlThing['id']();
387 return new Promise((resolve, reject) => {
388 this.editDialog.open({size: 'lg'}).subscribe(
390 this.successString.current()
391 .then(str => this.toast.success(str));
392 this.acpGrid.reloadWithoutPagerReset();
396 this.updateFailedString.current()
397 .then(str => this.toast.danger(str));
404 allFutureDates(date: NgbDate, current: { year: number; month: number; }) {
405 const currentTime = new Date();
406 const today = new NgbDate(currentTime.getFullYear(), currentTime.getMonth() + 1, currentTime.getDate());
407 return date.after(today);
411 const d = new Date();
412 d.setDate(d.getDate() - 7);