Bug 11559: (QA followup) fix pagination bar, add Ctrl-D to macro editor
[koha.git] / koha-tmpl / intranet-tmpl / lib / koha / cateditor / marc-editor.js
1 /**
2  * Copyright 2015 ByWater Solutions
3  *
4  * This file is part of Koha.
5  *
6  * Koha is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * Koha is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Koha; if not, see <http://www.gnu.org/licenses>.
18  */
19
20 define( [ 'marc-record', 'koha-backend', 'preferences', 'text-marc', 'widget' ], function( MARC, KohaBackend, Preferences, TextMARC, Widget ) {
21     var NOTIFY_TIMEOUT = 250;
22
23     function editorCursorActivity( cm ) {
24         var editor = cm.marceditor;
25         var field = editor.getCurrentField();
26         if ( !field ) return;
27
28         // Set overwrite mode for tag numbers/indicators and contents of fixed fields
29         if ( field.isControlField || cm.getCursor().ch < 8 ) {
30             cm.toggleOverwrite(true);
31         } else {
32             cm.toggleOverwrite(false);
33         }
34
35         editor.onCursorActivity();
36     }
37
38     // This function exists to prevent inserting or partially deleting text that belongs to a
39     // widget. The 'marcAware' change source exists for other parts of the editor code to bypass
40     // this check.
41     function editorBeforeChange( cm, change ) {
42         var editor = cm.marceditor;
43         if ( editor.textMode || change.origin == 'marcAware' || change.origin == 'widget.clearToText' ) return;
44
45         // FIXME: Should only cancel changes if this is a control field/subfield widget
46         if ( change.from.line !== change.to.line || Math.abs( change.from.ch - change.to.ch ) > 1 || change.text.length != 1 || change.text[0].length != 0 ) return; // Not single-char change
47
48         if ( change.from.ch == change.to.ch - 1 && cm.findMarksAt( { line: change.from.line, ch: change.from.ch + 1 } ).length ) {
49             change.cancel();
50         } else if ( change.from.ch == change.to.ch && cm.findMarksAt(change.from).length && !change.text[0] == '‡' ) {
51             change.cancel();
52         }
53     }
54
55     function editorChanges( cm, changes ) {
56         var editor = cm.marceditor;
57         if ( editor.textMode ) return;
58
59         for (var i = 0; i < changes.length; i++) {
60             var change = changes[i];
61
62             var origin = change.from.line;
63             var newTo = CodeMirror.changeEnd(change);
64
65             for (var delLine = origin; delLine <= change.to.line; delLine++) {
66                 // Line deleted; currently nothing to do
67             }
68
69             for (var line = origin; line <= newTo.line; line++) {
70                 if ( Preferences.user.fieldWidgets ) Widget.UpdateLine( cm.marceditor, line );
71                 if ( change.origin != 'setValue' && change.origin != 'marcWidgetPrefill' && change.origin != 'widget.clearToText' ) {
72                     cm.addLineClass( line, 'wrapper', 'modified-line' );
73                     editor.modified = true;
74                 }
75             }
76         }
77
78         Widget.ActivateAt( cm, cm.getCursor() );
79         cm.marceditor.startNotify();
80     }
81
82     function editorSetOverwriteMode( cm, newState ) {
83         var editor = cm.marceditor;
84
85         editor.overwriteMode = newState;
86     }
87
88     // Editor helper functions
89     function activateTabPosition( cm, pos, idx ) {
90         // Allow tabbing to as-yet-nonexistent positions
91         var lenDiff = pos.ch - cm.getLine( pos.line ).length;
92         if ( lenDiff > 0 ) {
93             var extra = '';
94             while ( lenDiff-- > 0 ) extra += ' ';
95             if ( pos.prefill ) extra += pos.prefill;
96             cm.replaceRange( extra, { line: pos.line } );
97         }
98
99         cm.setCursor( pos );
100         Widget.ActivateAt( cm, pos, idx );
101     }
102
103     function getTabPositions( editor, cur ) {
104         cur = cur || editor.cm.getCursor();
105         var field = editor.getFieldAt( cur.line );
106
107         if ( field ) {
108             if ( field.isControlField ) {
109                 var positions = [ { ch: 0 }, { ch: 4 } ];
110
111                 $.each( positions, function( undef, pos ) {
112                     pos.line = cur.line;
113                 } );
114
115                 return positions;
116             } else {
117                 var positions = [ { ch: 0 }, { ch: 4, prefill: '_' }, { ch: 6, prefill: '_' } ];
118
119                 $.each( positions, function( undef, pos ) {
120                     pos.line = cur.line;
121                 } );
122                 $.each( field.getSubfields(), function( undef, subfield ) {
123                     positions.push( { line: cur.line, ch: subfield.contentsStart } );
124                 } );
125
126                 // Allow to tab to start of empty field
127                 if ( field.getSubfields().length == 0 ) {
128                     positions.push( { line: cur.line, ch: 8 } );
129                 }
130
131                 return positions;
132             }
133         } else {
134             return [];
135         }
136     }
137
138     var _editorKeys = {
139         Enter: function( cm ) {
140             var cursor = cm.getCursor();
141             cm.replaceRange( '\n', { line: cursor.line }, null, 'marcAware' );
142             cm.setCursor( { line: cursor.line + 1, ch: 0 } );
143         },
144
145         'Shift-Enter': function( cm ) {
146             var cur = cm.getCursor();
147
148             cm.replaceRange( "\n", cur, null );
149         },
150
151         'Ctrl-X': function( cm ) {
152             // Delete line (or cut)
153             if ( cm.somethingSelected() ) return true;
154
155             cm.execCommand('deleteLine');
156         },
157
158         'Shift-Ctrl-X': function( cm ) {
159             // Delete subfield
160             var field = cm.marceditor.getCurrentField();
161             if ( !field ) return;
162
163             var subfield = field.getSubfieldAt( cm.getCursor().ch );
164             if ( subfield ) subfield.delete();
165         },
166
167         Tab: function( cm ) {
168             // Move through parts of tag/fixed fields
169             var positions = getTabPositions( cm.marceditor );
170             var cur = cm.getCursor();
171
172             for ( var i = 0; i < positions.length; i++ ) {
173                 if ( positions[i].ch > cur.ch ) {
174                     activateTabPosition( cm, positions[i] );
175                     return false;
176                 }
177             }
178
179             cm.setCursor( { line: cur.line + 1, ch: 0 } );
180         },
181
182         'Shift-Tab': function( cm ) {
183             // Move backwards through parts of tag/fixed fields
184             var positions = getTabPositions( cm.marceditor );
185             var cur = cm.getCursor();
186
187             for ( var i = positions.length - 1; i >= 0; i-- ) {
188                 if ( positions[i].ch < cur.ch ) {
189                     activateTabPosition( cm, positions[i], -1 );
190                     return false;
191                 }
192             }
193
194             if ( cur.line == 0 ) return;
195
196             var prevPositions = getTabPositions( cm.marceditor, { line: cur.line - 1, ch: cm.getLine( cur.line - 1 ).length } );
197
198             if ( prevPositions.length ) {
199                 activateTabPosition( cm, prevPositions[ prevPositions.length - 1 ], -1 );
200             } else {
201                 cm.setCursor( { line: cur.line - 1, ch: 0 } );
202             }
203         },
204
205         'Ctrl-D': function( cm ) {
206             // Insert subfield delimiter
207             var cur = cm.getCursor();
208
209             cm.replaceRange( "‡", cur, null );
210         },
211     };
212
213     // The objects below are part of a field/subfield manipulation API, accessed through the base
214     // editor object.
215     //
216     // Each one is tied to a particular line; this means that using a field or subfield object after
217     // any other changes to the record will cause entertaining explosions. The objects are meant to
218     // be temporary, and should only be reused with great care. The macro code does this only
219     // because it is careful to dispose of the object after any other updates.
220     //
221     // Note, however, tha you can continue to use a field object after changing subfields. It's just
222     // the subfield objects that become invalid.
223
224     // This is an exception raised by the EditorSubfield and EditorField when an invalid change is
225     // attempted.
226     function FieldError(line, message) {
227         this.line = line;
228         this.message = message;
229     };
230
231     FieldError.prototype.toString = function() {
232         return 'FieldError(' + this.line + ', "' + this.message + '")';
233     };
234
235     // This is the temporary object for a particular subfield in a field. Any change to any other
236     // subfields will invalidate this subfield object.
237     function EditorSubfield( field, index, start, end ) {
238         this.field = field;
239         this.index = index;
240         this.start = start;
241         this.end = end;
242
243         if ( this.field.isControlField ) {
244             this.contentsStart = start;
245             this.code = '@';
246         } else {
247             this.contentsStart = start + 2;
248             this.code =  this.field.contents.substr( this.start + 1, 1 );
249         }
250
251         this.cm = field.cm;
252
253         var marks = this.cm.findMarksAt( { line: field.line, ch: this.contentsStart } );
254         if ( marks[0] && marks[0].widget ) {
255             this.widget = marks[0].widget;
256
257             this.text = this.widget.text;
258             this.setText = this.widget.setText;
259             this.getFixed = this.widget.getFixed;
260             this.setFixed = this.widget.setFixed;
261         } else {
262             this.widget = null;
263             this.text = this.field.contents.substr( this.contentsStart, end - this.contentsStart );
264         }
265     };
266
267     $.extend( EditorSubfield.prototype, {
268         _invalid: function() {
269             return this.field._subfieldsInvalid();
270         },
271
272         delete: function() {
273             this.cm.replaceRange( "", { line: this.field.line, ch: this.start }, { line: this.field.line, ch: this.end }, 'marcAware' );
274         },
275         focus: function() {
276             this.cm.setCursor( { line: this.field.line, ch: this.contentsStart } );
277         },
278         focusEnd: function() {
279             this.cm.setCursor( { line: this.field.line, ch: this.end } );
280         },
281         getText: function() {
282             return this.text;
283         },
284         setText: function( text ) {
285             if ( !this._invalid() ) throw new FieldError( this.field.line, 'subfield invalid' );
286             this.cm.replaceRange( text, { line: this.field.line, ch: this.contentsStart }, { line: this.field.line, ch: this.end }, 'marcAware' );
287             this.field._invalidateSubfields();
288         },
289     } );
290
291     function EditorField( editor, line ) {
292         this.editor = editor;
293         this.line = line;
294
295         this.cm = editor.cm;
296
297         this._updateInfo();
298         this.tag = this.contents.substr( 0, 3 );
299         this.isControlField = ( this.tag < '010' );
300
301         if ( this.isControlField ) {
302             this._ind1 = this.contents.substr( 4, 1 );
303             this._ind2 = this.contents.substr( 6, 1 );
304         } else {
305             this._ind1 = null;
306             this._ind2 = null;
307         }
308
309         this.subfields = null;
310     }
311
312     $.extend( EditorField.prototype, {
313         _subfieldsInvalid: function() {
314             return !this.subfields;
315         },
316         _invalidateSubfields: function() {
317             this._subfields = null;
318         },
319
320         _updateInfo: function() {
321             this.info = this.editor.getLineInfo( { line: this.line, ch: 0 } );
322             if ( this.info == null ) throw new FieldError( 'Invalid field' );
323             this.contents = this.info.contents;
324         },
325         _scanSubfields: function() {
326             this._updateInfo();
327
328             if ( this.isControlField ) {
329                 this._subfields = [ new EditorSubfield( this, 0, 4, this.contents.length ) ];
330             } else {
331                 var field = this;
332                 var subfields = this.info.subfields;
333                 this._subfields = [];
334
335                 for (var i = 0; i < this.info.subfields.length; i++) {
336                     var end = i == subfields.length - 1 ? this.contents.length : subfields[i+1].ch;
337
338                     this._subfields.push( new EditorSubfield( this, i, subfields[i].ch, end ) );
339                 }
340             }
341         },
342
343         delete: function() {
344             this.cm.replaceRange( "", { line: this.line, ch: 0 }, { line: this.line + 1, ch: 0 }, 'marcAware' );
345         },
346         focus: function() {
347             this.cm.setCursor( { line: this.line, ch: 0 } );
348
349             return this;
350         },
351
352         getText: function() {
353             var result = '';
354
355             $.each( this.getSubfields(), function() {
356                 if ( this.code != '@' ) result += '‡' + this.code;
357
358                 result += this.getText();
359             } );
360
361             return result;
362         },
363         setText: function( text ) {
364             var indicator_match = /^([_ 0-9])([_ 0-9])\‡/.exec( text );
365             if ( indicator_match ) {
366                 text = text.substr(2);
367                 this.setIndicator1( indicator_match[1] );
368                 this.setIndicator2( indicator_match[2] );
369             }
370
371             this.cm.replaceRange( text, { line: this.line, ch: this.isControlField ? 4 : 8 }, { line: this.line }, 'marcAware' );
372             this._invalidateSubfields();
373
374             return this;
375         },
376
377         getIndicator1: function() {
378             return this._ind1;
379         },
380         getIndicator2: function() {
381             return this._ind2;
382         },
383         setIndicator1: function(val) {
384             if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
385
386             this._ind1 = ( !val || val == ' ' ) ? '_' : val;
387             this.cm.replaceRange( this._ind1, { line: this.line, ch: 4 }, { line: this.line, ch: 5 }, 'marcAware' );
388
389             return this;
390         },
391         setIndicator2: function(val) {
392             if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
393
394             this._ind2 = ( !val || val == ' ' ) ? '_' : val;
395             this.cm.replaceRange( this._ind2, { line: this.line, ch: 6 }, { line: this.line, ch: 7 }, 'marcAware' );
396
397             return this;
398         },
399
400         appendSubfield: function( code ) {
401             if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
402
403             this._invalidateSubfields();
404             this.cm.replaceRange( '‡' + code, { line: this.line }, null, 'marcAware' );
405             var subfields = this.getSubfields();
406
407             return subfields[ subfields.length - 1 ];
408         },
409         insertSubfield: function( code, position ) {
410             if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
411
412             position = position || 0;
413
414             var subfields = this.getSubfields();
415             this._invalidateSubfields();
416             this.cm.replaceRange( '‡' + code, { line: this.line, ch: subfields[position] ? subfields[position].start : null }, null, 'marcAware' );
417             subfields = this.getSubfields();
418
419             return subfields[ position ];
420         },
421         getSubfields: function( code ) {
422             if ( !this._subfields ) this._scanSubfields();
423             if ( code == null ) return this._subfields;
424
425             var result = [];
426
427             $.each( this._subfields, function() {
428                 if ( code == null || this.code == code ) result.push(this);
429             } );
430
431             return result;
432         },
433         getFirstSubfield: function( code ) {
434             var result = this.getSubfields( code );
435
436             return ( result && result.length ) ? result[0] : null;
437         },
438         getSubfieldAt: function( ch ) {
439             var subfields = this.getSubfields();
440
441             for (var i = 0; i < subfields.length; i++) {
442                 if ( subfields[i].start < ch && subfields[i].end >= ch ) return subfields[i];
443             }
444         },
445     } );
446
447     function MARCEditor( options ) {
448         this.cm = CodeMirror(
449             options.position,
450             {
451                 extraKeys: _editorKeys,
452                 gutters: [
453                     'modified-line-gutter',
454                 ],
455                 lineWrapping: true,
456                 mode: {
457                     name: 'marc',
458                     nonRepeatableTags: KohaBackend.GetTagsBy( '', 'repeatable', '0' ),
459                     nonRepeatableSubfields: KohaBackend.GetSubfieldsBy( '', 'repeatable', '0' )
460                 }
461             }
462         );
463         this.cm.marceditor = this;
464
465         this.cm.on( 'beforeChange', editorBeforeChange );
466         this.cm.on( 'changes', editorChanges );
467         this.cm.on( 'cursorActivity', editorCursorActivity );
468         this.cm.on( 'overwriteToggle', editorSetOverwriteMode );
469
470         this.onCursorActivity = options.onCursorActivity;
471
472         this.subscribers = [];
473         this.subscribe( function( marceditor ) {
474             Widget.Notify( marceditor );
475         } );
476     }
477
478     MARCEditor.FieldError = FieldError;
479
480     $.extend( MARCEditor.prototype, {
481         setUseWidgets: function( val ) {
482             if ( val ) {
483                 for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
484                     Widget.UpdateLine( this, line );
485                 }
486             } else {
487                 $.each( this.cm.getAllMarks(), function( undef, mark ) {
488                     if ( mark.widget ) mark.widget.clearToText();
489                 } );
490             }
491         },
492
493         focus: function() {
494             this.cm.focus();
495         },
496
497         getCursor: function() {
498             return this.cm.getCursor();
499         },
500
501         refresh: function() {
502             this.cm.refresh();
503         },
504
505         displayRecord: function( record ) {
506             this.cm.setValue( TextMARC.RecordToText(record) );
507             this.modified = false;
508         },
509
510         getRecord: function() {
511             this.textMode = true;
512
513             $.each( this.cm.getAllMarks(), function( undef, mark ) {
514                 if ( mark.widget ) mark.widget.clearToText();
515             } );
516             var record = TextMARC.TextToRecord( this.cm.getValue() );
517             for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
518                 if ( Preferences.user.fieldWidgets ) Widget.UpdateLine( this, line );
519             }
520
521             this.textMode = false;
522
523             return record;
524         },
525
526         getLineInfo: function( pos ) {
527             var contents = this.cm.getLine( pos.line );
528             if ( contents == null ) return {};
529
530             var tagNumber = contents.match( /^([A-Za-z0-9]{3})/ );
531
532             if ( !tagNumber ) return null; // No tag at all on this line
533             tagNumber = tagNumber[1];
534
535             if ( tagNumber < '010' ) return { tagNumber: tagNumber, contents: contents }; // No current subfield
536
537             var matcher = /‡([a-z0-9%])/g;
538             var match;
539
540             var subfields = [];
541             var currentSubfield;
542
543             while ( ( match = matcher.exec(contents) ) ) {
544                 subfields.push( { code: match[1], ch: match.index } );
545                 if ( match.index < pos.ch ) currentSubfield = match[1];
546             }
547
548             return { tagNumber: tagNumber, subfields: subfields, currentSubfield: currentSubfield, contents: contents };
549         },
550
551         addError: function( line, error ) {
552             var found = false;
553             var options = {};
554
555             if ( line == null ) {
556                 line = 0;
557                 options.above = true;
558             }
559
560             $.each( this.cm.getLineHandle(line).widgets || [], function( undef, widget ) {
561                 if ( !widget.isErrorMarker ) return;
562
563                 found = true;
564
565                 $( widget.node ).append( '; ' + error );
566                 widget.changed();
567
568                 return false;
569             } );
570
571             if ( found ) return;
572
573             var node = $( '<div class="structure-error"><i class="icon-remove"></i> ' + error + '</div>' )[0];
574             var widget = this.cm.addLineWidget( line, node, options );
575
576             widget.node = node;
577             widget.isErrorMarker = true;
578         },
579
580         removeErrors: function() {
581             for ( var line = 0; line < this.cm.lineCount(); line++ ) {
582                 $.each( this.cm.getLineHandle( line ).widgets || [], function( undef, lineWidget ) {
583                     if ( lineWidget.isErrorMarker ) lineWidget.clear();
584                 } );
585             }
586         },
587
588         startNotify: function() {
589             if ( this.notifyTimeout ) clearTimeout( this.notifyTimeout );
590             this.notifyTimeout = setTimeout( $.proxy( function() {
591                 this.notifyAll();
592
593                 this.notifyTimeout = null;
594             }, this ), NOTIFY_TIMEOUT );
595         },
596
597         notifyAll: function() {
598             $.each( this.subscribers, $.proxy( function( undef, subscriber ) {
599                 subscriber(this);
600             }, this ) );
601         },
602
603         subscribe: function( subscriber ) {
604             this.subscribers.push( subscriber );
605         },
606
607         createField: function( tag, line ) {
608             var contents = tag + ( tag < '010' ? ' ' : ' _ _ ' );
609
610             if ( line > this.cm.lastLine() ) {
611                 contents = '\n' + contents;
612             } else {
613                 contents = contents + '\n';
614             }
615
616             this.cm.replaceRange( contents, { line: line, ch: 0 }, null, 'marcAware' );
617
618             return new EditorField( this, line );
619         },
620
621         createFieldOrdered: function( tag ) {
622             var line, contents;
623
624             for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
625                 if ( contents && contents.substr(0, 3) > tag ) break;
626             }
627
628             return this.createField( tag, line );
629         },
630
631         createFieldGrouped: function( tag ) {
632             // Control fields should be inserted in actual order, whereas other fields should be
633             // inserted grouped
634             if ( tag < '010' ) return this.createFieldOrdered( tag );
635
636             var line, contents;
637
638             for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
639                 if ( contents && contents[0] > tag[0] ) break;
640             }
641
642             return this.createField( tag, line );
643         },
644
645         getFieldAt: function( line ) {
646             try {
647                 return new EditorField( this, line );
648             } catch (e) {
649                 return null;
650             }
651         },
652
653         getCurrentField: function() {
654             return this.getFieldAt( this.cm.getCursor().line );
655         },
656
657         getFields: function( tag ) {
658             var result = [];
659
660             if ( tag != null ) tag += ' ';
661
662             for ( var line = 0; line < this.cm.lineCount(); line++ ) {
663                 if ( tag && this.cm.getLine(line).substr( 0, 4 ) != tag ) continue;
664
665                 // If this throws a FieldError, pretend it doesn't exist
666                 try {
667                     result.push( new EditorField( this, line ) );
668                 } catch (e) {
669                     if ( !( e instanceof FieldError ) ) throw e;
670                 }
671             }
672
673             return result;
674         },
675
676         getFirstField: function( tag ) {
677             var result = this.getFields( tag );
678
679             return ( result && result.length ) ? result[0] : null;
680         },
681
682         getAllFields: function( tag ) {
683             return this.getFields( null );
684         },
685     } );
686
687     return MARCEditor;
688 } );