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';
12 * MARC Editable Content Component
16 selector: 'eg-marc-editable-content',
17 templateUrl: './editable-content.component.html',
18 styleUrls: ['./editable-content.component.css']
21 export class EditableContentComponent
22 implements OnInit, AfterViewInit, OnDestroy {
24 @Input() context: MarcEditContext;
25 @Input() field: MarcField;
26 @Input() fieldType: MARC_EDITABLE_FIELD_TYPE = null;
28 // read-only field text. E.g. 'LDR'
29 @Input() fieldText: string = null;
31 // array of subfield code and subfield value
32 @Input() subfield: MarcSubfield;
34 @Input() fixedFieldCode: string;
36 // space-separated list of additional CSS classes to append
37 @Input() moreClasses: string;
39 // aria-label text. This will not be visible in the UI.
40 @Input() ariaLabel: string;
42 get record(): MarcRecord { return this.context.record; }
45 randId = Math.floor(Math.random() * 100000);
46 editInput: any; // <input/> or <div contenteditable/>
47 maxLength: number = null;
49 // Track the load-time content so we know what text value to
50 // track on our undo stack.
51 undoBackToText: string;
53 focusSub: Subscription;
54 undoRedoSub: Subscription;
55 isLeader: boolean; // convenience
57 // Cache of fixed field menu options
58 ffValues: ContextMenuEntry[] = [];
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.
66 private renderer: Renderer2,
67 private tagTable: TagTableService) {}
70 this.setupFieldType();
74 if (this.focusSub) { this.focusSub.unsubscribe(); }
75 if (this.undoRedoSub) { this.undoRedoSub.unsubscribe(); }
78 watchForFocusRequests() {
79 this.focusSub = this.context.fieldFocusRequest.pipe(
80 filter((req: FieldFocusRequest) => this.focusRequestIsMe(req)))
81 .subscribe((req: FieldFocusRequest) => this.selectText(req));
84 watchForUndoRedoRequests() {
85 this.undoRedoSub = this.context.textUndoRedoRequest.pipe(
86 filter((action: TextUndoRedoAction) => this.focusRequestIsMe(action.position)))
87 .subscribe((action: TextUndoRedoAction) => this.processUndoRedo(action));
90 focusRequestIsMe(req: FieldFocusRequest): boolean {
91 if (req.target !== this.fieldType) { return false; }
94 if (req.fieldId !== this.field.fieldId) { return false; }
95 } else if (req.target === 'ldr') {
97 } else if (req.target === 'ffld' &&
98 req.ffCode !== this.fixedFieldCode) {
102 if (req.sfOffset !== undefined &&
103 req.sfOffset !== this.subfield[2]) {
104 // this is not the subfield you are looking for.
111 selectText(req?: FieldFocusRequest) {
115 this.editInput.select();
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.
123 fieldId: this.field ? this.field.fieldId : -1,
124 target: this.fieldType,
125 sfOffset: this.subfield ? this.subfield[2] : undefined,
126 ffCode: this.fixedFieldCode
130 this.context.lastFocused = req;
134 const content = this.getContent();
135 this.undoBackToText = content;
137 switch (this.fieldType) {
139 this.isLeader = true;
140 if (content) { this.maxLength = content.length; }
141 this.watchForFocusRequests();
142 this.watchForUndoRedoRequests();
147 this.watchForFocusRequests();
148 this.watchForUndoRedoRequests();
152 this.watchForFocusRequests();
153 this.watchForUndoRedoRequests();
157 this.applyFFOptions();
158 this.watchForFocusRequests();
159 this.watchForUndoRedoRequests();
165 this.watchForFocusRequests();
166 this.watchForUndoRedoRequests();
171 this.watchForFocusRequests();
172 this.watchForUndoRedoRequests();
177 this.watchForFocusRequests();
178 this.watchForUndoRedoRequests();
184 return this.tagTable.getFfFieldMeta(
185 this.fixedFieldCode, this.record.recordType())
188 this.maxLength = fieldMeta.length || 1;
192 // Fixed field options change when the record type changes.
193 this.context.recordChange.subscribe(_ => this.applyFFOptions());
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; }
201 switch (this.fieldType) {
203 return this.tagTable.getFieldTags();
206 return this.tagTable.getSubfieldCodes(this.field.tag);
209 return this.tagTable.getSubfieldValues(
210 this.field.tag, this.subfield[0]);
214 return this.tagTable.getIndicatorValues(
215 this.field.tag, this.fieldType);
218 return this.tagTable.getFfValues(
219 this.fixedFieldCode, this.record.recordType());
225 getContent(): string {
226 if (this.fieldText) { return this.fieldText; } // read-only
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;
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
246 if ( this.ffValue === undefined ||
247 !this.context.lastFocused ||
248 !this.focusRequestIsMe(this.context.lastFocused)) {
251 this.record.extractFixedField(this.fixedFieldCode);
258 setContent(value: string, propagatBigText?: boolean, skipUndoTrack?: boolean) {
260 if (this.fieldText) { return; } // read-only text
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;
271 // Track locally and propagate to the record.
272 this.ffValue = value;
273 this.record.setFixedField(this.fixedFieldCode, value);
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;
284 if (!skipUndoTrack) {
285 this.trackTextChangeForUndo(value);
289 trackTextChangeForUndo(value: string) {
291 // Human-driven changes invalidate the redo stack.
292 this.context.redoStack = [];
294 const lastUndo = this.context.undoStack[0];
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.
306 const undo = new TextUndoRedoAction();
307 undo.position = this.context.lastFocused;
308 undo.textContent = this.undoBackToText;
310 this.context.addToUndoStack(undo);
313 // Apply the undo or redo action and track its opposite
314 // action on the necessary stack
315 processUndoRedo(action: TextUndoRedoAction) {
317 // Undoing a text change
318 const recoverContent = this.getContent();
319 this.setContent(action.textContent, true, true);
321 action.textContent = recoverContent;
322 const moveTo = action.isRedo ?
323 this.context.undoStack : this.context.redoStack;
325 moveTo.unshift(action);
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();
335 // Propagate editable div content into our record
336 bigTextValueChange() {
337 this.setContent(this.editInput.innerText);
341 this.editInput = // numeric id requires [id=...] query selector
342 this.renderer.selectRootElement(`[id='${this.randId}']`);
344 // Initialize the editable div
345 this.editInput.innerText = this.getContent();
348 inputSize(): number {
349 if (this.maxLength) {
350 return this.maxLength + 1;
352 // give at least 2+ chars space and grow with the content
353 return Math.max(2, (this.getContent() || '').length) * 1.1;
357 const targetNode = this.editInput.firstChild;
360 // Div contains no text content, nothing to select
364 const range = document.createRange();
365 range.setStart(targetNode, 0);
366 range.setEnd(targetNode, targetNode.length);
368 const selection = window.getSelection();
369 selection.removeAllRanges();
370 selection.addRange(range);
373 // Route keydown events to the appropriate handler
374 inputKeyDown(evt: KeyboardEvent) {
378 if (evt.ctrlKey) { // redo
379 this.context.requestRedo();
380 evt.preventDefault();
385 if (evt.ctrlKey) { // undo
386 this.context.requestUndo();
387 evt.preventDefault();
393 // shift+F6 => add 006
394 this.context.add00X('006');
395 evt.preventDefault();
396 evt.stopPropagation();
402 // shift+F7 => add 007
403 this.context.add00X('007');
404 evt.preventDefault();
405 evt.stopPropagation();
411 // shift+F8 => add/replace 008
412 this.context.insertReplace008();
413 evt.preventDefault();
414 evt.stopPropagation();
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; }
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);
432 evt.preventDefault(); // Bare newlines not allowed.
438 // ctrl+delete == delete whole field
439 this.context.deleteField(this.field);
440 evt.preventDefault();
442 } else if (evt.shiftKey) {
445 // shift+delete == delete subfield
447 this.context.deleteSubfield(this.field, this.subfield);
449 // prevent any shift-delete from bubbling up becuase
450 // unexpected stuff will be deleted.
451 evt.preventDefault();
459 // ctrl+down == copy current field down one
460 this.context.insertField(
461 this.field, this.record.cloneField(this.field));
463 // avoid dupe focus requests
464 this.context.focusNextTag(this.field);
467 evt.preventDefault();
473 // ctrl+up == copy current field up one
474 this.context.insertField(
475 this.field, this.record.cloneField(this.field), true);
477 // avoid dupe focus requests
478 this.context.focusPreviousTag(this.field);
481 // up == move focus to tag of previous field
482 evt.preventDefault();
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();
497 insertField(before: boolean) {
499 const newField = this.record.newField(
500 {tag: '999', subfields: [[' ', '', 0]]});
503 this.record.insertFieldsBefore(this.field, newField);
505 this.record.insertFieldsAfter(this.field, newField);
508 this.context.requestFieldFocus(
509 {fieldId: newField.fieldId, target: 'tag'});
513 if (!this.context.focusNextTag(this.field)) {
514 this.context.focusPreviousTag(this.field);
517 this.record.deleteFields(this.field);
521 // If subfields remain, focus the previous subfield.
522 // otherwise focus our tag.
523 const sfpos = this.subfield[2] - 1;
525 this.field.deleteExactSubfields(this.subfield);
527 const focus: FieldFocusRequest = {
528 fieldId: this.field.fieldId, target: 'tag'};
531 focus.target = 'sfv';
532 focus.sfOffset = sfpos;
535 this.context.requestFieldFocus(focus);
538 contextMenuChange(value: string) {
539 this.setContent(value, true);