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';
24 import {SampleDataService} from '@eg/share/util/sample-data.service';
27 templateUrl: 'sandbox.component.html',
28 styles: ['.date-time-input.ng-invalid {border: 5px purple solid;}',
29 '.date-time-input.ng-valid {border: 5px green solid; animation: slide 5s linear 1s infinite alternate;}',
30 '@keyframes slide {0% {margin-left:0px;} 50% {margin-left:200px;}']
32 export class SandboxComponent implements OnInit {
34 @ViewChild('progressDialog', { static: true })
35 private progressDialog: ProgressDialogComponent;
37 @ViewChild('dateSelect', { static: false })
38 private dateSelector: DateSelectComponent;
40 @ViewChild('printTemplate', { static: true })
41 private printTemplate: TemplateRef<any>;
43 @ViewChild('fmRecordEditor', { static: true })
44 private fmRecordEditor: FmRecordEditorComponent;
46 @ViewChild('numConfirmDialog', { static: true })
47 private numConfirmDialog: ConfirmDialogComponent;
51 @ViewChild('bresvEditor', { static: true })
52 private bresvEditor: FmRecordEditorComponent;
55 // @ViewChild('helloStr') private helloStr: StringComponent;
57 gridDataSource: GridDataSource = new GridDataSource();
59 cbEntries: ComboboxEntry[];
60 // supplier of async combobox data
61 cbAsyncSource: (term: string) => Observable<ComboboxEntry>;
63 btSource: GridDataSource = new GridDataSource();
64 acpSource: GridDataSource = new GridDataSource();
65 editSelected: (rows: IdlObject[]) => void;
66 @ViewChild('acpGrid', { static: true }) acpGrid: GridComponent;
67 @ViewChild('acpEditDialog', { static: true }) editDialog: FmRecordEditorComponent;
68 @ViewChild('successString', { static: true }) successString: StringComponent;
69 @ViewChild('updateFailedString', { static: true }) updateFailedString: StringComponent;
70 world = 'world'; // for local template version
71 btGridTestContext: any = {hello : this.world};
78 @Input() set testString(str: string) {
86 dynamicTitleText: string;
88 badOrgForm: FormGroup;
90 ranganathan: FormGroup;
92 dateObject: Date = new Date();
94 simpleCombo: ComboboxEntry;
95 kingdom: ComboboxEntry;
97 complimentEvergreen: (rows: IdlObject[]) => void;
98 notOneSelectedRow: (rows: IdlObject[]) => boolean;
100 // selector field value on metarecord object
103 // cross-tab communications example
104 private sbChannel: any;
105 sbChannelText: string;
107 myTimeForm: FormGroup;
110 private idl: IdlService,
111 private org: OrgService,
112 private pcrud: PcrudService,
113 private strings: StringService,
114 private toast: ToastService,
115 private format: FormatService,
116 private printer: PrintService,
117 private samples: SampleDataService
119 // BroadcastChannel is not yet defined in PhantomJS and elsewhere
120 this.sbChannel = (typeof BroadcastChannel === 'undefined') ?
121 {} : new BroadcastChannel('eg.sbChannel');
122 this.sbChannel.onmessage = (e) => this.sbChannelHandler(e);
126 this.badOrgForm = new FormGroup({
127 'badOrgSelector': new FormControl(
128 {'id': 4, 'includeAncestors': false, 'includeDescendants': true}, (c: FormControl) => {
129 // An Angular custom validator
130 if (c.value.orgIds && c.value.orgIds.length > 5) {
131 return { tooMany: 'That\'s too many fancy libraries!' };
138 this.ranganathan = new FormGroup({
139 'law': new FormControl('second', (c: FormControl) => {
140 // An Angular custom validator
141 if ('wrong' === c.value.id || c.value.freetext) {
142 return { notALaw: 'That\'s not a real law of library science!' };
149 this.badOrgForm.get('badOrgSelector').valueChanges.subscribe(bad => {
150 this.toast.danger('The fanciest libraries are: ' + JSON.stringify(bad.orgIds));
153 this.ranganathan.get('law').valueChanges.subscribe(l => {
154 this.toast.success('You chose: ' + l.label);
157 this.kingdom = {id: 'Bacteria', label: 'Bacteria'};
159 this.gridDataSource.data = [
160 {name: 'Jane', state: 'AZ'},
161 {name: 'Al', state: 'CA'},
162 {name: 'The Tick', state: 'TX'}
165 this.pcrud.retrieveAll('cmrcfld', {order_by: {cmrcfld: 'name'}})
166 .subscribe(format => {
167 if (!this.cbEntries) { this.cbEntries = []; }
168 this.cbEntries.push({id: format.id(), label: format.name()});
171 this.cbAsyncSource = term => {
172 return this.pcrud.search(
174 {name: {'ilike': `%${term}%`}}, // could -or search on label
175 {order_by: {cmrcfld: 'name'}}
176 ).pipe(map(marcField => {
177 return {id: marcField.id(), label: marcField.name()};
181 this.btSource.getRows = (pager: Pager, sort: any[]) => {
183 const orderBy: any = {cbt: 'name'};
185 orderBy.cbt = sort[0].name + ' ' + sort[0].dir;
188 return this.pcrud.retrieveAll('cbt', {
189 offset: pager.offset,
193 // example of inline fleshing
194 cbt.owner(this.org.get(cbt.owner()));
195 cbt.datetime_test = new Date();
201 this.acpSource.getRows = (pager: Pager, sort: any[]) => {
202 const orderBy: any = {acp: 'id'};
204 orderBy.acp = sort[0].name + ' ' + sort[0].dir;
207 // base query to grab everything
208 const base: Object = {};
209 base[this.idl.classes['acp'].pkey] = {'!=' : null};
210 const query: any = new Array();
213 // and add any filters
214 Object.keys(this.acpSource.filters).forEach(key => {
215 Object.keys(this.acpSource.filters[key]).forEach(key2 => {
216 query.push(this.acpSource.filters[key][key2]);
219 return this.pcrud.search('acp',
222 flesh_fields: {acp: ['location', 'status']},
223 offset: pager.offset,
229 this.editSelected = (idlThings: IdlObject[]) => {
231 // Edit each IDL thing one at a time
232 const editOneThing = (thing: IdlObject) => {
233 if (!thing) { return; }
235 this.showEditDialog(thing).then(
236 () => editOneThing(idlThings.shift()));
239 editOneThing(idlThings.shift());
241 this.acpGrid.onRowActivate.subscribe(
242 (acpRec: IdlObject) => { this.showEditDialog(acpRec); }
245 this.complimentEvergreen = (rows: IdlObject[]) => alert('Evergreen is great!');
246 this.notOneSelectedRow = (rows: IdlObject[]) => (rows.length !== 1);
248 this.pcrud.retrieve('bre', 1, {}, {fleshSelectors: true})
250 // Format service will automatically find the selector
251 // value to display from our fleshed metarecord field.
252 this.aMetarecord = this.format.transform({
253 value: bib.metarecord(),
255 idlField: 'metarecord'
259 const b = this.idl.create('bresv');
260 b.cancel_time('2019-03-25T11:07:59-0400');
261 this.bresvEditor.mode = 'create';
262 this.bresvEditor.record = b;
264 this.myTimeForm = new FormGroup({
265 'datetime': new FormControl(Moment([]), (c: FormControl) => {
266 // An Angular custom validator
267 if (c.value.year() < 2019) {
268 return { tooLongAgo: 'That\'s before 2019' };
276 sbChannelHandler = msg => {
277 setTimeout(() => { this.sbChannelText = msg.data.msg; });
280 sendMessage($event) {
281 this.sbChannel.postMessage({msg : $event.target.value});
284 // Example of click handler for row action
285 complimentEvergreen2(rows: IdlObject[]) {
286 alert('I know, right?');
290 this.fmRecordEditor.open({size: 'lg'}).subscribe(
291 pcrudResult => console.debug('Record editor performed action'),
292 err => console.error(err),
293 () => console.debug('Dialog closed')
297 btGridRowClassCallback(row: any): string {
298 if (row.id() === 1) {
299 return 'text-uppercase font-weight-bold text-danger';
303 btGridRowFlairCallback(row: any): GridRowFlairEntry {
304 const flair = {icon: null, title: null};
305 if (row.id() === 2) {
306 flair.icon = 'priority_high';
307 flair.title = 'I Am ID 2';
308 } else if (row.id() === 3) {
309 flair.icon = 'not_interested';
314 // apply to all 'name' columns regardless of row
315 btGridCellClassCallback(row: any, col: GridColumn): string {
316 if (col.name === 'name') {
317 if (row.id() === 7) {
318 return 'text-lowercase font-weight-bold text-info';
320 return 'text-uppercase font-weight-bold text-success';
326 template: this.printTemplate,
327 contextData: {world : this.world},
328 printContext: 'default'
332 text: '<b>hello</b>',
333 printContext: 'default'
339 template: this.printTemplate,
340 contextData: {world : this.world},
341 printContext: 'default',
347 console.log('HERE WITH ' + date);
348 this.testDate = date;
352 this.progressDialog.open();
354 // every 250ms emit x*10 for 0-10
355 observableTimer(0, 250).pipe(
359 val => this.progressDialog.update({value: val, max: 100}),
361 () => this.progressDialog.close()
366 this.toast.success('HELLO TOAST TEST');
367 setTimeout(() => this.toast.danger('DANGER TEST AHHH!'), 4000);
371 this.strings.interpolate('staff.sandbox.test', {name : 'janey'})
372 .then(txt => this.toast.success(txt));
375 this.strings.interpolate('staff.sandbox.test', {name : 'johnny'})
376 .then(txt => this.toast.success(txt));
380 confirmNumber(num: number): void {
381 this.numThings = num;
382 console.log(this.numThings);
383 this.numConfirmDialog.open();
386 showEditDialog(idlThing: IdlObject): Promise<any> {
387 this.editDialog.mode = 'update';
388 this.editDialog.recordId = idlThing['id']();
389 return new Promise((resolve, reject) => {
390 this.editDialog.open({size: 'lg'}).subscribe(
392 this.successString.current()
393 .then(str => this.toast.success(str));
394 this.acpGrid.reloadWithoutPagerReset();
398 this.updateFailedString.current()
399 .then(str => this.toast.danger(str));
406 allFutureDates(date: NgbDate, current: { year: number; month: number; }) {
407 const currentTime = new Date();
408 const today = new NgbDate(currentTime.getFullYear(), currentTime.getMonth() + 1, currentTime.getDate());
409 return date.after(today);
413 const d = new Date();
414 d.setDate(d.getDate() - 7);
420 // Note these values can be IDL objects or plain hashes.
421 const templateData = {
422 patron: this.samples.listOfThings('au')[0],
423 address: this.samples.listOfThings('aua')[0]
426 // NOTE: eventually this will be baked into the print service.
428 templateName: 'patron_address',
429 contextData: templateData,
430 printContext: 'default'