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, GridCellTextGenerator} 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';
25 import {HtmlToTxtService} from '@eg/share/util/htmltotxt.service';
28 templateUrl: 'sandbox.component.html',
29 styles: ['.date-time-input.ng-invalid {border: 5px purple solid;}',
30 '.date-time-input.ng-valid {border: 5px green solid; animation: slide 5s linear 1s infinite alternate;}',
31 '@keyframes slide {0% {margin-left:0px;} 50% {margin-left:200px;}']
33 export class SandboxComponent implements OnInit {
35 @ViewChild('progressDialog', { static: true })
36 private progressDialog: ProgressDialogComponent;
38 @ViewChild('dateSelect', { static: false })
39 private dateSelector: DateSelectComponent;
41 @ViewChild('printTemplate', { static: true })
42 private printTemplate: TemplateRef<any>;
44 @ViewChild('fmRecordEditor', { static: true })
45 private fmRecordEditor: FmRecordEditorComponent;
47 @ViewChild('numConfirmDialog', { static: true })
48 private numConfirmDialog: ConfirmDialogComponent;
52 @ViewChild('bresvEditor', { static: true })
53 private bresvEditor: FmRecordEditorComponent;
56 // @ViewChild('helloStr') private helloStr: StringComponent;
58 gridDataSource: GridDataSource = new GridDataSource();
60 cbEntries: ComboboxEntry[];
61 // supplier of async combobox data
62 cbAsyncSource: (term: string) => Observable<ComboboxEntry>;
64 btSource: GridDataSource = new GridDataSource();
65 btGridCellTextGenerator: GridCellTextGenerator;
66 acpSource: GridDataSource = new GridDataSource();
67 eventsDataSource: GridDataSource = new GridDataSource();
68 editSelected: (rows: IdlObject[]) => void;
69 @ViewChild('acpGrid', { static: true }) acpGrid: GridComponent;
70 @ViewChild('acpEditDialog', { static: true }) editDialog: FmRecordEditorComponent;
71 @ViewChild('successString', { static: true }) successString: StringComponent;
72 @ViewChild('updateFailedString', { static: true }) updateFailedString: StringComponent;
73 world = 'world'; // for local template version
74 btGridTestContext: any = {hello : this.world};
81 @Input() set testString(str: string) {
89 dynamicTitleText: string;
91 badOrgForm: FormGroup;
93 ranganathan: FormGroup;
95 dateObject: Date = new Date();
97 simpleCombo: ComboboxEntry;
98 kingdom: ComboboxEntry;
100 complimentEvergreen: (rows: IdlObject[]) => void;
101 notOneSelectedRow: (rows: IdlObject[]) => boolean;
103 // selector field value on metarecord object
106 // file-reader example
107 fileContents: Array<string>;
109 // cross-tab communications example
110 private sbChannel: any;
111 sbChannelText: string;
113 myTimeForm: FormGroup;
116 aLocation: IdlObject; // acpl
119 private idl: IdlService,
120 private org: OrgService,
121 private pcrud: PcrudService,
122 private strings: StringService,
123 private toast: ToastService,
124 private format: FormatService,
125 private printer: PrintService,
126 private samples: SampleDataService,
127 private h2txt: HtmlToTxtService
129 // BroadcastChannel is not yet defined in PhantomJS and elsewhere
130 this.sbChannel = (typeof BroadcastChannel === 'undefined') ?
131 {} : new BroadcastChannel('eg.sbChannel');
132 this.sbChannel.onmessage = (e) => this.sbChannelHandler(e);
136 this.badOrgForm = new FormGroup({
137 'badOrgSelector': new FormControl(
138 {'id': 4, 'includeAncestors': false, 'includeDescendants': true}, (c: FormControl) => {
139 // An Angular custom validator
140 if (c.value.orgIds && c.value.orgIds.length > 5) {
141 return { tooMany: 'That\'s too many fancy libraries!' };
148 this.ranganathan = new FormGroup({
149 'law': new FormControl('second', (c: FormControl) => {
150 // An Angular custom validator
151 if ('wrong' === c.value.id || c.value.freetext) {
152 return { notALaw: 'That\'s not a real law of library science!' };
159 this.badOrgForm.get('badOrgSelector').valueChanges.subscribe(bad => {
160 this.toast.danger('The fanciest libraries are: ' + JSON.stringify(bad.orgIds));
163 this.ranganathan.get('law').valueChanges.subscribe(l => {
164 this.toast.success('You chose: ' + l.label);
167 this.kingdom = {id: 'Bacteria', label: 'Bacteria'};
169 this.gridDataSource.data = [
170 {name: 'Jane', state: 'AZ'},
171 {name: 'Al', state: 'CA'},
172 {name: 'The Tick', state: 'TX'}
175 this.pcrud.retrieveAll('cmrcfld', {order_by: {cmrcfld: 'name'}})
176 .subscribe(format => {
177 if (!this.cbEntries) { this.cbEntries = []; }
178 this.cbEntries.push({id: format.id(), label: format.name()});
181 this.cbAsyncSource = term => {
182 return this.pcrud.search(
184 {name: {'ilike': `%${term}%`}}, // could -or search on label
185 {order_by: {cmrcfld: 'name'}}
186 ).pipe(map(marcField => {
187 return {id: marcField.id(), label: marcField.name()};
191 this.btSource.getRows = (pager: Pager, sort: any[]) => {
193 const orderBy: any = {cbt: 'name'};
195 orderBy.cbt = sort[0].name + ' ' + sort[0].dir;
198 return this.pcrud.retrieveAll('cbt', {
199 offset: pager.offset,
203 // example of inline fleshing
204 cbt.owner(this.org.get(cbt.owner()));
205 cbt.datetime_test = new Date();
211 // GridCellTextGenerator for the btGrid; note that this
212 // also demonstrates that a GridCellTextGenerator only has
213 // access to the row, and does not have access to any additional
214 // context that might be passed to a cellTemplate
215 this.btGridCellTextGenerator = {
216 test: row => 'HELLO universe ' + row.id()
219 this.acpSource.getRows = (pager: Pager, sort: any[]) => {
220 const orderBy: any = {acp: 'id'};
222 orderBy.acp = sort[0].name + ' ' + sort[0].dir;
225 // base query to grab everything
226 const base: Object = {};
227 base[this.idl.classes['acp'].pkey] = {'!=' : null};
228 const query: any = new Array();
231 // and add any filters
232 Object.keys(this.acpSource.filters).forEach(key => {
233 Object.keys(this.acpSource.filters[key]).forEach(key2 => {
234 query.push(this.acpSource.filters[key][key2]);
237 return this.pcrud.search('acp',
240 flesh_fields: {acp: ['location', 'status', 'creator', 'editor']},
241 offset: pager.offset,
247 this.eventsDataSource.getRows = (pager: Pager, sort: any[]) => {
249 const orderEventsBy: any = {atevdef: 'name'};
251 orderEventsBy.atevdef = sort[0].name + ' ' + sort[0].dir;
254 const base: Object = {};
255 base[this.idl.classes['atevdef'].pkey] = {'!=' : null};
256 const query: any = new Array();
259 Object.keys(this.eventsDataSource.filters).forEach(key => {
260 Object.keys(this.eventsDataSource.filters[key]).forEach(key2 => {
261 query.push(this.eventsDataSource.filters[key][key2]);
265 return this.pcrud.search('atevdef', query, {
267 flesh_fields: {atevdef: ['hook', 'validator', 'reactor']},
268 offset: pager.offset,
270 order_by: orderEventsBy
274 this.editSelected = (idlThings: IdlObject[]) => {
276 // Edit each IDL thing one at a time
277 const editOneThing = (thing: IdlObject) => {
278 if (!thing) { return; }
280 this.showEditDialog(thing).then(
281 () => editOneThing(idlThings.shift()));
284 editOneThing(idlThings.shift());
286 this.acpGrid.onRowActivate.subscribe(
287 (acpRec: IdlObject) => { this.showEditDialog(acpRec); }
290 this.complimentEvergreen = (rows: IdlObject[]) => alert('Evergreen is great!');
291 this.notOneSelectedRow = (rows: IdlObject[]) => (rows.length !== 1);
293 this.pcrud.retrieve('bre', 1, {}, {fleshSelectors: true})
295 // Format service will automatically find the selector
296 // value to display from our fleshed metarecord field.
297 this.aMetarecord = this.format.transform({
298 value: bib.metarecord(),
300 idlField: 'metarecord'
304 const b = this.idl.create('bresv');
305 b.cancel_time('2019-03-25T11:07:59-0400');
306 this.bresvEditor.mode = 'create';
307 this.bresvEditor.record = b;
309 this.myTimeForm = new FormGroup({
310 'datetime': new FormControl(Moment([]), (c: FormControl) => {
311 // An Angular custom validator
312 if (c.value.year() < 2019) {
313 return { tooLongAgo: 'That\'s before 2019' };
320 const str = 'César & Me';
321 console.log(this.h2txt.htmlToTxt(str));
324 sbChannelHandler = msg => {
325 setTimeout(() => { this.sbChannelText = msg.data.msg; });
328 sendMessage($event) {
329 this.sbChannel.postMessage({msg : $event.target.value});
332 // Example of click handler for row action
333 complimentEvergreen2(rows: IdlObject[]) {
334 alert('I know, right?');
338 this.fmRecordEditor.open({size: 'lg'}).subscribe(
339 pcrudResult => console.debug('Record editor performed action'),
340 err => console.error(err),
341 () => console.debug('Dialog closed')
345 btGridRowClassCallback(row: any): string {
346 if (row.id() === 1) {
347 return 'text-uppercase font-weight-bold text-danger';
351 btGridRowFlairCallback(row: any): GridRowFlairEntry {
352 const flair = {icon: null, title: null};
353 if (row.id() === 2) {
354 flair.icon = 'priority_high';
355 flair.title = 'I Am ID 2';
356 } else if (row.id() === 3) {
357 flair.icon = 'not_interested';
362 // apply to all 'name' columns regardless of row
363 btGridCellClassCallback(row: any, col: GridColumn): string {
364 if (col.name === 'name') {
365 if (row.id() === 7) {
366 return 'text-lowercase font-weight-bold text-info';
368 return 'text-uppercase font-weight-bold text-success';
374 template: this.printTemplate,
375 contextData: {world : this.world},
376 printContext: 'default'
380 text: '<b>hello</b>',
381 printContext: 'default'
387 template: this.printTemplate,
388 contextData: {world : this.world},
389 printContext: 'default',
395 console.log('HERE WITH ' + date);
396 this.testDate = date;
400 this.progressDialog.open();
402 // every 250ms emit x*10 for 0-10
403 observableTimer(0, 250).pipe(
407 val => this.progressDialog.update({value: val, max: 100}),
409 () => this.progressDialog.close()
414 this.toast.success('HELLO TOAST TEST');
415 setTimeout(() => this.toast.danger('DANGER TEST AHHH!'), 4000);
419 this.strings.interpolate('staff.sandbox.test', {name : 'janey'})
420 .then(txt => this.toast.success(txt));
423 this.strings.interpolate('staff.sandbox.test', {name : 'johnny'})
424 .then(txt => this.toast.success(txt));
428 confirmNumber(num: number): void {
429 this.numThings = num;
430 console.log(this.numThings);
431 this.numConfirmDialog.open();
434 showEditDialog(idlThing: IdlObject): Promise<any> {
435 this.editDialog.mode = 'update';
436 this.editDialog.recordId = idlThing['id']();
437 return new Promise((resolve, reject) => {
438 this.editDialog.open({size: 'lg'}).subscribe(
440 this.successString.current()
441 .then(str => this.toast.success(str));
442 this.acpGrid.reloadWithoutPagerReset();
446 this.updateFailedString.current()
447 .then(str => this.toast.danger(str));
454 allFutureDates(date: NgbDate, current: { year: number; month: number; }) {
455 const currentTime = new Date();
456 const today = new NgbDate(currentTime.getFullYear(), currentTime.getMonth() + 1, currentTime.getDate());
457 return date.after(today);
461 const d = new Date();
462 d.setDate(d.getDate() - 7);
468 // Note these values can be IDL objects or plain hashes.
469 const templateData = {
470 patron: this.samples.listOfThings('au')[0],
471 address: this.samples.listOfThings('aua')[0]
474 // NOTE: eventually this will be baked into the print service.
476 templateName: 'patron_address',
477 contextData: templateData,
478 printContext: 'default'