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 get record(): MarcRecord { return this.context.record; }
42 randId = Math.floor(Math.random() * 100000);
43 editInput: any; // <input/> or <div contenteditable/>
44 maxLength: number = null;
46 // Track the load-time content so we know what text value to
47 // track on our undo stack.
48 undoBackToText: string;
50 focusSub: Subscription;
51 undoRedoSub: Subscription;
52 isLeader: boolean; // convenience
54 // Cache of fixed field menu options
55 ffValues: ContextMenuEntry[] = [];
57 // Track the fixed field value locally since extracting the value
58 // in real time from the record, which adds padding to the text,
59 // causes usability problems.
63 private renderer: Renderer2,
64 private tagTable: TagTableService) {}
67 this.setupFieldType();
71 if (this.focusSub) { this.focusSub.unsubscribe(); }
72 if (this.undoRedoSub) { this.undoRedoSub.unsubscribe(); }
75 watchForFocusRequests() {
76 this.focusSub = this.context.fieldFocusRequest.pipe(
77 filter((req: FieldFocusRequest) => this.focusRequestIsMe(req)))
78 .subscribe((req: FieldFocusRequest) => this.selectText(req));
81 watchForUndoRedoRequests() {
82 this.undoRedoSub = this.context.textUndoRedoRequest.pipe(
83 filter((action: TextUndoRedoAction) => this.focusRequestIsMe(action.position)))
84 .subscribe((action: TextUndoRedoAction) => this.processUndoRedo(action));
87 focusRequestIsMe(req: FieldFocusRequest): boolean {
88 if (req.target !== this.fieldType) { return false; }
91 if (req.fieldId !== this.field.fieldId) { return false; }
92 } else if (req.target === 'ldr') {
94 } else if (req.target === 'ffld' &&
95 req.ffCode !== this.fixedFieldCode) {
99 if (req.sfOffset !== undefined &&
100 req.sfOffset !== this.subfield[2]) {
101 // this is not the subfield you are looking for.
108 selectText(req?: FieldFocusRequest) {
112 this.editInput.select();
116 // Focus request may have come from keyboard navigation,
117 // clicking, etc. Model the event as a focus request
118 // so it can be tracked the same.
120 fieldId: this.field ? this.field.fieldId : -1,
121 target: this.fieldType,
122 sfOffset: this.subfield ? this.subfield[2] : undefined,
123 ffCode: this.fixedFieldCode
127 this.context.lastFocused = req;
131 const content = this.getContent();
132 this.undoBackToText = content;
134 switch (this.fieldType) {
136 this.isLeader = true;
137 if (content) { this.maxLength = content.length; }
138 this.watchForFocusRequests();
139 this.watchForUndoRedoRequests();
144 this.watchForFocusRequests();
145 this.watchForUndoRedoRequests();
149 this.watchForFocusRequests();
150 this.watchForUndoRedoRequests();
154 this.applyFFOptions();
155 this.watchForFocusRequests();
156 this.watchForUndoRedoRequests();
162 this.watchForFocusRequests();
163 this.watchForUndoRedoRequests();
168 this.watchForFocusRequests();
169 this.watchForUndoRedoRequests();
174 this.watchForFocusRequests();
175 this.watchForUndoRedoRequests();
181 return this.tagTable.getFfFieldMeta(
182 this.fixedFieldCode, this.record.recordType())
185 this.maxLength = fieldMeta.length || 1;
189 // Fixed field options change when the record type changes.
190 this.context.recordChange.subscribe(_ => this.applyFFOptions());
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; }
198 switch (this.fieldType) {
200 return this.tagTable.getFieldTags();
203 return this.tagTable.getSubfieldCodes(this.field.tag);
206 return this.tagTable.getSubfieldValues(
207 this.field.tag, this.subfield[0]);
211 return this.tagTable.getIndicatorValues(
212 this.field.tag, this.fieldType);
215 return this.tagTable.getFfValues(
216 this.fixedFieldCode, this.record.recordType());
222 getContent(): string {
223 if (this.fieldText) { return this.fieldText; } // read-only
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;
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
243 if ( this.ffValue === undefined ||
244 !this.context.lastFocused ||
245 !this.focusRequestIsMe(this.context.lastFocused)) {
248 this.record.extractFixedField(this.fixedFieldCode);
255 setContent(value: string, propagatBigText?: boolean, skipUndoTrack?: boolean) {
257 if (this.fieldText) { return; } // read-only text
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;
268 // Track locally and propagate to the record.
269 this.ffValue = value;
270 this.record.setFixedField(this.fixedFieldCode, value);
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;
281 if (!skipUndoTrack) {
282 this.trackTextChangeForUndo(value);
286 trackTextChangeForUndo(value: string) {
288 // Human-driven changes invalidate the redo stack.
289 this.context.redoStack = [];
291 const lastUndo = this.context.undoStack[0];
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.
303 const undo = new TextUndoRedoAction();
304 undo.position = this.context.lastFocused;
305 undo.textContent = this.undoBackToText;
307 this.context.undoStack.unshift(undo);
310 // Apply the undo or redo action and track its opposite
311 // action on the necessary stack
312 processUndoRedo(action: TextUndoRedoAction) {
314 // Undoing a text change
315 const recoverContent = this.getContent();
316 this.setContent(action.textContent, true, true);
318 action.textContent = recoverContent;
319 const moveTo = action.isRedo ?
320 this.context.undoStack : this.context.redoStack;
322 moveTo.unshift(action);
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();
332 // Propagate editable div content into our record
333 bigTextValueChange() {
334 this.setContent(this.editInput.innerText);
338 this.editInput = // numeric id requires [id=...] query selector
339 this.renderer.selectRootElement(`[id='${this.randId}']`);
341 // Initialize the editable div
342 this.editInput.innerText = this.getContent();
345 inputSize(): number {
346 if (this.maxLength) {
347 return this.maxLength + 1;
349 // give at least 2+ chars space and grow with the content
350 return Math.max(2, (this.getContent() || '').length) * 1.1;
354 const targetNode = this.editInput.firstChild;
357 // Div contains no text content, nothing to select
361 const range = document.createRange();
362 range.setStart(targetNode, 0);
363 range.setEnd(targetNode, targetNode.length);
365 const selection = window.getSelection();
366 selection.removeAllRanges();
367 selection.addRange(range);
370 // Route keydown events to the appropriate handler
371 inputKeyDown(evt: KeyboardEvent) {
375 if (evt.ctrlKey) { // redo
376 this.context.requestRedo();
377 evt.preventDefault();
382 if (evt.ctrlKey) { // undo
383 this.context.requestUndo();
384 evt.preventDefault();
390 // shift+F6 => add 006
391 this.context.add00X('006');
392 evt.preventDefault();
393 evt.stopPropagation();
399 // shift+F7 => add 007
400 this.context.add00X('007');
401 evt.preventDefault();
402 evt.stopPropagation();
408 // shift+F8 => add/replace 008
409 this.context.insertReplace008();
410 evt.preventDefault();
411 evt.stopPropagation();
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; }
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);
429 evt.preventDefault(); // Bare newlines not allowed.
435 // ctrl+delete == delete whole field
436 this.context.deleteField(this.field);
437 evt.preventDefault();
439 } else if (evt.shiftKey && this.subfield) {
440 // shift+delete == delete subfield
442 this.context.deleteSubfield(this.field, this.subfield);
443 evt.preventDefault();
451 // ctrl+down == copy current field down one
452 this.context.insertField(
453 this.field, this.record.cloneField(this.field));
455 // avoid dupe focus requests
456 this.context.focusNextTag(this.field);
459 evt.preventDefault();
465 // ctrl+up == copy current field up one
466 this.context.insertField(
467 this.field, this.record.cloneField(this.field), true);
469 // avoid dupe focus requests
470 this.context.focusPreviousTag(this.field);
473 // up == move focus to tag of previous field
474 evt.preventDefault();
480 // ctrl+i / ctrl+d == insert subfield
481 const pos = this.subfield ? this.subfield[2] + 1 : 0;
482 this.context.insertStubSubfield(this.field, pos);
483 evt.preventDefault();
489 insertField(before: boolean) {
491 const newField = this.record.newField(
492 {tag: '999', subfields: [[' ', '', 0]]});
495 this.record.insertFieldsBefore(this.field, newField);
497 this.record.insertFieldsAfter(this.field, newField);
500 this.context.requestFieldFocus(
501 {fieldId: newField.fieldId, target: 'tag'});
505 if (!this.context.focusNextTag(this.field)) {
506 this.context.focusPreviousTag(this.field);
509 this.record.deleteFields(this.field);
513 // If subfields remain, focus the previous subfield.
514 // otherwise focus our tag.
515 const sfpos = this.subfield[2] - 1;
517 this.field.deleteExactSubfields(this.subfield);
519 const focus: FieldFocusRequest = {
520 fieldId: this.field.fieldId, target: 'tag'};
523 focus.target = 'sfv';
524 focus.sfOffset = sfpos;
527 this.context.requestFieldFocus(focus);
530 contextMenuChange(value: string) {
531 this.setContent(value, true);