]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/share/marc-edit/editable-content.component.ts
c6c1ebc49826c45f4ce1864d04186c9626329146
[working/Evergreen.git] / Open-ILS / src / eg2 / src / app / staff / share / marc-edit / editable-content.component.ts
1 import {ElementRef, Component, Input, Output, OnInit, OnDestroy,
2     EventEmitter, AfterViewInit, Renderer2} from '@angular/core';
3 import {Subscription} from 'rxjs';
4 import {filter} from 'rxjs/operators';
5 import {MarcRecord, MarcField, MarcSubfield} from './marcrecord';
6 import {MarcEditContext, FieldFocusRequest, MARC_EDITABLE_FIELD_TYPE,
7     TextUndoRedoAction} from './editor-context';
8 import {ContextMenuEntry} from '@eg/share/context-menu/context-menu.service';
9 import {TagTableService} from './tagtable.service';
10
11 /**
12  * MARC Editable Content Component
13  */
14
15 @Component({
16   selector: 'eg-marc-editable-content',
17   templateUrl: './editable-content.component.html',
18   styleUrls: ['./editable-content.component.css']
19 })
20
21 export class EditableContentComponent
22     implements OnInit, AfterViewInit, OnDestroy {
23
24     @Input() context: MarcEditContext;
25     @Input() field: MarcField;
26     @Input() fieldType: MARC_EDITABLE_FIELD_TYPE = null;
27
28     // read-only field text.  E.g. 'LDR'
29     @Input() fieldText: string = null;
30
31     // array of subfield code and subfield value
32     @Input() subfield: MarcSubfield;
33
34     @Input() fixedFieldCode: string;
35
36     // space-separated list of additional CSS classes to append
37     @Input() moreClasses: string;
38
39     // aria-label text.  This will not be visible in the UI.
40     @Input() ariaLabel: string;
41
42     get record(): MarcRecord { return this.context.record; }
43
44     bigText = false;
45     randId = Math.floor(Math.random() * 100000);
46     editInput: any; // <input/> or <div contenteditable/>
47     maxLength: number = null;
48
49     // Track the load-time content so we know what text value to
50     // track on our undo stack.
51     undoBackToText: string;
52
53     focusSub: Subscription;
54     undoRedoSub: Subscription;
55     isLeader: boolean; // convenience
56
57     // Cache of fixed field menu options
58     ffValues: ContextMenuEntry[] = [];
59
60     // Track the fixed field value locally since extracting the value
61     // in real time from the record, which adds padding to the text,
62     // causes usability problems.
63     ffValue: string;
64
65     constructor(
66         private renderer: Renderer2,
67         private tagTable: TagTableService) {}
68
69     ngOnInit() {
70         this.setupFieldType();
71     }
72
73     ngOnDestroy() {
74         if (this.focusSub) { this.focusSub.unsubscribe(); }
75         if (this.undoRedoSub) { this.undoRedoSub.unsubscribe(); }
76     }
77
78     watchForFocusRequests() {
79         this.focusSub = this.context.fieldFocusRequest.pipe(
80             filter((req: FieldFocusRequest) => this.focusRequestIsMe(req)))
81         .subscribe((req: FieldFocusRequest) => this.selectText(req));
82     }
83
84     watchForUndoRedoRequests() {
85         this.undoRedoSub = this.context.textUndoRedoRequest.pipe(
86             filter((action: TextUndoRedoAction) => this.focusRequestIsMe(action.position)))
87         .subscribe((action: TextUndoRedoAction) => this.processUndoRedo(action));
88     }
89
90     focusRequestIsMe(req: FieldFocusRequest): boolean {
91         if (req.target !== this.fieldType) { return false; }
92
93         if (this.field) {
94             if (req.fieldId !== this.field.fieldId) { return false; }
95         } else if (req.target === 'ldr') {
96             return this.isLeader;
97         } else if (req.target === 'ffld' &&
98             req.ffCode !== this.fixedFieldCode) {
99             return false;
100         }
101
102         if (req.sfOffset !== undefined &&
103             req.sfOffset !== this.subfield[2]) {
104             // this is not the subfield you are looking for.
105             return false;
106         }
107
108         return true;
109     }
110
111     selectText(req?: FieldFocusRequest) {
112         if (this.bigText) {
113             this.focusBigText();
114         } else {
115             this.editInput.select();
116         }
117
118         if (!req) {
119             // Focus request may have come from keyboard navigation,
120             // clicking, etc.  Model the event as a focus request
121             // so it can be tracked the same.
122             req = {
123                 fieldId: this.field ? this.field.fieldId : -1,
124                 target: this.fieldType,
125                 sfOffset: this.subfield ? this.subfield[2] : undefined,
126                 ffCode: this.fixedFieldCode
127             };
128         }
129
130         this.context.lastFocused = req;
131     }
132
133     setupFieldType() {
134         const content = this.getContent();
135         this.undoBackToText = content;
136
137         switch (this.fieldType) {
138             case 'ldr':
139                 this.isLeader = true;
140                 if (content) { this.maxLength = content.length; }
141                 this.watchForFocusRequests();
142                 this.watchForUndoRedoRequests();
143                 break;
144
145             case 'tag':
146                 this.maxLength = 3;
147                 this.watchForFocusRequests();
148                 this.watchForUndoRedoRequests();
149                 break;
150
151             case 'cfld':
152                 this.watchForFocusRequests();
153                 this.watchForUndoRedoRequests();
154                 break;
155
156             case 'ffld':
157                 this.applyFFOptions();
158                 this.watchForFocusRequests();
159                 this.watchForUndoRedoRequests();
160                 break;
161
162             case 'ind1':
163             case 'ind2':
164                 this.maxLength = 1;
165                 this.watchForFocusRequests();
166                 this.watchForUndoRedoRequests();
167                 break;
168
169             case 'sfc':
170                 this.maxLength = 1;
171                 this.watchForFocusRequests();
172                 this.watchForUndoRedoRequests();
173                 break;
174
175             case 'sfv':
176                 this.bigText = true;
177                 this.watchForFocusRequests();
178                 this.watchForUndoRedoRequests();
179                 break;
180         }
181     }
182
183     applyFFOptions() {
184         return this.tagTable.getFfFieldMeta(
185             this.fixedFieldCode, this.record.recordType())
186         .then(fieldMeta => {
187             if (fieldMeta) {
188                 this.maxLength = fieldMeta.length || 1;
189             }
190         });
191
192         // Fixed field options change when the record type changes.
193         this.context.recordChange.subscribe(_ => this.applyFFOptions());
194     }
195
196     // These are served dynamically to handle cases where a tag or
197     // subfield is modified in place.
198     contextMenuEntries(): ContextMenuEntry[] {
199         if (this.isLeader) { return; }
200
201         switch (this.fieldType) {
202             case 'tag':
203                 return this.tagTable.getFieldTags();
204
205             case 'sfc':
206                 return this.tagTable.getSubfieldCodes(this.field.tag);
207
208             case 'sfv':
209                 return this.tagTable.getSubfieldValues(
210                     this.field.tag, this.subfield[0]);
211
212             case 'ind1':
213             case 'ind2':
214                 return this.tagTable.getIndicatorValues(
215                     this.field.tag, this.fieldType);
216
217             case 'ffld':
218                 return this.tagTable.getFfValues(
219                     this.fixedFieldCode, this.record.recordType());
220         }
221
222         return null;
223     }
224
225     getContent(): string {
226         if (this.fieldText) { return this.fieldText; } // read-only
227
228         switch (this.fieldType) {
229             case 'ldr': return this.record.leader;
230             case 'cfld': return this.field.data;
231             case 'tag': return this.field.tag;
232             case 'sfc': return this.subfield[0];
233             case 'sfv': return this.subfield[1];
234             case 'ind1': return this.field.ind1;
235             case 'ind2': return this.field.ind2;
236
237             case 'ffld':
238                 // When actively editing a fixed field, track its value
239                 // in a local variable instead of pulling the value
240                 // from record.extractFixedField(), which applies
241                 // additional formattting, causing usability problems
242                 // (e.g. unexpected spaces).  Once focus is gone, the
243                 // view will be updated with the correctly formatted
244                 // value.
245
246                 if ( this.ffValue === undefined ||
247                     !this.context.lastFocused ||
248                     !this.focusRequestIsMe(this.context.lastFocused)) {
249
250                     this.ffValue =
251                         this.record.extractFixedField(this.fixedFieldCode);
252                 }
253                 return this.ffValue;
254         }
255         return 'X';
256     }
257
258     setContent(value: string, propagatBigText?: boolean, skipUndoTrack?: boolean) {
259
260         if (this.fieldText) { return; } // read-only text
261
262         switch (this.fieldType) {
263             case 'ldr': this.record.leader = value; break;
264             case 'cfld': this.field.data = value; break;
265             case 'tag': this.field.tag = value; break;
266             case 'sfc': this.subfield[0] = value; break;
267             case 'sfv': this.subfield[1] = value; break;
268             case 'ind1': this.field.ind1 = value; break;
269             case 'ind2': this.field.ind2 = value; break;
270             case 'ffld':
271                 // Track locally and propagate to the record.
272                 this.ffValue = value;
273                 this.record.setFixedField(this.fixedFieldCode, value);
274                 break;
275         }
276
277         if (propagatBigText && this.bigText) {
278             // Propagate new content to the bigtext div.
279             // Should only be used when a content change occurrs via
280             // external means (i.e. not from a direct edit of the div).
281             this.editInput.innerText = value;
282         }
283
284         if (!skipUndoTrack) {
285             this.trackTextChangeForUndo(value);
286         }
287     }
288
289     trackTextChangeForUndo(value: string) {
290
291         // Human-driven changes invalidate the redo stack.
292         this.context.redoStack = [];
293
294         const lastUndo = this.context.undoStack[0];
295
296         if (lastUndo
297             && lastUndo instanceof TextUndoRedoAction
298             && lastUndo.textContent === this.undoBackToText
299             && this.focusRequestIsMe(lastUndo.position)) {
300             // Most recent undo entry was a text change event within the
301             // current atomic editing (focused) session for the input.
302             // Nothing else to track.
303             return;
304         }
305
306         const undo = new TextUndoRedoAction();
307         undo.position = this.context.lastFocused;
308         undo.textContent =  this.undoBackToText;
309
310         this.context.addToUndoStack(undo);
311     }
312
313     // Apply the undo or redo action and track its opposite
314     // action on the necessary stack
315     processUndoRedo(action: TextUndoRedoAction) {
316
317         // Undoing a text change
318         const recoverContent = this.getContent();
319         this.setContent(action.textContent, true, true);
320
321         action.textContent = recoverContent;
322         const moveTo = action.isRedo ?
323             this.context.undoStack : this.context.redoStack;
324
325         moveTo.unshift(action);
326     }
327
328     inputBlurred() {
329         // If the text content changed during this focus session,
330         // track the new value as the value the next session of
331         // text edits should return to upon undo.
332         this.undoBackToText = this.getContent();
333     }
334
335     // Propagate editable div content into our record
336     bigTextValueChange() {
337         this.setContent(this.editInput.innerText);
338     }
339
340     ngAfterViewInit() {
341         this.editInput = // numeric id requires [id=...] query selector
342             this.renderer.selectRootElement(`[id='${this.randId}']`);
343
344         // Initialize the editable div
345         this.editInput.innerText = this.getContent();
346     }
347
348     inputSize(): number {
349         if (this.maxLength) {
350             return this.maxLength + 1;
351         }
352         // give at least 2+ chars space and grow with the content
353         return Math.max(2, (this.getContent() || '').length) * 1.1;
354     }
355
356     focusBigText() {
357         const targetNode = this.editInput.firstChild;
358
359         if (!targetNode) {
360             // Div contains no text content, nothing to select
361             return;
362         }
363
364         const range = document.createRange();
365         range.setStart(targetNode, 0);
366         range.setEnd(targetNode, targetNode.length);
367
368         const selection = window.getSelection();
369         selection.removeAllRanges();
370         selection.addRange(range);
371     }
372
373     // Route keydown events to the appropriate handler
374     inputKeyDown(evt: KeyboardEvent) {
375
376         switch (evt.key) {
377             case 'y':
378                 if (evt.ctrlKey) { // redo
379                     this.context.requestRedo();
380                     evt.preventDefault();
381                 }
382                 return;
383
384             case 'z':
385                 if (evt.ctrlKey) { // undo
386                     this.context.requestUndo();
387                     evt.preventDefault();
388                 }
389                 return;
390
391             case 'F6':
392                 if (evt.shiftKey) {
393                     // shift+F6 => add 006
394                     this.context.add00X('006');
395                     evt.preventDefault();
396                     evt.stopPropagation();
397                 }
398                 return;
399
400             case 'F7':
401                 if (evt.shiftKey) {
402                     // shift+F7 => add 007
403                     this.context.add00X('007');
404                     evt.preventDefault();
405                     evt.stopPropagation();
406                 }
407                 return;
408
409             case 'F8':
410                 if (evt.shiftKey) {
411                     // shift+F8 => add/replace 008
412                     this.context.insertReplace008();
413                     evt.preventDefault();
414                     evt.stopPropagation();
415                 }
416                 return;
417         }
418
419         // None of the remaining key combos are supported by the LDR
420         // or fixed field editor.
421         if (this.fieldType === 'ldr' || this.fieldType === 'ffld') { return; }
422
423         switch (evt.key) {
424
425             case 'Enter':
426                 if (evt.ctrlKey) {
427                     // ctrl+enter == insert stub field after focused field
428                     // ctrl+shift+enter == insert stub field before focused field
429                     this.context.insertStubField(this.field, evt.shiftKey);
430                 }
431
432                 evt.preventDefault(); // Bare newlines not allowed.
433                 break;
434
435             case 'Delete':
436
437                 if (evt.ctrlKey) {
438                     // ctrl+delete == delete whole field
439                     this.context.deleteField(this.field);
440                     evt.preventDefault();
441
442                 } else if (evt.shiftKey) {
443
444                     if (this.subfield) {
445                         // shift+delete == delete subfield
446
447                         this.context.deleteSubfield(this.field, this.subfield);
448                     }
449                     // prevent any shift-delete from bubbling up becuase
450                     // unexpected stuff will be deleted.
451                     evt.preventDefault();
452                 }
453
454                 break;
455
456             case 'ArrowDown':
457
458                 if (evt.ctrlKey) {
459                     // ctrl+down == copy current field down one
460                     this.context.insertField(
461                         this.field, this.record.cloneField(this.field));
462                 } else {
463                     // avoid dupe focus requests
464                     this.context.focusNextTag(this.field);
465                 }
466
467                 evt.preventDefault();
468                 break;
469
470             case 'ArrowUp':
471
472                 if (evt.ctrlKey) {
473                     // ctrl+up == copy current field up one
474                     this.context.insertField(
475                         this.field, this.record.cloneField(this.field), true);
476                 } else {
477                     // avoid dupe focus requests
478                     this.context.focusPreviousTag(this.field);
479                 }
480
481                 // up == move focus to tag of previous field
482                 evt.preventDefault();
483                 break;
484
485             case 'd': // thunk
486             case 'i':
487                 if (evt.ctrlKey) {
488                     // ctrl+i / ctrl+d == insert subfield
489                     const pos = this.subfield ? this.subfield[2] + 1 : 0;
490                     this.context.insertStubSubfield(this.field, pos);
491                     evt.preventDefault();
492                 }
493                 break;
494         }
495     }
496
497     insertField(before: boolean) {
498
499         const newField = this.record.newField(
500             {tag: '999', subfields: [[' ', '', 0]]});
501
502         if (before) {
503             this.record.insertFieldsBefore(this.field, newField);
504         } else {
505             this.record.insertFieldsAfter(this.field, newField);
506         }
507
508         this.context.requestFieldFocus(
509             {fieldId: newField.fieldId, target: 'tag'});
510     }
511
512     deleteField() {
513         if (!this.context.focusNextTag(this.field)) {
514             this.context.focusPreviousTag(this.field);
515         }
516
517         this.record.deleteFields(this.field);
518     }
519
520     deleteSubfield() {
521         // If subfields remain, focus the previous subfield.
522         // otherwise focus our tag.
523         const sfpos = this.subfield[2] - 1;
524
525         this.field.deleteExactSubfields(this.subfield);
526
527         const focus: FieldFocusRequest = {
528             fieldId: this.field.fieldId, target: 'tag'};
529
530         if (sfpos >= 0) {
531             focus.target = 'sfv';
532             focus.sfOffset = sfpos;
533         }
534
535         this.context.requestFieldFocus(focus);
536     }
537
538     contextMenuChange(value: string) {
539         this.setContent(value, true);
540     }
541 }
542
543