1 import {ElementRef, Component, Input, Output, OnInit, OnDestroy,
2 ViewChild, 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 import {StringComponent} from '@eg/share/string/string.component';
13 * MARC Editable Content Component
17 selector: 'eg-marc-editable-content',
18 templateUrl: './editable-content.component.html',
19 styleUrls: ['./editable-content.component.css']
22 export class EditableContentComponent
23 implements OnInit, AfterViewInit, OnDestroy {
25 @Input() context: MarcEditContext;
26 @Input() field: MarcField;
27 @Input() fieldType: MARC_EDITABLE_FIELD_TYPE = null;
29 // read-only field text. E.g. 'LDR'
30 @Input() fieldText: string = null;
32 // array of subfield code and subfield value
33 @Input() subfield: MarcSubfield;
35 @Input() fixedFieldCode: string;
37 // space-separated list of additional CSS classes to append
38 @Input() moreClasses: string;
40 // aria-label text. This will not be visible in the UI.
41 @Input() ariaLabel: string;
43 get record(): MarcRecord { return this.context.record; }
46 randId = Math.floor(Math.random() * 100000);
47 editInput: any; // <input/> or <div contenteditable/>
48 maxLength: number = null;
50 // Track the load-time content so we know what text value to
51 // track on our undo stack.
52 undoBackToText: string;
54 focusSub: Subscription;
55 undoRedoSub: Subscription;
56 isLeader: boolean; // convenience
58 // Cache of fixed field menu options
59 ffValues: ContextMenuEntry[] = [];
61 // Cache of tag context menu entries
62 tagMenuEntries: ContextMenuEntry[] = [];
64 // Track the fixed field value locally since extracting the value
65 // in real time from the record, which adds padding to the text,
66 // causes usability problems.
69 @ViewChild('add006', {static: false}) add006Str: StringComponent;
70 @ViewChild('add007', {static: false}) add007Str: StringComponent;
71 @ViewChild('add008', {static: false}) add008Str: StringComponent;
72 @ViewChild('insertBefore', {static: false}) insertBeforeStr: StringComponent;
73 @ViewChild('insertAfter', {static: false}) insertAfterStr: StringComponent;
74 @ViewChild('deleteField', {static: false}) deleteFieldStr: StringComponent;
77 private renderer: Renderer2,
78 private tagTable: TagTableService) {}
81 this.setupFieldType();
85 if (this.focusSub) { this.focusSub.unsubscribe(); }
86 if (this.undoRedoSub) { this.undoRedoSub.unsubscribe(); }
89 watchForFocusRequests() {
90 this.focusSub = this.context.fieldFocusRequest.pipe(
91 filter((req: FieldFocusRequest) => this.focusRequestIsMe(req)))
92 .subscribe((req: FieldFocusRequest) => this.selectText(req));
95 watchForUndoRedoRequests() {
96 this.undoRedoSub = this.context.textUndoRedoRequest.pipe(
97 filter((action: TextUndoRedoAction) => this.focusRequestIsMe(action.position)))
98 .subscribe((action: TextUndoRedoAction) => this.processUndoRedo(action));
101 focusRequestIsMe(req: FieldFocusRequest): boolean {
102 if (req.target !== this.fieldType) { return false; }
105 if (req.fieldId !== this.field.fieldId) { return false; }
106 } else if (req.target === 'ldr') {
107 return this.isLeader;
108 } else if (req.target === 'ffld' &&
109 req.ffCode !== this.fixedFieldCode) {
113 if (req.sfOffset !== undefined &&
114 req.sfOffset !== this.subfield[2]) {
115 // this is not the subfield you are looking for.
122 selectText(req?: FieldFocusRequest) {
126 this.editInput.select();
130 // Focus request may have come from keyboard navigation,
131 // clicking, etc. Model the event as a focus request
132 // so it can be tracked the same.
134 fieldId: this.field ? this.field.fieldId : -1,
135 target: this.fieldType,
136 sfOffset: this.subfield ? this.subfield[2] : undefined,
137 ffCode: this.fixedFieldCode
141 this.context.lastFocused = req;
145 const content = this.getContent();
146 this.undoBackToText = content;
148 switch (this.fieldType) {
150 this.isLeader = true;
151 if (content) { this.maxLength = content.length; }
152 this.watchForFocusRequests();
153 this.watchForUndoRedoRequests();
158 this.watchForFocusRequests();
159 this.watchForUndoRedoRequests();
163 this.watchForFocusRequests();
164 this.watchForUndoRedoRequests();
168 this.applyFFOptions();
169 this.watchForFocusRequests();
170 this.watchForUndoRedoRequests();
176 this.watchForFocusRequests();
177 this.watchForUndoRedoRequests();
182 this.watchForFocusRequests();
183 this.watchForUndoRedoRequests();
188 this.watchForFocusRequests();
189 this.watchForUndoRedoRequests();
193 if (this.fieldText) {
194 this.maxLength = this.fieldText.length;
200 return this.tagTable.getFfFieldMeta(
201 this.fixedFieldCode, this.record.recordType())
204 this.maxLength = fieldMeta.length || 1;
209 // These are served dynamically to handle cases where a tag or
210 // subfield is modified in place.
211 contextMenuEntries(): ContextMenuEntry[] {
212 if (this.isLeader) { return; }
214 switch (this.fieldType) {
216 return this.tagContextMenuEntries();
219 return this.tagTable.getSubfieldCodes(this.field.tag);
222 return this.tagTable.getSubfieldValues(
223 this.field.tag, this.subfield[0]);
227 return this.tagTable.getIndicatorValues(
228 this.field.tag, this.fieldType);
231 return this.tagTable.getFfValues(
232 this.fixedFieldCode, this.record.recordType());
238 tagContextMenuEntries(): ContextMenuEntry[] {
240 // string components may not yet be loaded.
241 if (this.tagMenuEntries.length > 0 || !this.add006Str) {
242 return this.tagMenuEntries;
245 this.tagMenuEntries.push(
246 {label: this.add006Str.text, value: '_add006'},
247 {label: this.add007Str.text, value: '_add007'},
248 {label: this.add008Str.text, value: '_add008'}
251 if (!this.field.isCtrlField) {
252 // Only data field tags get these.
253 this.tagMenuEntries.push(
254 {label: this.insertAfterStr.text, value: '_insertAfter'},
255 {label: this.insertBeforeStr.text, value: '_insertBefore'}
259 this.tagMenuEntries.push(
260 {label: this.deleteFieldStr.text, value: '_deleteField'},
264 this.tagTable.getFieldTags().forEach(e => this.tagMenuEntries.push(e));
266 return this.tagMenuEntries;
269 getContent(): string {
270 if (this.fieldText) { return this.fieldText; } // read-only
272 switch (this.fieldType) {
273 case 'ldr': return this.record.leader;
274 case 'cfld': return this.field.data;
275 case 'tag': return this.field.tag;
276 case 'sfc': return this.subfield[0];
277 case 'sfv': return this.subfield[1];
278 case 'ind1': return this.field.ind1;
279 case 'ind2': return this.field.ind2;
282 // When actively editing a fixed field, track its value
283 // in a local variable instead of pulling the value
284 // from record.extractFixedField(), which applies
285 // additional formattting, causing usability problems
286 // (e.g. unexpected spaces). Once focus is gone, the
287 // view will be updated with the correctly formatted
290 if ( this.ffValue === undefined ||
291 !this.context.lastFocused ||
292 !this.focusRequestIsMe(this.context.lastFocused)) {
295 this.record.extractFixedField(this.fixedFieldCode);
302 setContent(value: string, propagatBigText?: boolean, skipUndoTrack?: boolean) {
304 if (this.fieldText) { return; } // read-only text
306 switch (this.fieldType) {
307 case 'ldr': this.record.leader = value; break;
308 case 'cfld': this.field.data = value; break;
309 case 'tag': this.field.tag = value; break;
310 case 'sfc': this.subfield[0] = value; break;
311 case 'sfv': this.subfield[1] = value; break;
312 case 'ind1': this.field.ind1 = value; break;
313 case 'ind2': this.field.ind2 = value; break;
315 // Track locally and propagate to the record.
316 this.ffValue = value;
317 this.record.setFixedField(this.fixedFieldCode, value);
321 if (propagatBigText && this.bigText) {
322 // Propagate new content to the bigtext div.
323 // Should only be used when a content change occurrs via
324 // external means (i.e. not from a direct edit of the div).
325 this.editInput.innerText = value;
328 if (!skipUndoTrack) {
329 this.trackTextChangeForUndo(value);
333 trackTextChangeForUndo(value: string) {
335 // Human-driven changes invalidate the redo stack.
336 this.context.redoStack = [];
338 const lastUndo = this.context.undoStack[0];
341 && lastUndo instanceof TextUndoRedoAction
342 && lastUndo.textContent === this.undoBackToText
343 && this.focusRequestIsMe(lastUndo.position)) {
344 // Most recent undo entry was a text change event within the
345 // current atomic editing (focused) session for the input.
346 // Nothing else to track.
350 const undo = new TextUndoRedoAction();
351 undo.position = this.context.lastFocused;
352 undo.textContent = this.undoBackToText;
354 this.context.addToUndoStack(undo);
357 // Apply the undo or redo action and track its opposite
358 // action on the necessary stack
359 processUndoRedo(action: TextUndoRedoAction) {
361 // Undoing a text change
362 const recoverContent = this.getContent();
363 this.setContent(action.textContent, true, true);
365 action.textContent = recoverContent;
366 const moveTo = action.isRedo ?
367 this.context.undoStack : this.context.redoStack;
369 moveTo.unshift(action);
373 // If the text content changed during this focus session,
374 // track the new value as the value the next session of
375 // text edits should return to upon undo.
376 this.undoBackToText = this.getContent();
379 // Propagate editable div content into our record
380 bigTextValueChange() {
381 this.setContent(this.editInput.innerText);
385 this.editInput = // numeric id requires [id=...] query selector
386 this.renderer.selectRootElement(`[id='${this.randId}']`);
388 // Initialize the editable div
389 this.editInput.innerText = this.getContent();
392 inputSize(): number {
393 if (this.maxLength) {
394 return this.maxLength + 1;
396 // give at least 2+ chars space and grow with the content
397 return Math.max(2, (this.getContent() || '').length) * 1.1;
401 const targetNode = this.editInput.firstChild;
404 // Div contains no text content, nothing to select
408 const range = document.createRange();
409 range.setStart(targetNode, 0);
410 range.setEnd(targetNode, targetNode.length);
412 const selection = window.getSelection();
413 selection.removeAllRanges();
414 selection.addRange(range);
417 // Route keydown events to the appropriate handler
418 inputKeyDown(evt: KeyboardEvent) {
422 if (evt.ctrlKey) { // redo
423 this.context.requestRedo();
424 evt.preventDefault();
429 if (evt.ctrlKey) { // undo
430 this.context.requestUndo();
431 evt.preventDefault();
437 // shift+F6 => add 006
438 this.context.add00X('006');
439 evt.preventDefault();
440 evt.stopPropagation();
446 // shift+F7 => add 007
447 this.context.add00X('007');
448 evt.preventDefault();
449 evt.stopPropagation();
455 // shift+F8 => add/replace 008
456 this.context.insertReplace008();
457 evt.preventDefault();
458 evt.stopPropagation();
463 // None of the remaining key combos are supported by the LDR
464 // or fixed field editor.
465 if (this.fieldType === 'ldr' || this.fieldType === 'ffld') { return; }
471 // ctrl+enter == insert stub field after focused field
472 // ctrl+shift+enter == insert stub field before focused field
473 this.context.insertStubField(this.field, evt.shiftKey);
476 evt.preventDefault(); // Bare newlines not allowed.
482 // ctrl+delete == delete whole field
483 this.context.deleteField(this.field);
484 evt.preventDefault();
486 } else if (evt.shiftKey) {
489 // shift+delete == delete subfield
491 this.context.deleteSubfield(this.field, this.subfield);
493 // prevent any shift-delete from bubbling up becuase
494 // unexpected stuff will be deleted.
495 evt.preventDefault();
503 // ctrl+down == copy current field down one
504 this.context.insertField(
505 this.field, this.record.cloneField(this.field));
507 // avoid dupe focus requests
508 this.context.focusNextTag(this.field);
511 evt.preventDefault();
517 // ctrl+up == copy current field up one
518 this.context.insertField(
519 this.field, this.record.cloneField(this.field), true);
521 // avoid dupe focus requests
522 this.context.focusPreviousTag(this.field);
525 // up == move focus to tag of previous field
526 evt.preventDefault();
532 // ctrl+i / ctrl+d == insert subfield
533 const pos = this.subfield ? this.subfield[2] + 1 : 0;
534 this.context.insertStubSubfield(this.field, pos);
535 evt.preventDefault();
541 insertField(before: boolean) {
543 const newField = this.record.newField(
544 {tag: '999', subfields: [[' ', '', 0]]});
547 this.record.insertFieldsBefore(this.field, newField);
549 this.record.insertFieldsAfter(this.field, newField);
552 this.context.requestFieldFocus(
553 {fieldId: newField.fieldId, target: 'tag'});
557 if (!this.context.focusNextTag(this.field)) {
558 this.context.focusPreviousTag(this.field);
561 this.record.deleteFields(this.field);
565 // If subfields remain, focus the previous subfield.
566 // otherwise focus our tag.
567 const sfpos = this.subfield[2] - 1;
569 this.field.deleteExactSubfields(this.subfield);
571 const focus: FieldFocusRequest = {
572 fieldId: this.field.fieldId, target: 'tag'};
575 focus.target = 'sfv';
576 focus.sfOffset = sfpos;
579 this.context.requestFieldFocus(focus);
582 contextMenuChange(value: string) {
585 case '_add006': return this.context.add00X('006');
586 case '_add007': return this.context.add00X('007');
587 case '_add008': return this.context.insertReplace008();
588 case '_insertBefore':
589 return this.context.insertStubField(this.field, true);
591 return this.context.insertStubField(this.field);
592 case '_deleteField': return this.context.deleteField(this.field);
595 this.setContent(value, true);
597 // Context menus can steal focus.
598 this.context.requestFieldFocus(this.context.lastFocused);