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 ) {
22 var NOTIFY_TIMEOUT = 250;
24 function editorCursorActivity( cm ) {
25 var editor = cm.marceditor;
26 var field = editor.getCurrentField();
29 // Set overwrite mode for tag numbers/indicators and contents of fixed fields
30 if ( field.isControlField || cm.getCursor().ch < 8 ) {
31 cm.toggleOverwrite(true);
33 cm.toggleOverwrite(false);
36 editor.onCursorActivity();
39 // This function exists to prevent inserting or partially deleting text that belongs to a
40 // widget. The 'marcAware' change source exists for other parts of the editor code to bypass
42 function editorBeforeChange( cm, change ) {
43 var editor = cm.marceditor;
44 if ( editor.textMode || change.origin == 'marcAware' || change.origin == 'widget.clearToText' ) return;
46 // FIXME: Should only cancel changes if this is a control field/subfield widget
47 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
49 if ( change.from.ch == change.to.ch - 1 && cm.findMarksAt( { line: change.from.line, ch: change.from.ch + 1 } ).length ) {
51 } else if ( change.from.ch == change.to.ch && cm.findMarksAt(change.from).length && !change.text[0] == '‡' ) {
56 function editorChanges( cm, changes ) {
57 var editor = cm.marceditor;
58 if ( editor.textMode ) return;
60 for (var i = 0; i < changes.length; i++) {
61 var change = changes[i];
63 var origin = change.from.line;
64 var newTo = CodeMirror.changeEnd(change);
66 for (var delLine = origin; delLine <= change.to.line; delLine++) {
67 // Line deleted; currently nothing to do
70 for (var line = origin; line <= newTo.line; line++) {
71 if ( Preferences.user.fieldWidgets ) Widget.UpdateLine( cm.marceditor, line );
72 if ( change.origin != 'setValue' && change.origin != 'marcWidgetPrefill' && change.origin != 'widget.clearToText' ) {
73 cm.addLineClass( line, 'wrapper', 'modified-line' );
74 editor.modified = true;
79 Widget.ActivateAt( cm, cm.getCursor() );
80 cm.marceditor.startNotify();
83 function editorSetOverwriteMode( cm, newState ) {
84 var editor = cm.marceditor;
86 editor.overwriteMode = newState;
89 // Editor helper functions
90 function activateTabPosition( cm, pos, idx ) {
91 // Allow tabbing to as-yet-nonexistent positions
92 var lenDiff = pos.ch - cm.getLine( pos.line ).length;
95 while ( lenDiff-- > 0 ) extra += ' ';
96 if ( pos.prefill ) extra += pos.prefill;
97 cm.replaceRange( extra, { line: pos.line } );
101 Widget.ActivateAt( cm, pos, idx );
104 function getTabPositions( editor, cur ) {
105 cur = cur || editor.cm.getCursor();
106 var field = editor.getFieldAt( cur.line );
109 if ( field.isControlField ) {
110 var positions = [ { ch: 0 }, { ch: 4 } ];
112 $.each( positions, function( undef, pos ) {
118 var positions = [ { ch: 0 }, { ch: 4, prefill: '_' }, { ch: 6, prefill: '_' } ];
120 $.each( positions, function( undef, pos ) {
123 $.each( field.getSubfields(), function( undef, subfield ) {
124 positions.push( { line: cur.line, ch: subfield.contentsStart } );
127 // Allow to tab to start of empty field
128 if ( field.getSubfields().length == 0 ) {
129 positions.push( { line: cur.line, ch: 8 } );
140 'Alt-C': function( cm ) {
141 cm.replaceRange( '©', cm.getCursor() );
144 'Alt-P': function( cm ) {
145 cm.replaceRange( '℗', cm.getCursor() );
148 Enter: function( cm ) {
149 var cursor = cm.getCursor();
150 cm.replaceRange( '\n', { line: cursor.line }, null, 'marcAware' );
151 cm.setCursor( { line: cursor.line + 1, ch: 0 } );
154 'Shift-Enter': function( cm ) {
155 var cur = cm.getCursor();
157 cm.replaceRange( "\n", cur, null );
160 'Ctrl-X': function( cm ) {
161 // Delete line (or cut)
162 if ( cm.somethingSelected() ) return true;
164 cm.execCommand('deleteLine');
167 'Shift-Ctrl-L': function( cm ) {
168 // Launch the auth search popup
169 var field = cm.marceditor.getCurrentField();
171 if ( !field ) return;
172 if ( authInfo[field.tag] == undefined ) return;
173 authtype = authInfo[field.tag].authtypecode;
174 index = 'tag_'+field.tag+'_rancor';
175 var mainmainstring = '';
176 if( field.getSubfields( authInfo[field.tag].subfield ).length != 0 ){
177 mainmainstring += field.getSubfields( authInfo[field.tag].subfield )[0].text;
180 var subfields = field.getSubfields();
182 for(i=0;i < subfields.length ;i++){
183 if ( authInfo[field.tag].subfield == subfields[i].code ) continue;
184 if( subfields[i].code == '9' ) continue;
185 mainstring += subfields[i].text+' ';
187 newin=window.open("../authorities/auth_finder.pl?source=biblio&authtypecode="+authtype+"&index="+index+"&value_mainstr="+encodeURI(mainmainstring)+"&value_main="+encodeURI(mainstring), "_blank",'width=700,height=550,toolbar=false,scrollbars=yes');
191 'Shift-Ctrl-X': function( cm ) {
193 var field = cm.marceditor.getCurrentField();
194 if ( !field ) return;
196 var subfield = field.getSubfieldAt( cm.getCursor().ch );
197 if ( subfield ) subfield.delete();
200 Tab: function( cm ) {
201 // Move through parts of tag/fixed fields
202 var positions = getTabPositions( cm.marceditor );
203 var cur = cm.getCursor();
205 for ( var i = 0; i < positions.length; i++ ) {
206 if ( positions[i].ch > cur.ch ) {
207 activateTabPosition( cm, positions[i] );
212 cm.setCursor( { line: cur.line + 1, ch: 0 } );
215 'Shift-Tab': function( cm ) {
216 // Move backwards through parts of tag/fixed fields
217 var positions = getTabPositions( cm.marceditor );
218 var cur = cm.getCursor();
220 for ( var i = positions.length - 1; i >= 0; i-- ) {
221 if ( positions[i].ch < cur.ch ) {
222 activateTabPosition( cm, positions[i], -1 );
227 if ( cur.line == 0 ) return;
229 var prevPositions = getTabPositions( cm.marceditor, { line: cur.line - 1, ch: cm.getLine( cur.line - 1 ).length } );
231 if ( prevPositions.length ) {
232 activateTabPosition( cm, prevPositions[ prevPositions.length - 1 ], -1 );
234 cm.setCursor( { line: cur.line - 1, ch: 0 } );
238 'Ctrl-D': function( cm ) {
239 // Insert subfield delimiter
240 var cur = cm.getCursor();
242 cm.replaceRange( "‡", cur, null );
246 // The objects below are part of a field/subfield manipulation API, accessed through the base
249 // Each one is tied to a particular line; this means that using a field or subfield object after
250 // any other changes to the record will cause entertaining explosions. The objects are meant to
251 // be temporary, and should only be reused with great care. The macro code does this only
252 // because it is careful to dispose of the object after any other updates.
254 // Note, however, tha you can continue to use a field object after changing subfields. It's just
255 // the subfield objects that become invalid.
257 // This is an exception raised by the EditorSubfield and EditorField when an invalid change is
259 function FieldError(line, message) {
261 this.message = message;
264 FieldError.prototype.toString = function() {
265 return 'FieldError(' + this.line + ', "' + this.message + '")';
268 // This is the temporary object for a particular subfield in a field. Any change to any other
269 // subfields will invalidate this subfield object.
270 function EditorSubfield( field, index, start, end ) {
276 if ( this.field.isControlField ) {
277 this.contentsStart = start;
280 this.contentsStart = start + 2;
281 this.code = this.field.contents.substr( this.start + 1, 1 );
286 var marks = this.cm.findMarksAt( { line: field.line, ch: this.contentsStart } );
287 if ( marks[0] && marks[0].widget ) {
288 this.widget = marks[0].widget;
290 this.text = this.widget.text;
291 this.setText = this.widget.setText;
292 this.getFixed = this.widget.getFixed;
293 this.setFixed = this.widget.setFixed;
296 this.text = this.field.contents.substr( this.contentsStart, end - this.contentsStart );
300 $.extend( EditorSubfield.prototype, {
301 _invalid: function() {
302 return this.field._subfieldsInvalid();
306 this.cm.replaceRange( "", { line: this.field.line, ch: this.start }, { line: this.field.line, ch: this.end }, 'marcAware' );
309 this.cm.setCursor( { line: this.field.line, ch: this.contentsStart } );
311 focusEnd: function() {
312 this.cm.setCursor( { line: this.field.line, ch: this.end } );
314 getText: function() {
317 setText: function( text ) {
318 if ( !this._invalid() ) throw new FieldError( this.field.line, 'subfield invalid' );
319 this.cm.replaceRange( text, { line: this.field.line, ch: this.contentsStart }, { line: this.field.line, ch: this.end }, 'marcAware' );
320 this.field._invalidateSubfields();
324 function EditorField( editor, line ) {
325 this.editor = editor;
331 this.tag = this.contents.substr( 0, 3 );
332 this.isControlField = ( this.tag < '010' );
334 if ( this.isControlField ) {
335 this._ind1 = this.contents.substr( 4, 1 );
336 this._ind2 = this.contents.substr( 6, 1 );
342 this.subfields = null;
345 $.extend( EditorField.prototype, {
346 _subfieldsInvalid: function() {
347 return !this.subfields;
349 _invalidateSubfields: function() {
350 this._subfields = null;
353 _updateInfo: function() {
354 this.info = this.editor.getLineInfo( { line: this.line, ch: 0 } );
355 if ( this.info == null ) throw new FieldError( 'Invalid field' );
356 this.contents = this.info.contents;
358 _scanSubfields: function() {
361 if ( this.isControlField ) {
362 this._subfields = [ new EditorSubfield( this, 0, 4, this.contents.length ) ];
365 var subfields = this.info.subfields;
366 this._subfields = [];
368 for (var i = 0; i < this.info.subfields.length; i++) {
369 var end = i == subfields.length - 1 ? this.contents.length : subfields[i+1].ch;
371 this._subfields.push( new EditorSubfield( this, i, subfields[i].ch, end ) );
377 this.cm.replaceRange( "", { line: this.line, ch: 0 }, { line: this.line + 1, ch: 0 }, 'marcAware' );
380 this.cm.setCursor( { line: this.line, ch: 0 } );
385 getText: function() {
388 $.each( this.getSubfields(), function() {
389 if ( this.code != '@' ) result += '‡' + this.code;
391 result += this.getText();
396 setText: function( text ) {
397 var indicator_match = /^([_ 0-9])([_ 0-9])\‡/.exec( text );
398 if ( indicator_match ) {
399 text = text.substr(2);
400 this.setIndicator1( indicator_match[1] );
401 this.setIndicator2( indicator_match[2] );
404 this.cm.replaceRange( text, { line: this.line, ch: this.isControlField ? 4 : 8 }, { line: this.line }, 'marcAware' );
405 this._invalidateSubfields();
410 getIndicator1: function() {
413 getIndicator2: function() {
416 setIndicator1: function(val) {
417 if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
419 this._ind1 = ( !val || val == ' ' ) ? '_' : val;
420 this.cm.replaceRange( this._ind1, { line: this.line, ch: 4 }, { line: this.line, ch: 5 }, 'marcAware' );
424 setIndicator2: function(val) {
425 if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
427 this._ind2 = ( !val || val == ' ' ) ? '_' : val;
428 this.cm.replaceRange( this._ind2, { line: this.line, ch: 6 }, { line: this.line, ch: 7 }, 'marcAware' );
433 appendSubfield: function( code ) {
434 if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
436 this._invalidateSubfields();
437 this.cm.replaceRange( '‡' + code, { line: this.line }, null, 'marcAware' );
438 var subfields = this.getSubfields();
440 return subfields[ subfields.length - 1 ];
442 insertSubfield: function( code, position ) {
443 if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
445 position = position || 0;
447 var subfields = this.getSubfields();
448 this._invalidateSubfields();
449 this.cm.replaceRange( '‡' + code, { line: this.line, ch: subfields[position] ? subfields[position].start : null }, null, 'marcAware' );
450 subfields = this.getSubfields();
452 return subfields[ position ];
454 getSubfields: function( code ) {
455 if ( !this._subfields ) this._scanSubfields();
456 if ( code == null ) return this._subfields;
460 $.each( this._subfields, function() {
461 if ( code == null || this.code == code ) result.push(this);
466 getFirstSubfield: function( code ) {
467 var result = this.getSubfields( code );
469 return ( result && result.length ) ? result[0] : null;
471 getSubfieldAt: function( ch ) {
472 var subfields = this.getSubfields();
474 for (var i = 0; i < subfields.length; i++) {
475 if ( subfields[i].start < ch && subfields[i].end >= ch ) return subfields[i];
480 function MARCEditor( options ) {
481 this.frameworkcode = '';
483 this.cm = CodeMirror(
486 extraKeys: _editorKeys,
488 'modified-line-gutter',
493 nonRepeatableTags: KohaBackend.GetTagsBy( '', 'repeatable', '0' ),
494 nonRepeatableSubfields: KohaBackend.GetSubfieldsBy( '', 'repeatable', '0' )
498 this.cm.marceditor = this;
500 this.cm.on( 'beforeChange', editorBeforeChange );
501 this.cm.on( 'changes', editorChanges );
502 this.cm.on( 'cursorActivity', editorCursorActivity );
503 this.cm.on( 'overwriteToggle', editorSetOverwriteMode );
505 this.onCursorActivity = options.onCursorActivity;
507 this.subscribers = [];
508 this.subscribe( function( marceditor ) {
509 Widget.Notify( marceditor );
513 MARCEditor.FieldError = FieldError;
515 $.extend( MARCEditor.prototype, {
516 setUseWidgets: function( val ) {
518 for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
519 Widget.UpdateLine( this, line );
522 $.each( this.cm.getAllMarks(), function( undef, mark ) {
523 if ( mark.widget ) mark.widget.clearToText();
532 getCursor: function() {
533 return this.cm.getCursor();
536 refresh: function() {
540 setFrameworkCode: function( code, callback ) {
541 this.frameworkcode = code;
542 $( 'a.change-framework i.selected' ).addClass( 'hidden' );
543 $( 'a.change-framework i.unselected' ).removeClass( 'hidden' );
544 $( 'a.change-framework[data-frameworkcode="' + code + '"] i.unselected' ).addClass( 'hidden' );
545 $( 'a.change-framework[data-frameworkcode="' + code + '"] i.selected' ).removeClass( 'hidden ');
546 KohaBackend.InitFramework( code, callback );
549 displayRecord: function( record ) {
550 this.cm.setValue( TextMARC.RecordToText(record) );
551 this.modified = false;
553 this.setFrameworkCode(
554 typeof record.frameworkcode !== 'undefined' ? record.frameworkcode : '',
556 if ( typeof error !== 'undefined' ) {
557 humanMsg.displayAlert( _(error), { className: 'humanError' } );
559 cm.setOption( 'mode', {
561 nonRepeatableTags: KohaBackend.GetTagsBy( this.frameworkcode, 'repeatable', '0' ),
562 nonRepeatableSubfields: KohaBackend.GetSubfieldsBy( this.frameworkcode, 'repeatable', '0' )
568 getRecord: function() {
569 this.textMode = true;
571 $.each( this.cm.getAllMarks(), function( undef, mark ) {
572 if ( mark.widget ) mark.widget.clearToText();
574 var record = TextMARC.TextToRecord( this.cm.getValue() );
575 for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
576 if ( Preferences.user.fieldWidgets ) Widget.UpdateLine( this, line );
579 this.textMode = false;
581 record.frameworkcode = this.frameworkcode;
585 getLineInfo: function( pos ) {
586 var contents = this.cm.getLine( pos.line );
587 if ( contents == null ) return {};
589 var tagNumber = contents.match( /^([A-Za-z0-9]{3})/ );
591 if ( !tagNumber ) return null; // No tag at all on this line
592 tagNumber = tagNumber[1];
594 if ( tagNumber < '010' ) return { tagNumber: tagNumber, contents: contents }; // No current subfield
596 var matcher = /‡([a-z0-9%])/g;
602 while ( ( match = matcher.exec(contents) ) ) {
603 subfields.push( { code: match[1], ch: match.index } );
604 if ( match.index < pos.ch ) currentSubfield = match[1];
607 return { tagNumber: tagNumber, subfields: subfields, currentSubfield: currentSubfield, contents: contents };
610 addError: function( line, error ) {
614 if ( line == null ) {
616 options.above = true;
619 $.each( this.cm.getLineHandle(line).widgets || [], function( undef, widget ) {
620 if ( !widget.isErrorMarker ) return;
624 $( widget.node ).append( '; ' + error );
632 var node = $( '<div class="structure-error"><i class="fa fa-remove"></i> ' + error + '</div>' )[0];
633 var widget = this.cm.addLineWidget( line, node, options );
636 widget.isErrorMarker = true;
639 removeErrors: function() {
640 for ( var line = 0; line < this.cm.lineCount(); line++ ) {
641 $.each( this.cm.getLineHandle( line ).widgets || [], function( undef, lineWidget ) {
642 if ( lineWidget.isErrorMarker ) lineWidget.clear();
647 startNotify: function() {
648 if ( this.notifyTimeout ) clearTimeout( this.notifyTimeout );
649 this.notifyTimeout = setTimeout( $.proxy( function() {
652 this.notifyTimeout = null;
653 }, this ), NOTIFY_TIMEOUT );
656 notifyAll: function() {
657 $.each( this.subscribers, $.proxy( function( undef, subscriber ) {
662 subscribe: function( subscriber ) {
663 this.subscribers.push( subscriber );
666 createField: function( tag, line ) {
667 var contents = tag + ( tag < '010' ? ' ' : ' _ _ ' );
669 if ( line > this.cm.lastLine() ) {
670 contents = '\n' + contents;
672 contents = contents + '\n';
675 this.cm.replaceRange( contents, { line: line, ch: 0 }, null, 'marcAware' );
677 return new EditorField( this, line );
680 createFieldOrdered: function( tag ) {
683 for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
684 if ( contents && contents.substr(0, 3) > tag ) break;
687 return this.createField( tag, line );
690 createFieldGrouped: function( tag ) {
691 // Control fields should be inserted in actual order, whereas other fields should be
693 if ( tag < '010' ) return this.createFieldOrdered( tag );
697 for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
698 if ( contents && contents[0] > tag[0] ) break;
701 return this.createField( tag, line );
704 getFieldAt: function( line ) {
706 return new EditorField( this, line );
712 getCurrentField: function() {
713 return this.getFieldAt( this.cm.getCursor().line );
716 getFields: function( tag ) {
719 if ( tag != null ) tag += ' ';
721 for ( var line = 0; line < this.cm.lineCount(); line++ ) {
722 if ( tag && this.cm.getLine(line).substr( 0, 4 ) != tag ) continue;
724 // If this throws a FieldError, pretend it doesn't exist
726 result.push( new EditorField( this, line ) );
728 if ( !( e instanceof FieldError ) ) throw e;
735 getFirstField: function( tag ) {
736 var result = this.getFields( tag );
738 return ( result && result.length ) ? result[0] : null;
741 getAllFields: function( tag ) {
742 return this.getFields( null );