2 * Copyright 2015 ByWater Solutions
4 * This file is part of Koha.
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.
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.
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>.
20 define( [ 'marc-record', 'koha-backend', 'preferences', 'text-marc', 'widget' ], function( MARC, KohaBackend, Preferences, TextMARC, Widget ) {
21 var NOTIFY_TIMEOUT = 250;
23 function editorCursorActivity( cm ) {
24 var editor = cm.marceditor;
25 var field = editor.getCurrentField();
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);
32 cm.toggleOverwrite(false);
35 editor.onCursorActivity();
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
41 function editorBeforeChange( cm, change ) {
42 var editor = cm.marceditor;
43 if ( editor.textMode || change.origin == 'marcAware' || change.origin == 'widget.clearToText' ) return;
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
48 if ( change.from.ch == change.to.ch - 1 && cm.findMarksAt( { line: change.from.line, ch: change.from.ch + 1 } ).length ) {
50 } else if ( change.from.ch == change.to.ch && cm.findMarksAt(change.from).length && !change.text[0] == '‡' ) {
55 function editorChanges( cm, changes ) {
56 var editor = cm.marceditor;
57 if ( editor.textMode ) return;
59 for (var i = 0; i < changes.length; i++) {
60 var change = changes[i];
62 var origin = change.from.line;
63 var newTo = CodeMirror.changeEnd(change);
65 for (var delLine = origin; delLine <= change.to.line; delLine++) {
66 // Line deleted; currently nothing to do
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;
78 Widget.ActivateAt( cm, cm.getCursor() );
79 cm.marceditor.startNotify();
82 function editorSetOverwriteMode( cm, newState ) {
83 var editor = cm.marceditor;
85 editor.overwriteMode = newState;
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;
94 while ( lenDiff-- > 0 ) extra += ' ';
95 if ( pos.prefill ) extra += pos.prefill;
96 cm.replaceRange( extra, { line: pos.line } );
100 Widget.ActivateAt( cm, pos, idx );
103 function getTabPositions( editor, cur ) {
104 cur = cur || editor.cm.getCursor();
105 var field = editor.getFieldAt( cur.line );
108 if ( field.isControlField ) {
109 var positions = [ { ch: 0 }, { ch: 4 } ];
111 $.each( positions, function( undef, pos ) {
117 var positions = [ { ch: 0 }, { ch: 4, prefill: '_' }, { ch: 6, prefill: '_' } ];
119 $.each( positions, function( undef, pos ) {
122 $.each( field.getSubfields(), function( undef, subfield ) {
123 positions.push( { line: cur.line, ch: subfield.contentsStart } );
126 // Allow to tab to start of empty field
127 if ( field.getSubfields().length == 0 ) {
128 positions.push( { line: cur.line, ch: 8 } );
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 } );
145 'Shift-Enter': function( cm ) {
146 var cur = cm.getCursor();
148 cm.replaceRange( "\n", cur, null );
151 'Ctrl-X': function( cm ) {
152 // Delete line (or cut)
153 if ( cm.somethingSelected() ) return true;
155 cm.execCommand('deleteLine');
158 'Shift-Ctrl-X': function( cm ) {
160 var field = cm.marceditor.getCurrentField();
161 if ( !field ) return;
163 var subfield = field.getSubfieldAt( cm.getCursor().ch );
164 if ( subfield ) subfield.delete();
167 Tab: function( cm ) {
168 // Move through parts of tag/fixed fields
169 var positions = getTabPositions( cm.marceditor );
170 var cur = cm.getCursor();
172 for ( var i = 0; i < positions.length; i++ ) {
173 if ( positions[i].ch > cur.ch ) {
174 activateTabPosition( cm, positions[i] );
179 cm.setCursor( { line: cur.line + 1, ch: 0 } );
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();
187 for ( var i = positions.length - 1; i >= 0; i-- ) {
188 if ( positions[i].ch < cur.ch ) {
189 activateTabPosition( cm, positions[i], -1 );
194 if ( cur.line == 0 ) return;
196 var prevPositions = getTabPositions( cm.marceditor, { line: cur.line - 1, ch: cm.getLine( cur.line - 1 ).length } );
198 if ( prevPositions.length ) {
199 activateTabPosition( cm, prevPositions[ prevPositions.length - 1 ], -1 );
201 cm.setCursor( { line: cur.line - 1, ch: 0 } );
205 'Ctrl-D': function( cm ) {
206 // Insert subfield delimiter
207 var cur = cm.getCursor();
209 cm.replaceRange( "‡", cur, null );
213 // The objects below are part of a field/subfield manipulation API, accessed through the base
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.
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.
224 // This is an exception raised by the EditorSubfield and EditorField when an invalid change is
226 function FieldError(line, message) {
228 this.message = message;
231 FieldError.prototype.toString = function() {
232 return 'FieldError(' + this.line + ', "' + this.message + '")';
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 ) {
243 if ( this.field.isControlField ) {
244 this.contentsStart = start;
247 this.contentsStart = start + 2;
248 this.code = this.field.contents.substr( this.start + 1, 1 );
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;
257 this.text = this.widget.text;
258 this.setText = this.widget.setText;
259 this.getFixed = this.widget.getFixed;
260 this.setFixed = this.widget.setFixed;
263 this.text = this.field.contents.substr( this.contentsStart, end - this.contentsStart );
267 $.extend( EditorSubfield.prototype, {
268 _invalid: function() {
269 return this.field._subfieldsInvalid();
273 this.cm.replaceRange( "", { line: this.field.line, ch: this.start }, { line: this.field.line, ch: this.end }, 'marcAware' );
276 this.cm.setCursor( { line: this.field.line, ch: this.contentsStart } );
278 focusEnd: function() {
279 this.cm.setCursor( { line: this.field.line, ch: this.end } );
281 getText: function() {
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();
291 function EditorField( editor, line ) {
292 this.editor = editor;
298 this.tag = this.contents.substr( 0, 3 );
299 this.isControlField = ( this.tag < '010' );
301 if ( this.isControlField ) {
302 this._ind1 = this.contents.substr( 4, 1 );
303 this._ind2 = this.contents.substr( 6, 1 );
309 this.subfields = null;
312 $.extend( EditorField.prototype, {
313 _subfieldsInvalid: function() {
314 return !this.subfields;
316 _invalidateSubfields: function() {
317 this._subfields = null;
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;
325 _scanSubfields: function() {
328 if ( this.isControlField ) {
329 this._subfields = [ new EditorSubfield( this, 0, 4, this.contents.length ) ];
332 var subfields = this.info.subfields;
333 this._subfields = [];
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;
338 this._subfields.push( new EditorSubfield( this, i, subfields[i].ch, end ) );
344 this.cm.replaceRange( "", { line: this.line, ch: 0 }, { line: this.line + 1, ch: 0 }, 'marcAware' );
347 this.cm.setCursor( { line: this.line, ch: 0 } );
352 getText: function() {
355 $.each( this.getSubfields(), function() {
356 if ( this.code != '@' ) result += '‡' + this.code;
358 result += this.getText();
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] );
371 this.cm.replaceRange( text, { line: this.line, ch: this.isControlField ? 4 : 8 }, { line: this.line }, 'marcAware' );
372 this._invalidateSubfields();
377 getIndicator1: function() {
380 getIndicator2: function() {
383 setIndicator1: function(val) {
384 if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
386 this._ind1 = ( !val || val == ' ' ) ? '_' : val;
387 this.cm.replaceRange( this._ind1, { line: this.line, ch: 4 }, { line: this.line, ch: 5 }, 'marcAware' );
391 setIndicator2: function(val) {
392 if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
394 this._ind2 = ( !val || val == ' ' ) ? '_' : val;
395 this.cm.replaceRange( this._ind2, { line: this.line, ch: 6 }, { line: this.line, ch: 7 }, 'marcAware' );
400 appendSubfield: function( code ) {
401 if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
403 this._invalidateSubfields();
404 this.cm.replaceRange( '‡' + code, { line: this.line }, null, 'marcAware' );
405 var subfields = this.getSubfields();
407 return subfields[ subfields.length - 1 ];
409 insertSubfield: function( code, position ) {
410 if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
412 position = position || 0;
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();
419 return subfields[ position ];
421 getSubfields: function( code ) {
422 if ( !this._subfields ) this._scanSubfields();
423 if ( code == null ) return this._subfields;
427 $.each( this._subfields, function() {
428 if ( code == null || this.code == code ) result.push(this);
433 getFirstSubfield: function( code ) {
434 var result = this.getSubfields( code );
436 return ( result && result.length ) ? result[0] : null;
438 getSubfieldAt: function( ch ) {
439 var subfields = this.getSubfields();
441 for (var i = 0; i < subfields.length; i++) {
442 if ( subfields[i].start < ch && subfields[i].end >= ch ) return subfields[i];
447 function MARCEditor( options ) {
448 this.cm = CodeMirror(
451 extraKeys: _editorKeys,
453 'modified-line-gutter',
458 nonRepeatableTags: KohaBackend.GetTagsBy( '', 'repeatable', '0' ),
459 nonRepeatableSubfields: KohaBackend.GetSubfieldsBy( '', 'repeatable', '0' )
463 this.cm.marceditor = this;
465 this.cm.on( 'beforeChange', editorBeforeChange );
466 this.cm.on( 'changes', editorChanges );
467 this.cm.on( 'cursorActivity', editorCursorActivity );
468 this.cm.on( 'overwriteToggle', editorSetOverwriteMode );
470 this.onCursorActivity = options.onCursorActivity;
472 this.subscribers = [];
473 this.subscribe( function( marceditor ) {
474 Widget.Notify( marceditor );
478 MARCEditor.FieldError = FieldError;
480 $.extend( MARCEditor.prototype, {
481 setUseWidgets: function( val ) {
483 for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
484 Widget.UpdateLine( this, line );
487 $.each( this.cm.getAllMarks(), function( undef, mark ) {
488 if ( mark.widget ) mark.widget.clearToText();
497 getCursor: function() {
498 return this.cm.getCursor();
501 refresh: function() {
505 displayRecord: function( record ) {
506 this.cm.setValue( TextMARC.RecordToText(record) );
507 this.modified = false;
510 getRecord: function() {
511 this.textMode = true;
513 $.each( this.cm.getAllMarks(), function( undef, mark ) {
514 if ( mark.widget ) mark.widget.clearToText();
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 );
521 this.textMode = false;
526 getLineInfo: function( pos ) {
527 var contents = this.cm.getLine( pos.line );
528 if ( contents == null ) return {};
530 var tagNumber = contents.match( /^([A-Za-z0-9]{3})/ );
532 if ( !tagNumber ) return null; // No tag at all on this line
533 tagNumber = tagNumber[1];
535 if ( tagNumber < '010' ) return { tagNumber: tagNumber, contents: contents }; // No current subfield
537 var matcher = /‡([a-z0-9%])/g;
543 while ( ( match = matcher.exec(contents) ) ) {
544 subfields.push( { code: match[1], ch: match.index } );
545 if ( match.index < pos.ch ) currentSubfield = match[1];
548 return { tagNumber: tagNumber, subfields: subfields, currentSubfield: currentSubfield, contents: contents };
551 addError: function( line, error ) {
555 if ( line == null ) {
557 options.above = true;
560 $.each( this.cm.getLineHandle(line).widgets || [], function( undef, widget ) {
561 if ( !widget.isErrorMarker ) return;
565 $( widget.node ).append( '; ' + error );
573 var node = $( '<div class="structure-error"><i class="icon-remove"></i> ' + error + '</div>' )[0];
574 var widget = this.cm.addLineWidget( line, node, options );
577 widget.isErrorMarker = true;
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();
588 startNotify: function() {
589 if ( this.notifyTimeout ) clearTimeout( this.notifyTimeout );
590 this.notifyTimeout = setTimeout( $.proxy( function() {
593 this.notifyTimeout = null;
594 }, this ), NOTIFY_TIMEOUT );
597 notifyAll: function() {
598 $.each( this.subscribers, $.proxy( function( undef, subscriber ) {
603 subscribe: function( subscriber ) {
604 this.subscribers.push( subscriber );
607 createField: function( tag, line ) {
608 var contents = tag + ( tag < '010' ? ' ' : ' _ _ ' );
610 if ( line > this.cm.lastLine() ) {
611 contents = '\n' + contents;
613 contents = contents + '\n';
616 this.cm.replaceRange( contents, { line: line, ch: 0 }, null, 'marcAware' );
618 return new EditorField( this, line );
621 createFieldOrdered: function( tag ) {
624 for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
625 if ( contents && contents.substr(0, 3) > tag ) break;
628 return this.createField( tag, line );
631 createFieldGrouped: function( tag ) {
632 // Control fields should be inserted in actual order, whereas other fields should be
634 if ( tag < '010' ) return this.createFieldOrdered( tag );
638 for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
639 if ( contents && contents[0] > tag[0] ) break;
642 return this.createField( tag, line );
645 getFieldAt: function( line ) {
647 return new EditorField( this, line );
653 getCurrentField: function() {
654 return this.getFieldAt( this.cm.getCursor().line );
657 getFields: function( tag ) {
660 if ( tag != null ) tag += ' ';
662 for ( var line = 0; line < this.cm.lineCount(); line++ ) {
663 if ( tag && this.cm.getLine(line).substr( 0, 4 ) != tag ) continue;
665 // If this throws a FieldError, pretend it doesn't exist
667 result.push( new EditorField( this, line ) );
669 if ( !( e instanceof FieldError ) ) throw e;
676 getFirstField: function( tag ) {
677 var result = this.getFields( tag );
679 return ( result && result.length ) ? result[0] : null;
682 getAllFields: function( tag ) {
683 return this.getFields( null );