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;
115 myTimeForm: FormGroup;
118 aLocation: IdlObject; // acpl
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);
138 this.badOrgForm = new FormGroup({
139 'badOrgSelector': new FormControl(
140 {'id': 4, 'includeAncestors': false, 'includeDescendants': true}, (c: FormControl) => {
141 // An Angular custom validator
142 if (c.value.orgIds && c.value.orgIds.length > 5) {
143 return { tooMany: 'That\'s too many fancy libraries!' };
150 this.ranganathan = new FormGroup({
151 'law': new FormControl('second', (c: FormControl) => {
152 // An Angular custom validator
153 if ('wrong' === c.value.id || c.value.freetext) {
154 return { notALaw: 'That\'s not a real law of library science!' };
161 this.badOrgForm.get('badOrgSelector').valueChanges.subscribe(bad => {
162 this.toast.danger('The fanciest libraries are: ' + JSON.stringify(bad.orgIds));
165 this.ranganathan.get('law').valueChanges.subscribe(l => {
166 this.toast.success('You chose: ' + l.label);
169 this.kingdom = {id: 'Bacteria', label: 'Bacteria'};
171 this.gridDataSource.data = [
172 {name: 'Jane', state: 'AZ'},
173 {name: 'Al', state: 'CA'},
174 {name: 'The Tick', state: 'TX'}
177 this.pcrud.retrieveAll('cmrcfld', {order_by: {cmrcfld: 'name'}})
178 .subscribe(format => {
179 if (!this.cbEntries) { this.cbEntries = []; }
180 this.cbEntries.push({id: format.id(), label: format.name()});
183 this.cbAsyncSource = term => {
184 return this.pcrud.search(
186 {name: {'ilike': `%${term}%`}}, // could -or search on label
187 {order_by: {cmrcfld: 'name'}}
188 ).pipe(map(marcField => {
189 return {id: marcField.id(), label: marcField.name()};
193 this.btSource.getRows = (pager: Pager, sort: any[]) => {
195 const orderBy: any = {cbt: 'name'};
197 orderBy.cbt = sort[0].name + ' ' + sort[0].dir;
200 return this.pcrud.retrieveAll('cbt', {
201 offset: pager.offset,
205 // example of inline fleshing
206 cbt.owner(this.org.get(cbt.owner()));
207 cbt.datetime_test = new Date();
213 // GridCellTextGenerator for the btGrid; note that this
214 // also demonstrates that a GridCellTextGenerator only has
215 // access to the row, and does not have access to any additional
216 // context that might be passed to a cellTemplate
217 this.btGridCellTextGenerator = {
218 test: row => 'HELLO universe ' + row.id()
221 this.acpSource.getRows = (pager: Pager, sort: any[]) => {
222 const orderBy: any = {acp: 'id'};
224 orderBy.acp = sort[0].name + ' ' + sort[0].dir;
227 // base query to grab everything
228 const base: Object = {};
229 base[this.idl.classes['acp'].pkey] = {'!=' : null};
230 const query: any = new Array();
233 // and add any filters
234 Object.keys(this.acpSource.filters).forEach(key => {
235 Object.keys(this.acpSource.filters[key]).forEach(key2 => {
236 query.push(this.acpSource.filters[key][key2]);
239 return this.pcrud.search('acp',
242 flesh_fields: {acp: ['location', 'status', 'creator', 'editor']},
243 offset: pager.offset,
249 this.eventsDataSource.getRows = (pager: Pager, sort: any[]) => {
251 const orderEventsBy: any = {atevdef: 'name'};
253 orderEventsBy.atevdef = sort[0].name + ' ' + sort[0].dir;
256 const base: Object = {};
257 base[this.idl.classes['atevdef'].pkey] = {'!=' : null};
258 const query: any = new Array();
261 Object.keys(this.eventsDataSource.filters).forEach(key => {
262 Object.keys(this.eventsDataSource.filters[key]).forEach(key2 => {
263 query.push(this.eventsDataSource.filters[key][key2]);
267 return this.pcrud.search('atevdef', query, {
269 flesh_fields: {atevdef: ['hook', 'validator', 'reactor']},
270 offset: pager.offset,
272 order_by: orderEventsBy
276 this.editSelected = (idlThings: IdlObject[]) => {
278 // Edit each IDL thing one at a time
279 const editOneThing = (thing: IdlObject) => {
280 if (!thing) { return; }
282 this.showEditDialog(thing).then(
283 () => editOneThing(idlThings.shift()));
286 editOneThing(idlThings.shift());
288 this.acpGrid.onRowActivate.subscribe(
289 (acpRec: IdlObject) => { this.showEditDialog(acpRec); }
292 this.complimentEvergreen = (rows: IdlObject[]) => alert('Evergreen is great!');
293 this.notOneSelectedRow = (rows: IdlObject[]) => (rows.length !== 1);
295 this.pcrud.retrieve('bre', 1, {}, {fleshSelectors: true})
297 // Format service will automatically find the selector
298 // value to display from our fleshed metarecord field.
299 this.aMetarecord = this.format.transform({
300 value: bib.metarecord(),
302 idlField: 'metarecord'
306 const b = this.idl.create('bresv');
307 b.cancel_time('2019-03-25T11:07:59-0400');
308 this.bresvEditor.mode = 'create';
309 this.bresvEditor.record = b;
311 this.myTimeForm = new FormGroup({
312 'datetime': new FormControl(Moment([]), (c: FormControl) => {
313 // An Angular custom validator
314 if (c.value.year() < 2019) {
315 return { tooLongAgo: 'That\'s before 2019' };
322 const str = 'César & Me';
323 console.log(this.h2txt.htmlToTxt(str));
326 sbChannelHandler = msg => {
327 setTimeout(() => { this.sbChannelText = msg.data.msg; });
330 sendMessage($event) {
331 this.sbChannel.postMessage({msg : $event.target.value});
334 // Example of click handler for row action
335 complimentEvergreen2(rows: IdlObject[]) {
336 alert('I know, right?');
340 this.fmRecordEditor.open({size: 'lg'}).subscribe(
341 pcrudResult => console.debug('Record editor performed action'),
342 err => console.error(err),
343 () => console.debug('Dialog closed')
347 btGridRowClassCallback(row: any): string {
348 if (row.id() === 1) {
349 return 'text-uppercase font-weight-bold text-danger';
353 btGridRowFlairCallback(row: any): GridRowFlairEntry {
354 const flair = {icon: null, title: null};
355 if (row.id() === 2) {
356 flair.icon = 'priority_high';
357 flair.title = 'I Am ID 2';
358 } else if (row.id() === 3) {
359 flair.icon = 'not_interested';
364 // apply to all 'name' columns regardless of row
365 btGridCellClassCallback(row: any, col: GridColumn): string {
366 if (col.name === 'name') {
367 if (row.id() === 7) {
368 return 'text-lowercase font-weight-bold text-info';
370 return 'text-uppercase font-weight-bold text-success';
376 template: this.printTemplate,
377 contextData: {world : this.world},
378 printContext: 'default'
382 text: '<b>hello</b>',
383 printContext: 'default'
389 template: this.printTemplate,
390 contextData: {world : this.world},
391 printContext: 'default',
397 console.log('HERE WITH ' + date);
398 this.testDate = date;
402 this.progressDialog.open();
404 // every 250ms emit x*10 for 0-10
405 observableTimer(0, 250).pipe(
409 val => this.progressDialog.update({value: val, max: 100}),
411 () => this.progressDialog.close()
416 this.toast.success('HELLO TOAST TEST');
417 setTimeout(() => this.toast.danger('DANGER TEST AHHH!'), 4000);
421 this.strings.interpolate('staff.sandbox.test', {name : 'janey'})
422 .then(txt => this.toast.success(txt));
425 this.strings.interpolate('staff.sandbox.test', {name : 'johnny'})
426 .then(txt => this.toast.success(txt));
430 confirmNumber(num: number): void {
431 this.numThings = num;
432 console.log(this.numThings);
433 this.numConfirmDialog.open();
436 showEditDialog(idlThing: IdlObject): Promise<any> {
437 this.editDialog.mode = 'update';
438 this.editDialog.recordId = idlThing['id']();
439 return new Promise((resolve, reject) => {
440 this.editDialog.open({size: 'lg'}).subscribe(
442 this.successString.current()
443 .then(str => this.toast.success(str));
444 this.acpGrid.reloadWithoutPagerReset();
448 this.updateFailedString.current()
449 .then(str => this.toast.danger(str));
456 allFutureDates(date: NgbDate, current: { year: number; month: number; }) {
457 const currentTime = new Date();
458 const today = new NgbDate(currentTime.getFullYear(), currentTime.getMonth() + 1, currentTime.getDate());
459 return date.after(today);
463 const d = new Date();
464 d.setDate(d.getDate() - 7);
470 // Note these values can be IDL objects or plain hashes.
471 const templateData = {
472 patron: this.samples.listOfThings('au')[0],
473 address: this.samples.listOfThings('aua')[0]
476 // NOTE: eventually this will be baked into the print service.
478 templateName: 'patron_address',
479 contextData: templateData,
480 printContext: 'default'
485 this.penaltyDialog.open()
486 .subscribe(val => console.log('penalty value', val));