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;
55 @ViewChild('penaltyDialog', {static: false}) penaltyDialog;
58 // @ViewChild('helloStr') private helloStr: StringComponent;
60 gridDataSource: GridDataSource = new GridDataSource();
62 cbEntries: ComboboxEntry[];
63 // supplier of async combobox data
64 cbAsyncSource: (term: string) => Observable<ComboboxEntry>;
66 btSource: GridDataSource = new GridDataSource();
67 btGridCellTextGenerator: GridCellTextGenerator;
68 acpSource: GridDataSource = new GridDataSource();
69 eventsDataSource: GridDataSource = new GridDataSource();
70 editSelected: (rows: IdlObject[]) => void;
71 @ViewChild('acpGrid', { static: true }) acpGrid: GridComponent;
72 @ViewChild('acpEditDialog', { static: true }) editDialog: FmRecordEditorComponent;
73 @ViewChild('successString', { static: true }) successString: StringComponent;
74 @ViewChild('updateFailedString', { static: true }) updateFailedString: StringComponent;
75 world = 'world'; // for local template version
76 btGridTestContext: any = {hello : this.world};
83 @Input() set testString(str: string) {
91 dynamicTitleText: string;
93 badOrgForm: FormGroup;
95 ranganathan: FormGroup;
97 dateObject: Date = new Date();
99 simpleCombo: ComboboxEntry;
100 kingdom: ComboboxEntry;
102 complimentEvergreen: (rows: IdlObject[]) => void;
103 notOneSelectedRow: (rows: IdlObject[]) => boolean;
105 // selector field value on metarecord object
108 // file-reader example
109 fileContents: Array<string>;
111 // cross-tab communications example
112 private sbChannel: any;
113 sbChannelText: string;
114 myTimeForm: FormGroup;
117 aLocation: IdlObject; // acpl
118 orgClassCallback: (orgId: number) => string;
121 private idl: IdlService,
122 private org: OrgService,
123 private pcrud: PcrudService,
124 private strings: StringService,
125 private toast: ToastService,
126 private format: FormatService,
127 private printer: PrintService,
128 private samples: SampleDataService,
129 private h2txt: HtmlToTxtService
131 // BroadcastChannel is not yet defined in PhantomJS and elsewhere
132 this.sbChannel = (typeof BroadcastChannel === 'undefined') ?
133 {} : new BroadcastChannel('eg.sbChannel');
134 this.sbChannel.onmessage = (e) => this.sbChannelHandler(e);
136 this.orgClassCallback = (orgId: number): string => {
137 if (orgId === 1) { return 'font-weight-bold'; }
138 return orgId <= 3 ? 'text-info' : 'text-danger';
143 this.badOrgForm = new FormGroup({
144 'badOrgSelector': new FormControl(
145 {'id': 4, 'includeAncestors': false, 'includeDescendants': true}, (c: FormControl) => {
146 // An Angular custom validator
147 if (c.value.orgIds && c.value.orgIds.length > 5) {
148 return { tooMany: 'That\'s too many fancy libraries!' };
155 this.ranganathan = new FormGroup({
156 'law': new FormControl('second', (c: FormControl) => {
157 // An Angular custom validator
158 if ('wrong' === c.value.id || c.value.freetext) {
159 return { notALaw: 'That\'s not a real law of library science!' };
166 this.badOrgForm.get('badOrgSelector').valueChanges.subscribe(bad => {
167 this.toast.danger('The fanciest libraries are: ' + JSON.stringify(bad.orgIds));
170 this.ranganathan.get('law').valueChanges.subscribe(l => {
171 this.toast.success('You chose: ' + l.label);
174 this.kingdom = {id: 'Bacteria', label: 'Bacteria'};
176 this.gridDataSource.data = [
177 {name: 'Jane', state: 'AZ'},
178 {name: 'Al', state: 'CA'},
179 {name: 'The Tick', state: 'TX'}
182 this.pcrud.retrieveAll('cmrcfld', {order_by: {cmrcfld: 'name'}})
183 .subscribe(format => {
184 if (!this.cbEntries) { this.cbEntries = []; }
185 this.cbEntries.push({id: format.id(), label: format.name()});
188 this.cbAsyncSource = term => {
189 return this.pcrud.search(
191 {name: {'ilike': `%${term}%`}}, // could -or search on label
192 {order_by: {cmrcfld: 'name'}}
193 ).pipe(map(marcField => {
194 return {id: marcField.id(), label: marcField.name()};
198 this.btSource.getRows = (pager: Pager, sort: any[]) => {
200 const orderBy: any = {cbt: 'name'};
202 orderBy.cbt = sort[0].name + ' ' + sort[0].dir;
205 return this.pcrud.retrieveAll('cbt', {
206 offset: pager.offset,
210 // example of inline fleshing
211 cbt.owner(this.org.get(cbt.owner()));
212 cbt.datetime_test = new Date();
218 // GridCellTextGenerator for the btGrid; note that this
219 // also demonstrates that a GridCellTextGenerator only has
220 // access to the row, and does not have access to any additional
221 // context that might be passed to a cellTemplate
222 this.btGridCellTextGenerator = {
223 test: row => 'HELLO universe ' + row.id()
226 this.acpSource.getRows = (pager: Pager, sort: any[]) => {
227 const orderBy: any = {acp: 'id'};
229 orderBy.acp = sort[0].name + ' ' + sort[0].dir;
232 // base query to grab everything
233 const base: Object = {};
234 base[this.idl.classes['acp'].pkey] = {'!=' : null};
235 const query: any = new Array();
238 // and add any filters
239 Object.keys(this.acpSource.filters).forEach(key => {
240 Object.keys(this.acpSource.filters[key]).forEach(key2 => {
241 query.push(this.acpSource.filters[key][key2]);
244 return this.pcrud.search('acp',
247 flesh_fields: {acp: ['location', 'status', 'creator', 'editor']},
248 offset: pager.offset,
254 this.eventsDataSource.getRows = (pager: Pager, sort: any[]) => {
256 const orderEventsBy: any = {atevdef: 'name'};
258 orderEventsBy.atevdef = sort[0].name + ' ' + sort[0].dir;
261 const base: Object = {};
262 base[this.idl.classes['atevdef'].pkey] = {'!=' : null};
263 const query: any = new Array();
266 console.log(JSON.stringify(this.eventsDataSource.filters));
268 Object.keys(this.eventsDataSource.filters).forEach(key => {
269 Object.keys(this.eventsDataSource.filters[key]).forEach(key2 => {
270 query.push(this.eventsDataSource.filters[key][key2]);
274 return this.pcrud.search('atevdef', query, {
276 flesh_fields: {atevdef: ['hook', 'validator', 'reactor']},
277 offset: pager.offset,
279 order_by: orderEventsBy
283 this.editSelected = (idlThings: IdlObject[]) => {
285 // Edit each IDL thing one at a time
286 const editOneThing = (thing: IdlObject) => {
287 if (!thing) { return; }
289 this.showEditDialog(thing).then(
290 () => editOneThing(idlThings.shift()));
293 editOneThing(idlThings.shift());
295 this.acpGrid.onRowActivate.subscribe(
296 (acpRec: IdlObject) => { this.showEditDialog(acpRec); }
299 this.complimentEvergreen = (rows: IdlObject[]) => alert('Evergreen is great!');
300 this.notOneSelectedRow = (rows: IdlObject[]) => (rows.length !== 1);
302 this.pcrud.retrieve('bre', 1, {}, {fleshSelectors: true})
304 // Format service will automatically find the selector
305 // value to display from our fleshed metarecord field.
306 this.aMetarecord = this.format.transform({
307 value: bib.metarecord(),
309 idlField: 'metarecord'
313 const b = this.idl.create('bresv');
314 b.cancel_time('2019-03-25T11:07:59-0400');
315 this.bresvEditor.mode = 'create';
316 this.bresvEditor.record = b;
318 this.myTimeForm = new FormGroup({
319 'datetime': new FormControl(Moment([]), (c: FormControl) => {
320 // An Angular custom validator
321 if (c.value.year() < 2019) {
322 return { tooLongAgo: 'That\'s before 2019' };
329 const str = 'César & Me';
330 console.log(this.h2txt.htmlToTxt(str));
333 sbChannelHandler = msg => {
334 setTimeout(() => { this.sbChannelText = msg.data.msg; });
337 sendMessage($event) {
338 this.sbChannel.postMessage({msg : $event.target.value});
341 // Example of click handler for row action
342 complimentEvergreen2(rows: IdlObject[]) {
343 alert('I know, right?');
347 this.fmRecordEditor.open({size: 'lg'}).subscribe(
348 pcrudResult => console.debug('Record editor performed action'),
349 err => console.error(err),
350 () => console.debug('Dialog closed')
354 btGridRowClassCallback(row: any): string {
355 if (row.id() === 1) {
356 return 'text-uppercase font-weight-bold text-danger';
360 btGridRowFlairCallback(row: any): GridRowFlairEntry {
361 const flair = {icon: null, title: null};
362 if (row.id() === 2) {
363 flair.icon = 'priority_high';
364 flair.title = 'I Am ID 2';
365 } else if (row.id() === 3) {
366 flair.icon = 'not_interested';
371 // apply to all 'name' columns regardless of row
372 btGridCellClassCallback(row: any, col: GridColumn): string {
373 if (col.name === 'name') {
374 if (row.id() === 7) {
375 return 'text-lowercase font-weight-bold text-info';
377 return 'text-uppercase font-weight-bold text-success';
383 template: this.printTemplate,
384 contextData: {world : this.world},
385 printContext: 'default'
389 text: '<b>hello</b>',
390 printContext: 'default'
396 template: this.printTemplate,
397 contextData: {world : this.world},
398 printContext: 'default',
404 console.log('HERE WITH ' + date);
405 this.testDate = date;
409 this.progressDialog.open();
411 // every 250ms emit x*10 for 0-10
412 observableTimer(0, 250).pipe(
416 val => this.progressDialog.update({value: val, max: 100}),
418 () => this.progressDialog.close()
423 this.toast.success('HELLO TOAST TEST');
424 setTimeout(() => this.toast.danger('DANGER TEST AHHH!'), 4000);
428 this.strings.interpolate('staff.sandbox.test', {name : 'janey'})
429 .then(txt => this.toast.success(txt));
432 this.strings.interpolate('staff.sandbox.test', {name : 'johnny'})
433 .then(txt => this.toast.success(txt));
437 confirmNumber(num: number): void {
438 this.numThings = num;
439 console.log(this.numThings);
440 this.numConfirmDialog.open();
443 showEditDialog(idlThing: IdlObject): Promise<any> {
444 this.editDialog.mode = 'update';
445 this.editDialog.recordId = idlThing['id']();
446 return new Promise((resolve, reject) => {
447 this.editDialog.open({size: 'lg'}).subscribe(
449 this.successString.current()
450 .then(str => this.toast.success(str));
451 this.acpGrid.reloadWithoutPagerReset();
455 this.updateFailedString.current()
456 .then(str => this.toast.danger(str));
463 allFutureDates(date: NgbDate, current: { year: number; month: number; }) {
464 const currentTime = new Date();
465 const today = new NgbDate(currentTime.getFullYear(), currentTime.getMonth() + 1, currentTime.getDate());
466 return date.after(today);
470 const d = new Date();
471 d.setDate(d.getDate() - 7);
477 // Note these values can be IDL objects or plain hashes.
478 const templateData = {
479 patron: this.samples.listOfThings('au')[0],
480 address: this.samples.listOfThings('aua')[0]
483 // NOTE: eventually this will be baked into the print service.
485 templateName: 'patron_address',
486 contextData: templateData,
487 printContext: 'default'
492 this.penaltyDialog.open()
493 .subscribe(val => console.log('penalty value', val));