Bug 18904: (QA follow-up) Do not put authid in searchbox of blinddetail
[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
22     var NOTIFY_TIMEOUT = 250;
23
24     function editorCursorActivity( cm ) {
25         var editor = cm.marceditor;
26         var field = editor.getCurrentField();
27         if ( !field ) return;
28
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);
32         } else {
33             cm.toggleOverwrite(false);
34         }
35
36         editor.onCursorActivity();
37     }
38
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
41     // this check.
42     function editorBeforeChange( cm, change ) {
43         var editor = cm.marceditor;
44         if ( editor.textMode || change.origin == 'marcAware' || change.origin == 'widget.clearToText' ) return;
45
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
48
49         if ( change.from.ch == change.to.ch - 1 && cm.findMarksAt( { line: change.from.line, ch: change.from.ch + 1 } ).length ) {
50             change.cancel();
51         } else if ( change.from.ch == change.to.ch && cm.findMarksAt(change.from).length && !change.text[0] == '‡' ) {
52             change.cancel();
53         }
54     }
55
56     function editorChanges( cm, changes ) {
57         var editor = cm.marceditor;
58         if ( editor.textMode ) return;
59
60         for (var i = 0; i < changes.length; i++) {
61             var change = changes[i];
62
63             var origin = change.from.line;
64             var newTo = CodeMirror.changeEnd(change);
65
66             for (var delLine = origin; delLine <= change.to.line; delLine++) {
67                 // Line deleted; currently nothing to do
68             }
69
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;
75                 }
76             }
77         }
78
79         Widget.ActivateAt( cm, cm.getCursor() );
80         cm.marceditor.startNotify();
81     }
82
83     function editorSetOverwriteMode( cm, newState ) {
84         var editor = cm.marceditor;
85
86         editor.overwriteMode = newState;
87     }
88
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;
93         if ( lenDiff > 0 ) {
94             var extra = '';
95             while ( lenDiff-- > 0 ) extra += ' ';
96             if ( pos.prefill ) extra += pos.prefill;
97             cm.replaceRange( extra, { line: pos.line } );
98         }
99
100         cm.setCursor( pos );
101         Widget.ActivateAt( cm, pos, idx );
102     }
103
104     function getTabPositions( editor, cur ) {
105         cur = cur || editor.cm.getCursor();
106         var field = editor.getFieldAt( cur.line );
107
108         if ( field ) {
109             if ( field.isControlField ) {
110                 var positions = [ { ch: 0 }, { ch: 4 } ];
111
112                 $.each( positions, function( undef, pos ) {
113                     pos.line = cur.line;
114                 } );
115
116                 return positions;
117             } else {
118                 var positions = [ { ch: 0 }, { ch: 4, prefill: '_' }, { ch: 6, prefill: '_' } ];
119
120                 $.each( positions, function( undef, pos ) {
121                     pos.line = cur.line;
122                 } );
123                 $.each( field.getSubfields(), function( undef, subfield ) {
124                     positions.push( { line: cur.line, ch: subfield.contentsStart } );
125                 } );
126
127                 // Allow to tab to start of empty field
128                 if ( field.getSubfields().length == 0 ) {
129                     positions.push( { line: cur.line, ch: 8 } );
130                 }
131
132                 return positions;
133             }
134         } else {
135             return [];
136         }
137     }
138
139     var _editorKeys = {
140         'Alt-C': function( cm ) {
141             cm.replaceRange( '©', cm.getCursor() );
142         },
143
144         'Alt-P': function( cm ) {
145             cm.replaceRange( '℗', cm.getCursor() );
146         },
147
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 } );
152         },
153
154         'Shift-Enter': function( cm ) {
155             var cur = cm.getCursor();
156
157             cm.replaceRange( "\n", cur, null );
158         },
159
160         'Ctrl-X': function( cm ) {
161             // Delete line (or cut)
162             if ( cm.somethingSelected() ) return true;
163
164             cm.execCommand('deleteLine');
165         },
166
167         'Ctrl-L': function( cm ) {
168             // Launch the auth search popup
169             var field = cm.marceditor.getCurrentField();
170
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;
178             }
179
180             var subfields = field.getSubfields();
181             var mainstring= '';
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+' ';
186             }
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');
188
189         },
190
191         'Shift-Ctrl-X': function( cm ) {
192             // Delete subfield
193             var field = cm.marceditor.getCurrentField();
194             if ( !field ) return;
195
196             var subfield = field.getSubfieldAt( cm.getCursor().ch );
197             if ( subfield ) subfield.delete();
198         },
199
200         Tab: function( cm ) {
201             // Move through parts of tag/fixed fields
202             var positions = getTabPositions( cm.marceditor );
203             var cur = cm.getCursor();
204
205             for ( var i = 0; i < positions.length; i++ ) {
206                 if ( positions[i].ch > cur.ch ) {
207                     activateTabPosition( cm, positions[i] );
208                     return false;
209                 }
210             }
211
212             cm.setCursor( { line: cur.line + 1, ch: 0 } );
213         },
214
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();
219
220             for ( var i = positions.length - 1; i >= 0; i-- ) {
221                 if ( positions[i].ch < cur.ch ) {
222                     activateTabPosition( cm, positions[i], -1 );
223                     return false;
224                 }
225             }
226
227             if ( cur.line == 0 ) return;
228
229             var prevPositions = getTabPositions( cm.marceditor, { line: cur.line - 1, ch: cm.getLine( cur.line - 1 ).length } );
230
231             if ( prevPositions.length ) {
232                 activateTabPosition( cm, prevPositions[ prevPositions.length - 1 ], -1 );
233             } else {
234                 cm.setCursor( { line: cur.line - 1, ch: 0 } );
235             }
236         },
237
238         'Ctrl-D': function( cm ) {
239             // Insert subfield delimiter
240             var cur = cm.getCursor();
241
242             cm.replaceRange( "‡", cur, null );
243         },
244     };
245
246     // The objects below are part of a field/subfield manipulation API, accessed through the base
247     // editor object.
248     //
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.
253     //
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.
256
257     // This is an exception raised by the EditorSubfield and EditorField when an invalid change is
258     // attempted.
259     function FieldError(line, message) {
260         this.line = line;
261         this.message = message;
262     };
263
264     FieldError.prototype.toString = function() {
265         return 'FieldError(' + this.line + ', "' + this.message + '")';
266     };
267
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 ) {
271         this.field = field;
272         this.index = index;
273         this.start = start;
274         this.end = end;
275
276         if ( this.field.isControlField ) {
277             this.contentsStart = start;
278             this.code = '@';
279         } else {
280             this.contentsStart = start + 2;
281             this.code =  this.field.contents.substr( this.start + 1, 1 );
282         }
283
284         this.cm = field.cm;
285
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;
289
290             this.text = this.widget.text;
291             this.setText = this.widget.setText;
292             this.getFixed = this.widget.getFixed;
293             this.setFixed = this.widget.setFixed;
294         } else {
295             this.widget = null;
296             this.text = this.field.contents.substr( this.contentsStart, end - this.contentsStart );
297         }
298     };
299
300     $.extend( EditorSubfield.prototype, {
301         _invalid: function() {
302             return this.field._subfieldsInvalid();
303         },
304
305         delete: function() {
306             this.cm.replaceRange( "", { line: this.field.line, ch: this.start }, { line: this.field.line, ch: this.end }, 'marcAware' );
307         },
308         focus: function() {
309             this.cm.setCursor( { line: this.field.line, ch: this.contentsStart } );
310         },
311         focusEnd: function() {
312             this.cm.setCursor( { line: this.field.line, ch: this.end } );
313         },
314         getText: function() {
315             return this.text;
316         },
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();
321         },
322     } );
323
324     function EditorField( editor, line ) {
325         this.editor = editor;
326         this.line = line;
327
328         this.cm = editor.cm;
329
330         this._updateInfo();
331         this.tag = this.contents.substr( 0, 3 );
332         this.isControlField = ( this.tag < '010' );
333
334         if ( this.isControlField ) {
335             this._ind1 = this.contents.substr( 4, 1 );
336             this._ind2 = this.contents.substr( 6, 1 );
337         } else {
338             this._ind1 = null;
339             this._ind2 = null;
340         }
341
342         this.subfields = null;
343     }
344
345     $.extend( EditorField.prototype, {
346         _subfieldsInvalid: function() {
347             return !this.subfields;
348         },
349         _invalidateSubfields: function() {
350             this._subfields = null;
351         },
352
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;
357         },
358         _scanSubfields: function() {
359             this._updateInfo();
360
361             if ( this.isControlField ) {
362                 this._subfields = [ new EditorSubfield( this, 0, 4, this.contents.length ) ];
363             } else {
364                 var field = this;
365                 var subfields = this.info.subfields;
366                 this._subfields = [];
367
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;
370
371                     this._subfields.push( new EditorSubfield( this, i, subfields[i].ch, end ) );
372                 }
373             }
374         },
375
376         delete: function() {
377             this.cm.replaceRange( "", { line: this.line, ch: 0 }, { line: this.line + 1, ch: 0 }, 'marcAware' );
378         },
379         focus: function() {
380             this.cm.setCursor( { line: this.line, ch: 0 } );
381
382             return this;
383         },
384
385         getText: function() {
386             var result = '';
387
388             $.each( this.getSubfields(), function() {
389                 if ( this.code != '@' ) result += '‡' + this.code;
390
391                 result += this.getText();
392             } );
393
394             return result;
395         },
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] );
402             }
403
404             this.cm.replaceRange( text, { line: this.line, ch: this.isControlField ? 4 : 8 }, { line: this.line }, 'marcAware' );
405             this._invalidateSubfields();
406
407             return this;
408         },
409
410         getIndicator1: function() {
411             return this._ind1;
412         },
413         getIndicator2: function() {
414             return this._ind2;
415         },
416         setIndicator1: function(val) {
417             if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
418
419             this._ind1 = ( !val || val == ' ' ) ? '_' : val;
420             this.cm.replaceRange( this._ind1, { line: this.line, ch: 4 }, { line: this.line, ch: 5 }, 'marcAware' );
421
422             return this;
423         },
424         setIndicator2: function(val) {
425             if ( this.isControlField ) throw new FieldError('Cannot set indicators on control field');
426
427             this._ind2 = ( !val || val == ' ' ) ? '_' : val;
428             this.cm.replaceRange( this._ind2, { line: this.line, ch: 6 }, { line: this.line, ch: 7 }, 'marcAware' );
429
430             return this;
431         },
432
433         appendSubfield: function( code ) {
434             if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
435
436             this._invalidateSubfields();
437             this.cm.replaceRange( '‡' + code, { line: this.line }, null, 'marcAware' );
438             var subfields = this.getSubfields();
439
440             return subfields[ subfields.length - 1 ];
441         },
442         insertSubfield: function( code, position ) {
443             if ( this.isControlField ) throw new FieldError('Cannot add subfields to control field');
444
445             position = position || 0;
446
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();
451
452             return subfields[ position ];
453         },
454         getSubfields: function( code ) {
455             if ( !this._subfields ) this._scanSubfields();
456             if ( code == null ) return this._subfields;
457
458             var result = [];
459
460             $.each( this._subfields, function() {
461                 if ( code == null || this.code == code ) result.push(this);
462             } );
463
464             return result;
465         },
466         getFirstSubfield: function( code ) {
467             var result = this.getSubfields( code );
468
469             return ( result && result.length ) ? result[0] : null;
470         },
471         getSubfieldAt: function( ch ) {
472             var subfields = this.getSubfields();
473
474             for (var i = 0; i < subfields.length; i++) {
475                 if ( subfields[i].start < ch && subfields[i].end >= ch ) return subfields[i];
476             }
477         },
478     } );
479
480     function MARCEditor( options ) {
481         this.cm = CodeMirror(
482             options.position,
483             {
484                 extraKeys: _editorKeys,
485                 gutters: [
486                     'modified-line-gutter',
487                 ],
488                 lineWrapping: true,
489                 mode: {
490                     name: 'marc',
491                     nonRepeatableTags: KohaBackend.GetTagsBy( '', 'repeatable', '0' ),
492                     nonRepeatableSubfields: KohaBackend.GetSubfieldsBy( '', 'repeatable', '0' )
493                 }
494             }
495         );
496         this.cm.marceditor = this;
497
498         this.cm.on( 'beforeChange', editorBeforeChange );
499         this.cm.on( 'changes', editorChanges );
500         this.cm.on( 'cursorActivity', editorCursorActivity );
501         this.cm.on( 'overwriteToggle', editorSetOverwriteMode );
502
503         this.onCursorActivity = options.onCursorActivity;
504
505         this.subscribers = [];
506         this.subscribe( function( marceditor ) {
507             Widget.Notify( marceditor );
508         } );
509     }
510
511     MARCEditor.FieldError = FieldError;
512
513     $.extend( MARCEditor.prototype, {
514         setUseWidgets: function( val ) {
515             if ( val ) {
516                 for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
517                     Widget.UpdateLine( this, line );
518                 }
519             } else {
520                 $.each( this.cm.getAllMarks(), function( undef, mark ) {
521                     if ( mark.widget ) mark.widget.clearToText();
522                 } );
523             }
524         },
525
526         focus: function() {
527             this.cm.focus();
528         },
529
530         getCursor: function() {
531             return this.cm.getCursor();
532         },
533
534         refresh: function() {
535             this.cm.refresh();
536         },
537
538         displayRecord: function( record ) {
539             this.cm.setValue( TextMARC.RecordToText(record) );
540             this.modified = false;
541         },
542
543         getRecord: function() {
544             this.textMode = true;
545
546             $.each( this.cm.getAllMarks(), function( undef, mark ) {
547                 if ( mark.widget ) mark.widget.clearToText();
548             } );
549             var record = TextMARC.TextToRecord( this.cm.getValue() );
550             for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
551                 if ( Preferences.user.fieldWidgets ) Widget.UpdateLine( this, line );
552             }
553
554             this.textMode = false;
555
556             return record;
557         },
558
559         getLineInfo: function( pos ) {
560             var contents = this.cm.getLine( pos.line );
561             if ( contents == null ) return {};
562
563             var tagNumber = contents.match( /^([A-Za-z0-9]{3})/ );
564
565             if ( !tagNumber ) return null; // No tag at all on this line
566             tagNumber = tagNumber[1];
567
568             if ( tagNumber < '010' ) return { tagNumber: tagNumber, contents: contents }; // No current subfield
569
570             var matcher = /‡([a-z0-9%])/g;
571             var match;
572
573             var subfields = [];
574             var currentSubfield;
575
576             while ( ( match = matcher.exec(contents) ) ) {
577                 subfields.push( { code: match[1], ch: match.index } );
578                 if ( match.index < pos.ch ) currentSubfield = match[1];
579             }
580
581             return { tagNumber: tagNumber, subfields: subfields, currentSubfield: currentSubfield, contents: contents };
582         },
583
584         addError: function( line, error ) {
585             var found = false;
586             var options = {};
587
588             if ( line == null ) {
589                 line = 0;
590                 options.above = true;
591             }
592
593             $.each( this.cm.getLineHandle(line).widgets || [], function( undef, widget ) {
594                 if ( !widget.isErrorMarker ) return;
595
596                 found = true;
597
598                 $( widget.node ).append( '; ' + error );
599                 widget.changed();
600
601                 return false;
602             } );
603
604             if ( found ) return;
605
606             var node = $( '<div class="structure-error"><i class="fa fa-remove"></i> ' + error + '</div>' )[0];
607             var widget = this.cm.addLineWidget( line, node, options );
608
609             widget.node = node;
610             widget.isErrorMarker = true;
611         },
612
613         removeErrors: function() {
614             for ( var line = 0; line < this.cm.lineCount(); line++ ) {
615                 $.each( this.cm.getLineHandle( line ).widgets || [], function( undef, lineWidget ) {
616                     if ( lineWidget.isErrorMarker ) lineWidget.clear();
617                 } );
618             }
619         },
620
621         startNotify: function() {
622             if ( this.notifyTimeout ) clearTimeout( this.notifyTimeout );
623             this.notifyTimeout = setTimeout( $.proxy( function() {
624                 this.notifyAll();
625
626                 this.notifyTimeout = null;
627             }, this ), NOTIFY_TIMEOUT );
628         },
629
630         notifyAll: function() {
631             $.each( this.subscribers, $.proxy( function( undef, subscriber ) {
632                 subscriber(this);
633             }, this ) );
634         },
635
636         subscribe: function( subscriber ) {
637             this.subscribers.push( subscriber );
638         },
639
640         createField: function( tag, line ) {
641             var contents = tag + ( tag < '010' ? ' ' : ' _ _ ' );
642
643             if ( line > this.cm.lastLine() ) {
644                 contents = '\n' + contents;
645             } else {
646                 contents = contents + '\n';
647             }
648
649             this.cm.replaceRange( contents, { line: line, ch: 0 }, null, 'marcAware' );
650
651             return new EditorField( this, line );
652         },
653
654         createFieldOrdered: function( tag ) {
655             var line, contents;
656
657             for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
658                 if ( contents && contents.substr(0, 3) > tag ) break;
659             }
660
661             return this.createField( tag, line );
662         },
663
664         createFieldGrouped: function( tag ) {
665             // Control fields should be inserted in actual order, whereas other fields should be
666             // inserted grouped
667             if ( tag < '010' ) return this.createFieldOrdered( tag );
668
669             var line, contents;
670
671             for ( line = 0; (contents = this.cm.getLine(line)); line++ ) {
672                 if ( contents && contents[0] > tag[0] ) break;
673             }
674
675             return this.createField( tag, line );
676         },
677
678         getFieldAt: function( line ) {
679             try {
680                 return new EditorField( this, line );
681             } catch (e) {
682                 return null;
683             }
684         },
685
686         getCurrentField: function() {
687             return this.getFieldAt( this.cm.getCursor().line );
688         },
689
690         getFields: function( tag ) {
691             var result = [];
692
693             if ( tag != null ) tag += ' ';
694
695             for ( var line = 0; line < this.cm.lineCount(); line++ ) {
696                 if ( tag && this.cm.getLine(line).substr( 0, 4 ) != tag ) continue;
697
698                 // If this throws a FieldError, pretend it doesn't exist
699                 try {
700                     result.push( new EditorField( this, line ) );
701                 } catch (e) {
702                     if ( !( e instanceof FieldError ) ) throw e;
703                 }
704             }
705
706             return result;
707         },
708
709         getFirstField: function( tag ) {
710             var result = this.getFields( tag );
711
712             return ( result && result.length ) ? result[0] : null;
713         },
714
715         getAllFields: function( tag ) {
716             return this.getFields( null );
717         },
718     } );
719
720     return MARCEditor;
721 } );