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 } );
138 var _editorKeys = {};
140 _editorKeys[insert_copyright] = function( cm ) {
141 cm.replaceRange( '©', cm.getCursor() );
144 _editorKeys[insert_copyright_sound] = function( cm ) {
145 cm.replaceRange( '℗', cm.getCursor() );
148 _editorKeys[new_line] = 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 _editorKeys[line_break] = function( cm ) {
155 var cur = cm.getCursor();
157 cm.replaceRange( "\n", cur, null );
160 _editorKeys[delete_field] = function( cm ) {
161 // Delete line (or cut)
162 if ( cm.somethingSelected() ) return true;
164 cm.execCommand('deleteLine');
167 _editorKeys[link_authorities] = 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 _editorKeys[delete_subfield] = 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 _editorKeys[next_position] = 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 _editorKeys[prev_position] = 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 _editorKeys[insert_delimiter] = function(cm){
239 var cur = cm.getCursor();
241 cm.replaceRange( "‡", cur, null );
244 _editorKeys[toggle_keyboard] = function( cm ) {
245 let keyboard = $(cm.getInputField()).getkeyboard();
246 keyboard.isVisible()?keyboard.close():keyboard.reveal();
249 // The objects below are part of a field/subfield manipulation API, accessed through the base
252 // Each one is tied to a particular line; this means that using a field or subfield object after
253 // any other changes to the record will cause entertaining explosions. The objects are meant to
254 // be temporary, and should only be reused with great care. The macro code does this only
255 // because it is careful to dispose of the object after any other updates.
257 // Note, however, tha you can continue to use a field object after changing subfields. It's just
258 // the subfield objects that become invalid.
260 // This is an exception raised by the EditorSubfield and EditorField when an invalid change is
262 function FieldError(line, message) {
264 this.message = message;
267 FieldError.prototype.toString = function() {
268 return 'FieldError(' + this.line + ', "' + this.message + '")';
271 // This is the temporary object for a particular subfield in a field. Any change to any other
272 // subfields will invalidate this subfield object.
273 function EditorSubfield( field, index, start, end ) {
279 if ( this.field.isControlField ) {
280 this.contentsStart = start;
283 this.contentsStart = start + 2;
284 this.code = this.field.contents.substr( this.start + 1, 1 );
289 var marks = this.cm.findMarksAt( { line: field.line, ch: this.contentsStart } );
290 if ( marks[0] && marks[0].widget ) {
291 this.widget = marks[0].widget;
293 this.text = this.widget.text;
294 this.setText = this.widget.setText;
295 this.getFixed = this.widget.getFixed;
296 this.setFixed = this.widget.setFixed;
299 this.text = this.field.contents.substr( this.contentsStart, end - this.contentsStart );
303 $.extend( EditorSubfield.prototype, {
304 _invalid: function() {
305 return this.field._subfieldsInvalid();
309 this.cm.replaceRange( "", { line: this.field.line, ch: this.start }, { line: this.field.line, ch: this.end }, 'marcAware' );
312 this.cm.setCursor( { line: this.field.line, ch: this.contentsStart } );
314 focusEnd: function() {
315 this.cm.setCursor( { line: this.field.line, ch: this.end } );
317 getText: function() {
320 setText: function( text ) {
321 if ( !this._invalid() ) throw new FieldError( this.field.line, 'subfield invalid' );
322 this.cm.replaceRange( text, { line: this.field.line, ch: this.contentsStart }, { line: this.field.line, ch: this.end }, 'marcAware' );
323 this.field._invalidateSubfields();
327 function EditorField( editor, line ) {
328 this.editor = editor;
334 this.tag = this.contents.substr( 0, 3 );
335 this.isControlField = ( this.tag < '010' );
337 if ( this.isControlField ) {
338 this._ind1 = this.contents.substr( 4, 1 );
339 this._ind2 = this.contents.substr( 6, 1 );
345 this.subfields = null;
348 $.extend( EditorField.prototype, {
349 _subfieldsInvalid: function() {
350 return !this.subfields;
352 _invalidateSubfields: function() {
353 this._subfields = null;
356 _updateInfo: function() {
357 this.info = this.editor.getLineInfo( { line: this.line, ch: 0 } );
358 if ( this.info == null ) throw new FieldError( 'Invalid field' );
359 this.contents = this.info.contents;
361 _scanSubfields: function() {
364 if ( this.isControlField ) {
365 this._subfields = [ new EditorSubfield( this, 0, 4, this.contents.length ) ];
368 var subfields = this.info.subfields;
369 this._subfields = [];
371 for (var i = 0; i < this.info.subfields.length; i++) {
372 var end = i == subfields.length - 1 ? this.contents.length : subfields[i+1].ch;
374 this._subfields.push( new EditorSubfield( this, i, subfields[i].ch, end ) );
380 this.cm.replaceRange( "", { line: this.line, ch: 0 }, { line: this.line + 1, ch: 0 }, 'marcAware' );
383 this.cm.setCursor( { line: this.line, ch: 0 } );
388 getText: function() {
391 $.each( this.getSubfields(), function() {
392 if ( this.code != '@' ) result += '‡' + this.code;
394 result += this.getText();
399 setText: function( text ) {
400 var indicator_match = /^([_ 0-9])([_ 0-9])\‡/.exec( text );
401 if ( indicator_match ) {
402 text = text.substr(2);
403 this.setIndicator1( indicator_match[1] );
404 this.setIndicator2( indicator_match[2] );
407 this.cm.replaceRange( text, { line: this.line, ch: this.isControlField ? 4 : 8 }, { line: this.line }, 'marcAware' );
408 this._invalidateSubfields();
413 getIndicator1: function() {
416 getIndicator2: function() {
419 setIndicator1: function(val) {
420 if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
422 this._ind1 = ( !val || val == ' ' ) ? '_' : val;
423 this.cm.replaceRange( this._ind1, { line: this.line, ch: 4 }, { line: this.line, ch: 5 }, 'marcAware' );
427 setIndicator2: function(val) {
428 if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
430 this._ind2 = ( !val || val == ' ' ) ? '_' : val;
431 this.cm.replaceRange( this._ind2, { line: this.line, ch: 6 }, { line: this.line, ch: 7 }, 'marcAware' );
436 appendSubfield: function( code ) {
437 if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
439 this._invalidateSubfields();
440 this.cm.replaceRange( '‡' + code, { line: this.line }, null, 'marcAware' );
441 var subfields = this.getSubfields();
443 return subfields[ subfields.length - 1 ];
445 insertSubfield: function( code, position ) {
446 if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
448 position = position || 0;
450 var subfields = this.getSubfields();
451 this._invalidateSubfields();
452 this.cm.replaceRange( '‡' + code, { line: this.line, ch: subfields[position] ? subfields[position].start : null }, null, 'marcAware' );
453 subfields = this.getSubfields();
455 return subfields[ position ];
457 getSubfields: function( code ) {
458 if ( !this._subfields ) this._scanSubfields();
459 if ( code == null ) return this._subfields;
463 $.each( this._subfields, function() {
464 if ( code == null || this.code == code ) result.push(this);
469 getFirstSubfield: function( code ) {
470 var result = this.getSubfields( code );
472 return ( result && result.length ) ? result[0] : null;
474 getSubfieldAt: function( ch ) {
475 var subfields = this.getSubfields();
477 for (var i = 0; i < subfields.length; i++) {
478 if ( subfields[i].start < ch && subfields[i].end >= ch ) return subfields[i];
483 function MARCEditor( options ) {
484 this.frameworkcode = '';
486 this.cm = CodeMirror(
489 extraKeys: _editorKeys,
491 'modified-line-gutter',
496 nonRepeatableTags: KohaBackend.GetTagsBy( '', 'repeatable', '0' ),
497 nonRepeatableSubfields: KohaBackend.GetSubfieldsBy( '', 'repeatable', '0' )
501 var inf = this.cm.getInputField();
503 var kb = $(inf).keyboard({
504 //keyBinding: "mousedown touchstart",
508 autoAcceptOnEsc: true,
513 of: $("#statusbar"), // optional - null (attach to input/textarea) or a jQuery object (attach elsewhere)
516 at2: 'center bottom' // used when "usePreview" is false (centers keyboard at bottom of the input/textarea)
518 beforeInsert: function(evnt, keyboard, elem, txt) {
519 var position = self.cm.getCursor();
521 self.cm.execCommand("delCharBefore");
523 if (txt === "\b" && position.ch === 0 && position.line !== 0) {
524 elem.value = self.cm.getLine(position.line) || "";
529 visible: function() {
530 $('#set-keyboard-layout').removeClass('hide');
532 hidden: function(e, keyboard, el, accepted) {
534 $('#set-keyboard-layout').addClass('hide');
539 Object.keys($.keyboard.layouts).forEach(function(layout) {
540 var div = $('#keyboard-layout .layouts').append('<div class="layout" data-layout="'+layout+'" data-name="'+($.keyboard.layouts[layout].name||layout)+'" >'+($.keyboard.layouts[layout].name||layout)+'</div>')
541 if(kb.layout == layout) {
542 div.addClass('active');
545 $('#keyboard-layout')
546 .on('show.bs.modal', function() {
548 $('#keyboard-layout .filter').focus();
549 $('#set-keyboard-layout').removeClass('hide');
551 .on('hide.bs.modal', function() {
552 !kb.isVisible() && kb.reveal();
554 $('#keyboard-layout .layout').click(function(event) {
555 $('#keyboard-layout .layout').removeClass('active');
556 $(this).addClass('active');
557 var layout = $(this).data().layout;
559 $('#keyboard-layout').modal('hide');
560 $('#keyboard-layout .filter').val('');
561 $('#keyboard-layout .layout').show();
563 $('#keyboard-layout .filter').keyup(function() {
564 var val = $(this).val();
565 if(!val||!val.length) return $('#keyboard-layout .layout').show();
566 var filter = new RegExp(val, 'i');
567 $('#keyboard-layout .layout').hide();
568 $('#keyboard-layout .layout').each(function() {
569 var name = $(this).data().name;
570 if(filter.test(name)) $(this).show();
574 this.cm.marceditor = this;
576 this.cm.on( 'beforeChange', editorBeforeChange );
577 this.cm.on( 'changes', editorChanges );
578 this.cm.on( 'cursorActivity', editorCursorActivity );
579 this.cm.on( 'overwriteToggle', editorSetOverwriteMode );
581 this.onCursorActivity = options.onCursorActivity;
583 this.subscribers = [];
584 this.subscribe( function( marceditor ) {
585 Widget.Notify( marceditor );
589 MARCEditor.FieldError = FieldError;
591 $.extend( MARCEditor.prototype, {
592 setUseWidgets: function( val ) {
594 for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
595 Widget.UpdateLine( this, line );
598 $.each( this.cm.getAllMarks(), function( undef, mark ) {
599 if ( mark.widget ) mark.widget.clearToText();
608 getCursor: function() {
609 return this.cm.getCursor();
612 refresh: function() {
616 setFrameworkCode: function( code, updateFields, callback ) {
617 this.frameworkcode = code;
618 $( 'a.change-framework i.selected' ).addClass( 'hidden' );
619 $( 'a.change-framework i.unselected' ).removeClass( 'hidden' );
620 $( 'a.change-framework[data-frameworkcode="' + code + '"] i.unselected' ).addClass( 'hidden' );
621 $( 'a.change-framework[data-frameworkcode="' + code + '"] i.selected' ).removeClass( 'hidden ');
623 KohaBackend.InitFramework( code, function ( error ) {
624 cm.setOption( 'mode', {
626 nonRepeatableTags: KohaBackend.GetTagsBy( code, 'repeatable', '0' ),
627 nonRepeatableSubfields: KohaBackend.GetSubfieldsBy( code, 'repeatable', '0' )
629 if ( updateFields ) {
630 var record = TextMARC.TextToRecord( cm.getValue() );
631 KohaBackend.FillRecord( code, record );
632 cm.setValue( TextMARC.RecordToText(record) );
638 displayRecord: function( record ) {
639 this.cm.setValue( TextMARC.RecordToText(record) );
640 this.modified = false;
641 this.setFrameworkCode(
642 typeof record.frameworkcode !== 'undefined' ? record.frameworkcode : '',
645 if ( typeof error !== 'undefined' ) {
646 humanMsg.displayAlert( _(error), { className: 'humanError' } );
652 getRecord: function() {
653 this.textMode = true;
655 $.each( this.cm.getAllMarks(), function( undef, mark ) {
656 if ( mark.widget ) mark.widget.clearToText();
658 var record = TextMARC.TextToRecord( this.cm.getValue() );
659 for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
660 if ( Preferences.user.fieldWidgets ) Widget.UpdateLine( this, line );
663 this.textMode = false;
665 record.frameworkcode = this.frameworkcode;
669 getLineInfo: function( pos ) {
670 var contents = this.cm.getLine( pos.line );
671 if ( contents == null ) return {};
673 var tagNumber = contents.match( /^([A-Za-z0-9]{3})/ );
675 if ( !tagNumber ) return null; // No tag at all on this line
676 tagNumber = tagNumber[1];
678 if ( tagNumber < '010' ) return { tagNumber: tagNumber, contents: contents }; // No current subfield
680 var matcher = /‡([a-z0-9%])/g;
686 while ( ( match = matcher.exec(contents) ) ) {
687 subfields.push( { code: match[1], ch: match.index } );
688 if ( match.index < pos.ch ) currentSubfield = match[1];
691 return { tagNumber: tagNumber, subfields: subfields, currentSubfield: currentSubfield, contents: contents };
694 addError: function( line, error ) {
698 if ( line == null ) {
700 options.above = true;
703 $.each( this.cm.getLineHandle(line).widgets || [], function( undef, widget ) {
704 if ( !widget.isErrorMarker ) return;
708 $( widget.node ).append( '; ' + error );
716 var node = $( '<div class="structure-error"><i class="fa fa-remove"></i> ' + error + '</div>' )[0];
717 var widget = this.cm.addLineWidget( line, node, options );
720 widget.isErrorMarker = true;
723 removeErrors: function() {
724 for ( var line = 0; line < this.cm.lineCount(); line++ ) {
725 $.each( this.cm.getLineHandle( line ).widgets || [], function( undef, lineWidget ) {
726 if ( lineWidget.isErrorMarker ) lineWidget.clear();
731 startNotify: function() {
732 if ( this.notifyTimeout ) clearTimeout( this.notifyTimeout );
733 this.notifyTimeout = setTimeout( $.proxy( function() {
736 this.notifyTimeout = null;
737 }, this ), NOTIFY_TIMEOUT );
740 notifyAll: function() {
741 $.each( this.subscribers, $.proxy( function( undef, subscriber ) {
746 subscribe: function( subscriber ) {
747 this.subscribers.push( subscriber );
750 createField: function( tag, line ) {
751 var contents = tag + ( tag < '010' ? ' ' : ' _ _ ' );
753 if ( line > this.cm.lastLine() ) {
754 contents = '\n' + contents;
756 contents = contents + '\n';
759 this.cm.replaceRange( contents, { line: line, ch: 0 }, null, 'marcAware' );
761 return new EditorField( this, line );
764 createFieldOrdered: function( tag ) {
767 for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
768 if ( contents && contents.substr(0, 3) > tag ) break;
771 return this.createField( tag, line );
774 createFieldGrouped: function( tag ) {
775 // Control fields should be inserted in actual order, whereas other fields should be
777 if ( tag < '010' ) return this.createFieldOrdered( tag );
781 for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
782 if ( contents && contents[0] > tag[0] ) break;
785 return this.createField( tag, line );
788 getFieldAt: function( line ) {
790 return new EditorField( this, line );
796 getCurrentField: function() {
797 return this.getFieldAt( this.cm.getCursor().line );
800 getFields: function( tag ) {
803 if ( tag != null ) tag += ' ';
805 for ( var line = 0; line < this.cm.lineCount(); line++ ) {
806 if ( tag && this.cm.getLine(line).substr( 0, 4 ) != tag ) continue;
808 // If this throws a FieldError, pretend it doesn't exist
810 result.push( new EditorField( this, line ) );
812 if ( !( e instanceof FieldError ) ) throw e;
819 getFirstField: function( tag ) {
820 var result = this.getFields( tag );
822 return ( result && result.length ) ? result[0] : null;
825 getAllFields: function( tag ) {
826 return this.getFields( null );