LP1852782 Context menu nagivation and FF repairs
[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
193     // These are served dynamically to handle cases where a tag or
194     // subfield is modified in place.
195     contextMenuEntries(): ContextMenuEntry[] {
196         if (this.isLeader) { return; }
197
198         switch (this.fieldType) {
199             case 'tag':
200                 return this.tagTable.getFieldTags();
201
202             case 'sfc':
203                 return this.tagTable.getSubfieldCodes(this.field.tag);
204
205             case 'sfv':
206                 return this.tagTable.getSubfieldValues(
207                     this.field.tag, this.subfield[0]);
208
209             case 'ind1':
210             case 'ind2':
211                 return this.tagTable.getIndicatorValues(
212                     this.field.tag, this.fieldType);
213
214             case 'ffld':
215                 return this.tagTable.getFfValues(
216                     this.fixedFieldCode, this.record.recordType());
217         }
218
219         return null;
220     }
221
222     getContent(): string {
223         if (this.fieldText) { return this.fieldText; } // read-only
224
225         switch (this.fieldType) {
226             case 'ldr': return this.record.leader;
227             case 'cfld': return this.field.data;
228             case 'tag': return this.field.tag;
229             case 'sfc': return this.subfield[0];
230             case 'sfv': return this.subfield[1];
231             case 'ind1': return this.field.ind1;
232             case 'ind2': return this.field.ind2;
233
234             case 'ffld':
235                 // When actively editing a fixed field, track its value
236                 // in a local variable instead of pulling the value
237                 // from record.extractFixedField(), which applies
238                 // additional formattting, causing usability problems
239                 // (e.g. unexpected spaces).  Once focus is gone, the
240                 // view will be updated with the correctly formatted
241                 // value.
242
243                 if ( this.ffValue === undefined ||
244                     !this.context.lastFocused ||
245                     !this.focusRequestIsMe(this.context.lastFocused)) {
246
247                     this.ffValue =
248                         this.record.extractFixedField(this.fixedFieldCode);
249                 }
250                 return this.ffValue;
251         }
252         return 'X';
253     }
254
255     setContent(value: string, propagatBigText?: boolean, skipUndoTrack?: boolean) {
256
257         if (this.fieldText) { return; } // read-only text
258
259         switch (this.fieldType) {
260             case 'ldr': this.record.leader = value; break;
261             case 'cfld': this.field.data = value; break;
262             case 'tag': this.field.tag = value; break;
263             case 'sfc': this.subfield[0] = value; break;
264             case 'sfv': this.subfield[1] = value; break;
265             case 'ind1': this.field.ind1 = value; break;
266             case 'ind2': this.field.ind2 = value; break;
267             case 'ffld':
268                 // Track locally and propagate to the record.
269                 this.ffValue = value;
270                 this.record.setFixedField(this.fixedFieldCode, value);
271                 break;
272         }
273
274         if (propagatBigText && this.bigText) {
275             // Propagate new content to the bigtext div.
276             // Should only be used when a content change occurrs via
277             // external means (i.e. not from a direct edit of the div).
278             this.editInput.innerText = value;
279         }
280
281         if (!skipUndoTrack) {
282             this.trackTextChangeForUndo(value);
283         }
284     }
285
286     trackTextChangeForUndo(value: string) {
287
288         // Human-driven changes invalidate the redo stack.
289         this.context.redoStack = [];
290
291         const lastUndo = this.context.undoStack[0];
292
293         if (lastUndo
294             && lastUndo instanceof TextUndoRedoAction
295             && lastUndo.textContent === this.undoBackToText
296             && this.focusRequestIsMe(lastUndo.position)) {
297             // Most recent undo entry was a text change event within the
298             // current atomic editing (focused) session for the input.
299             // Nothing else to track.
300             return;
301         }
302
303         const undo = new TextUndoRedoAction();
304         undo.position = this.context.lastFocused;
305         undo.textContent =  this.undoBackToText;
306
307         this.context.addToUndoStack(undo);
308     }
309
310     // Apply the undo or redo action and track its opposite
311     // action on the necessary stack
312     processUndoRedo(action: TextUndoRedoAction) {
313
314         // Undoing a text change
315         const recoverContent = this.getContent();
316         this.setContent(action.textContent, true, true);
317
318         action.textContent = recoverContent;
319         const moveTo = action.isRedo ?
320             this.context.undoStack : this.context.redoStack;
321
322         moveTo.unshift(action);
323     }
324
325     inputBlurred() {
326         // If the text content changed during this focus session,
327         // track the new value as the value the next session of
328         // text edits should return to upon undo.
329         this.undoBackToText = this.getContent();
330     }
331
332     // Propagate editable div content into our record
333     bigTextValueChange() {
334         this.setContent(this.editInput.innerText);
335     }
336
337     ngAfterViewInit() {
338         this.editInput = // numeric id requires [id=...] query selector
339             this.renderer.selectRootElement(`[id='${this.randId}']`);
340
341         // Initialize the editable div
342         this.editInput.innerText = this.getContent();
343     }
344
345     inputSize(): number {
346         if (this.maxLength) {
347             return this.maxLength + 1;
348         }
349         // give at least 2+ chars space and grow with the content
350         return Math.max(2, (this.getContent() || '').length) * 1.1;
351     }
352
353     focusBigText() {
354         const targetNode = this.editInput.firstChild;
355
356         if (!targetNode) {
357             // Div contains no text content, nothing to select
358             return;
359         }
360
361         const range = document.createRange();
362         range.setStart(targetNode, 0);
363         range.setEnd(targetNode, targetNode.length);
364
365         const selection = window.getSelection();
366         selection.removeAllRanges();
367         selection.addRange(range);
368     }
369
370     // Route keydown events to the appropriate handler
371     inputKeyDown(evt: KeyboardEvent) {
372
373         switch (evt.key) {
374             case 'y':
375                 if (evt.ctrlKey) { // redo
376                     this.context.requestRedo();
377                     evt.preventDefault();
378                 }
379                 return;
380
381             case 'z':
382                 if (evt.ctrlKey) { // undo
383                     this.context.requestUndo();
384                     evt.preventDefault();
385                 }
386                 return;
387
388             case 'F6':
389                 if (evt.shiftKey) {
390                     // shift+F6 => add 006
391                     this.context.add00X('006');
392                     evt.preventDefault();
393                     evt.stopPropagation();
394                 }
395                 return;
396
397             case 'F7':
398                 if (evt.shiftKey) {
399                     // shift+F7 => add 007
400                     this.context.add00X('007');
401                     evt.preventDefault();
402                     evt.stopPropagation();
403                 }
404                 return;
405
406             case 'F8':
407                 if (evt.shiftKey) {
408                     // shift+F8 => add/replace 008
409                     this.context.insertReplace008();
410                     evt.preventDefault();
411                     evt.stopPropagation();
412                 }
413                 return;
414         }
415
416         // None of the remaining key combos are supported by the LDR
417         // or fixed field editor.
418         if (this.fieldType === 'ldr' || this.fieldType === 'ffld') { return; }
419
420         switch (evt.key) {
421
422             case 'Enter':
423                 if (evt.ctrlKey) {
424                     // ctrl+enter == insert stub field after focused field
425                     // ctrl+shift+enter == insert stub field before focused field
426                     this.context.insertStubField(this.field, evt.shiftKey);
427                 }
428
429                 evt.preventDefault(); // Bare newlines not allowed.
430                 break;
431
432             case 'Delete':
433
434                 if (evt.ctrlKey) {
435                     // ctrl+delete == delete whole field
436                     this.context.deleteField(this.field);
437                     evt.preventDefault();
438
439                 } else if (evt.shiftKey) {
440
441                     if (this.subfield) {
442                         // shift+delete == delete subfield
443
444                         this.context.deleteSubfield(this.field, this.subfield);
445                     }
446                     // prevent any shift-delete from bubbling up becuase
447                     // unexpected stuff will be deleted.
448                     evt.preventDefault();
449                 }
450
451                 break;
452
453             case 'ArrowDown':
454
455                 if (evt.ctrlKey) {
456                     // ctrl+down == copy current field down one
457                     this.context.insertField(
458                         this.field, this.record.cloneField(this.field));
459                 } else {
460                     // avoid dupe focus requests
461                     this.context.focusNextTag(this.field);
462                 }
463
464                 evt.preventDefault();
465                 break;
466
467             case 'ArrowUp':
468
469                 if (evt.ctrlKey) {
470                     // ctrl+up == copy current field up one
471                     this.context.insertField(
472                         this.field, this.record.cloneField(this.field), true);
473                 } else {
474                     // avoid dupe focus requests
475                     this.context.focusPreviousTag(this.field);
476                 }
477
478                 // up == move focus to tag of previous field
479                 evt.preventDefault();
480                 break;
481
482             case 'd': // thunk
483             case 'i':
484                 if (evt.ctrlKey) {
485                     // ctrl+i / ctrl+d == insert subfield
486                     const pos = this.subfield ? this.subfield[2] + 1 : 0;
487                     this.context.insertStubSubfield(this.field, pos);
488                     evt.preventDefault();
489                 }
490                 break;
491         }
492     }
493
494     insertField(before: boolean) {
495
496         const newField = this.record.newField(
497             {tag: '999', subfields: [[' ', '', 0]]});
498
499         if (before) {
500             this.record.insertFieldsBefore(this.field, newField);
501         } else {
502             this.record.insertFieldsAfter(this.field, newField);
503         }
504
505         this.context.requestFieldFocus(
506             {fieldId: newField.fieldId, target: 'tag'});
507     }
508
509     deleteField() {
510         if (!this.context.focusNextTag(this.field)) {
511             this.context.focusPreviousTag(this.field);
512         }
513
514         this.record.deleteFields(this.field);
515     }
516
517     deleteSubfield() {
518         // If subfields remain, focus the previous subfield.
519         // otherwise focus our tag.
520         const sfpos = this.subfield[2] - 1;
521
522         this.field.deleteExactSubfields(this.subfield);
523
524         const focus: FieldFocusRequest = {
525             fieldId: this.field.fieldId, target: 'tag'};
526
527         if (sfpos >= 0) {
528             focus.target = 'sfv';
529             focus.sfOffset = sfpos;
530         }
531
532         this.context.requestFieldFocus(focus);
533     }
534
535     contextMenuChange(value: string) {
536         this.setContent(value, true);
537
538         // Context menus can steal focus.
539         this.context.requestFieldFocus(this.context.lastFocused);
540     }
541 }
542
543