Fixes #955, enables surrounding text with complex symbols
[redakcja.git] / redakcja / static / js / wiki / view_editor_wysiwyg.js
1 (function($){
2
3     /* Show theme to the user */
4     function selectTheme(themeId){
5         var selection = window.getSelection();
6         selection.removeAllRanges();
7
8         var range = document.createRange();
9         var s = $(".motyw[theme-class='" + themeId + "']")[0];
10         var e = $(".end[theme-class='" + themeId + "']")[0];
11
12         if (s && e) {
13             range.setStartAfter(s);
14             range.setEndBefore(e);
15             selection.addRange(range);
16         }
17     };
18
19     /* Verify insertion port for annotation or theme */
20     function verifyTagInsertPoint(node){
21         if (node.nodeType == 3) { // Text Node
22             node = node.parentNode;
23         }
24
25         if (node.nodeType != 1) {
26             return false;
27         }
28
29         node = $(node);
30         var xtype = node.attr('x-node');
31
32         if (!xtype || (xtype.search(':') >= 0) ||
33         xtype == 'motyw' ||
34         xtype == 'begin' ||
35         xtype == 'end') {
36             return false;
37         }
38
39         // don't allow themes inside annotations
40         if (node.is('*[x-annotation-box] *'))
41             return false;
42
43         return true;
44     }
45
46     /* Convert HTML fragment to plaintext */
47     var ANNOT_FORBIDDEN = ['pt', 'pa', 'pr', 'pe', 'begin', 'end', 'motyw'];
48
49     function html2plainText(fragment){
50         var text = "";
51
52         $(fragment.childNodes).each(function(){
53             if (this.nodeType == 3) // textNode
54                 text += this.nodeValue;
55             else {
56                 if (this.nodeType == 1 &&
57                         $.inArray($(this).attr('x-node'), ANNOT_FORBIDDEN) == -1) {
58                     text += html2plainText(this);
59                 }
60             };
61         });
62
63         return text;
64     }
65
66
67     /* Insert annotation using current selection */
68     function addAnnotation(){
69         var selection = window.getSelection();
70         var n = selection.rangeCount;
71
72         if (n == 0) {
73             window.alert("Nie zaznaczono żadnego obszaru");
74             return false;
75         }
76
77         // for now allow only 1 range
78         if (n > 1) {
79             window.alert("Zaznacz jeden obszar");
80             return false;
81         }
82
83         // remember the selected range
84         var range = selection.getRangeAt(0);
85
86         if (!verifyTagInsertPoint(range.endContainer)) {
87             window.alert("Nie można wstawić w to miejsce przypisu.");
88             return false;
89         }
90
91         // BUG #273 - selected text can contain themes, which should be omitted from
92         // defining term
93         var text = html2plainText(range.cloneContents());
94         var tag = $('<span></span>');
95         range.collapse(false);
96         range.insertNode(tag[0]);
97
98         xml2html({
99             xml: '<pe><slowo_obce>' + text + '</slowo_obce> --- </pe>',
100             success: function(text){
101                 var t = $(text);
102                 tag.replaceWith(t);
103                 openForEdit(t);
104             },
105             error: function(){
106                 tag.remove();
107                 alert('Błąd przy dodawaniu przypisu:' + errors);
108             }
109         })
110     }
111
112
113     /* Insert theme using current selection */
114
115     function addTheme(){
116         var selection = window.getSelection();
117         var n = selection.rangeCount;
118
119         if (n == 0) {
120             window.alert("Nie zaznaczono żadnego obszaru");
121             return false;
122         }
123
124         // for now allow only 1 range
125         if (n > 1) {
126             window.alert("Zaznacz jeden obszar.");
127             return false;
128         }
129
130
131         // remember the selected range
132         var range = selection.getRangeAt(0);
133
134
135         if ($(range.startContainer).is('.html-editarea') ||
136         $(range.endContainer).is('.html-editarea')) {
137             window.alert("Motywy można oznaczać tylko na tekście nie otwartym do edycji. \n Zamknij edytowany fragment i spróbuj ponownie.");
138             return false;
139         }
140
141         // verify if the start/end points make even sense -
142         // they must be inside a x-node (otherwise they will be discarded)
143         // and the x-node must be a main text
144         if (!verifyTagInsertPoint(range.startContainer)) {
145             window.alert("Motyw nie może się zaczynać w tym miejscu.");
146             return false;
147         }
148
149         if (!verifyTagInsertPoint(range.endContainer)) {
150             window.alert("Motyw nie może się kończyć w tym miejscu.");
151             return false;
152         }
153
154         var date = (new Date()).getTime();
155         var random = Math.floor(4000000000 * Math.random());
156         var id = ('' + date) + '-' + ('' + random);
157
158         var spoint = document.createRange();
159         var epoint = document.createRange();
160
161         spoint.setStart(range.startContainer, range.startOffset);
162         epoint.setStart(range.endContainer, range.endOffset);
163
164         var mtag, btag, etag, errors;
165
166         // insert theme-ref
167
168         xml2html({
169             xml: '<end id="e' + id + '" />',
170             success: function(text){
171                 etag = $('<span></span>');
172                 epoint.insertNode(etag[0]);
173                 etag.replaceWith(text);
174                 xml2html({
175                     xml: '<motyw id="m' + id + '"></motyw>',
176                     success: function(text){
177                         mtag = $('<span></span>');
178                         spoint.insertNode(mtag[0]);
179                         mtag.replaceWith(text);
180                         xml2html({
181                             xml: '<begin id="b' + id + '" />',
182                             success: function(text){
183                                 btag = $('<span></span>');
184                                 spoint.insertNode(btag[0])
185                                 btag.replaceWith(text);
186                                 selection.removeAllRanges();
187                                 openForEdit($('.motyw[theme-class=' + id + ']'));
188                             }
189                         });
190                     }
191                 });
192             }
193         });
194     }
195
196     function addSymbol() {
197         if($('div.html-editarea textarea')[0]) {
198             var specialCharsContainer = $("<div id='specialCharsContainer'><a href='#' id='specialCharsClose'>Zamknij</a><table id='tableSpecialChars' style='width: 600px;'></table></div>");
199             var specialChars = ['Ą','ą','Ć','ć','Ę','ę','Ł','ł','Ń','ń','Ó','ó','Ś','ś','Ż','ż','Ź','ź','Á','á','À','à',
200             'Â','â','Ä','ä','Å','å','Ā','ā','Ă','ă','Ã','ã',
201             'Æ','æ','Ç','ç','Č','č','Ċ','ċ','Ď','ď','É','é','È','è',
202             'Ê','ê','Ë','ë','Ē','ē','Ě','ě','Ġ','ġ','Ħ','ħ','Í','í','Î','î',
203             'Ī','ī','Ĭ','ĭ','Ľ','ľ','Ñ','ñ','Ň','ň','Ó','ó','Ö','ö',
204             'Ô','ô','Ō','ō','Ǒ','ǒ','Œ','œ','Ø','ø','Ř','ř','Š',
205             'š','Ş','ş','Ť','ť','Ţ','ţ','Ű','ű','Ú','ú',
206             'Ü','ü','Ů','ů','Ū','ū','Û','û','Ŭ','ŭ',
207             'Ý','ý','Ž','ž','ß','Ð','ð','Þ','þ','А','а','Б',
208             'б','В','в','Г','г','Д','д','Е','е','Ё','ё','Ж',
209             'ж','З','з','И','и','Й','й','К','к','Л','л','М',
210             'м','Н','н','О','о','П','п','Р','р','С','с',
211             'Т','т','У','у','Ф','ф','Х','х','Ц','ц','Ч',
212             'ч','Ш','ш','Щ','щ','Ъ','ъ','Ы','ы','Ь','ь','Э',
213             'э','Ю','ю','Я','я','ѓ','є','і','ї','ј','љ','њ',
214             'Ґ','ґ','Α','α','Β','β','Γ','γ','Δ','δ','Ε','ε',
215             'Ζ','ζ','Η','η','Θ','θ','Ι','ι','Κ','κ','Λ','λ','Μ',
216             'μ','Ν','ν','Ξ','ξ','Ο','ο','Π','π','Ρ','ρ','Σ','ς','σ',
217             'Τ','τ','Υ','υ','Φ','φ','Χ','χ','Ψ','ψ','Ω','ω','–',
218             '—','¡','¿','$','¢','£','€','©','®','°','¹','²','³',
219             '¼','½','¾','†','§','‰','•','←','↑','→','↓',
220             '„','”','„”','«','»','«»','’','[',']','~','|','−','·',
221             '×','÷','≈','≠','±','≤','≥','∈'];
222             var tableContent = "<tr>";
223             
224             for(var i in specialChars) {
225                 if(i % 14 == 0 && i > 0) {
226                     tableContent += "</tr><tr>";
227                 }              
228                 tableContent += "<td><input type='button' class='specialBtn' value='"+specialChars[i]+"'/></td>";              
229             }
230             
231             tableContent += "</tr>";                                   
232             $("#content").append(specialCharsContainer);
233             $("#tableSpecialChars").append(tableContent);
234             
235             /* events */
236             
237             $('.specialBtn').click(function(){
238                 var editArea = $('div.html-editarea textarea')[0];
239                 var insertVal = $(this).val();
240                 
241                 // if we want to surround text with quotes
242                 // not sure if just check if value has length == 2
243                 
244                 if(insertVal == '„”' || insertVal == '«»'){
245                     var startTag = insertVal[0];
246                     var endTag = insertVal[1];
247                                 var textAreaOpened = editArea;                                                  
248                                 //IE support
249                                 if (document.selection) {
250                                     textAreaOpened.focus();
251                                     sel = document.selection.createRange();
252                                     sel.text = startTag + sel.text + endTag;
253                                 }
254                                 //MOZILLA/NETSCAPE support
255                                 else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') {
256                                     var startPos = textAreaOpened.selectionStart;
257                                     var endPos = textAreaOpened.selectionEnd;
258                                     textAreaOpened.value = textAreaOpened.value.substring(0, startPos)
259                                           + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length);
260                                 }                
261                 } else {
262                     // if we just want to insert single symbol
263                     insertAtCaret(editArea, insertVal);
264                 }
265                 
266                 $(specialCharsContainer).remove();
267             });         
268             $('#specialCharsClose').click(function(){
269                 $(specialCharsContainer).remove();
270             });                   
271             
272         } else {
273             window.alert('Najedź na fragment tekstu, wybierz "Edytuj" i ustaw kursor na miejscu gdzie chcesz wstawić symbol.');
274         }
275     }
276
277     function insertAtCaret(txtarea,text) { 
278         /* http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/ */
279         var scrollPos = txtarea.scrollTop; 
280         var strPos = 0; 
281         var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
282         if (br == "ie") { 
283             txtarea.focus();
284             var range = document.selection.createRange(); 
285             range.moveStart ('character', -txtarea.value.length); 
286             strPos = range.text.length; 
287         } else if (br == "ff") strPos = txtarea.selectionStart; 
288         var front = (txtarea.value).substring(0,strPos); 
289         var back = (txtarea.value).substring(strPos,txtarea.value.length); 
290         txtarea.value=front+text+back; 
291         strPos = strPos + text.length; 
292         if (br == "ie") { 
293             txtarea.focus(); 
294             var range = document.selection.createRange(); 
295             range.moveStart ('character', -txtarea.value.length); 
296             range.moveStart ('character', strPos); 
297             range.moveEnd ('character', 0); 
298             range.select(); 
299         } else if (br == "ff") { 
300             txtarea.selectionStart = strPos; 
301             txtarea.selectionEnd = strPos; 
302             txtarea.focus(); 
303         } 
304         txtarea.scrollTop = scrollPos; 
305     } 
306
307     /* open edition window for selected fragment */
308     function openForEdit($origin){
309         var $box = null
310
311         // annotations overlay their sub box - not their own box //
312         if ($origin.is(".annotation-inline-box")) {
313             $box = $("*[x-annotation-box]", $origin);
314         }
315         else {
316             $box = $origin;
317         }
318         var x = $box[0].offsetLeft;
319         var y = $box[0].offsetTop;        
320         
321         var w = $box.outerWidth();
322         var h = $box.innerHeight();
323
324         if ($origin.is(".annotation-inline-box")) {
325             w = Math.max(w, 400);
326             h = Math.max(h, 60);
327             if($('.htmlview div').offset().left + $('.htmlview div').width() > ($('.vsplitbar').offset().left - 480)){
328                 x = -(Math.max($origin.offset().left, $origin.width())); 
329             } else {
330                 x = 100;
331             }
332         }
333
334         // start edition on this node
335         var $overlay = $('<div class="html-editarea"><button class="accept-button">Zapisz</button><button class="delete-button">Usuń</button><button class="tytul-button akap-edit-button">tytuł dzieła</button><button class="wyroznienie-button akap-edit-button">wyróżnienie</button><button class="slowo-button akap-edit-button">słowo obce</button><button class="znak-button akap-edit-button">znak spec.</button><textarea></textarea></div>').css({
336             position: 'absolute',
337             height: h,
338             left: x,
339             top: y,
340             width: w
341         }).appendTo($box[0].offsetParent || $box.parent()).show();
342         
343
344         if ($origin.is('.motyw')) {
345             $('.akap-edit-button').remove();
346             withThemes(function(canonThemes){
347                 $('textarea', $overlay).autocomplete(canonThemes, {
348                     autoFill: true,
349                     multiple: true,
350                     selectFirst: true,
351                     highlight: false
352                 });
353             })
354         }
355
356         if ($origin.is('.motyw')){
357             $('.delete-button', $overlay).click(function(){
358                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten motyw ?")) {
359                     $('[theme-class=' + $origin.attr('theme-class') + ']').remove();
360                     $overlay.remove();
361                     $(document).unbind('click.blur-overlay');
362                     return false;
363                 };
364             });
365         }
366         else if($box.is('*[x-annotation-box]')) {
367             $('.delete-button', $overlay).click(function(){
368                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten przypis?")) {
369                     $origin.remove();
370                     $overlay.remove();
371                     $(document).unbind('click.blur-overlay');
372                     return false;
373                 };
374             });
375         }
376         else {
377             $('.delete-button', $overlay).html("Anuluj");
378             $('.delete-button', $overlay).click(function(){
379                 if (window.confirm("Czy jesteś pewien, że chcesz anulować zmiany?")) {
380                     $overlay.remove();
381                     $(document).unbind('click.blur-overlay');
382                     return false;
383                 };
384             });
385         }
386
387
388         var serializer = new XMLSerializer();
389
390         html2text({
391             element: $box[0],
392             stripOuter: true,
393             success: function(text){
394                 $('textarea', $overlay).val($.trim(text));
395
396                 setTimeout(function(){
397                     $('textarea', $overlay).elastic().focus();
398                 }, 50);
399
400                 function save(argument){
401                     var nodeName = $box.attr('x-node') || 'pe';
402                     var insertedText = $('textarea', $overlay).val();
403
404                     if ($origin.is('.motyw')) {
405                         insertedText = insertedText.replace(/,\s*$/, '');
406                     }
407
408                     xml2html({
409                         xml: '<' + nodeName + '>' + insertedText + '</' + nodeName + '>',
410                         success: function(element){
411                             if (nodeName == 'out-of-flow-text') {
412                                 $(element).children().insertAfter($origin);
413                                 $origin.remove()
414                             }
415                             else {
416                                 $origin.html($(element).html());
417                             }
418                             $overlay.remove();
419                         },
420                         error: function(text){
421                             $overlay.remove();
422                             alert('Błąd! ' + text);
423                         }
424                     })
425                     
426                     var msg = $("<div class='saveNotify'><p>Twoje zmiany zostały naniesione na tekst źródłowy. Pamiętaj, że aby zmiany zostały utrwalone <span>należy je zapisać</span>!</p><p class='notifyTip'>Ta wiadomość zostanie automatycznie zamknięta za 6 sekund.</p></div>");
427                     $("#base").prepend(msg);
428                     $("#save-button").css({border: '2px solid #801000', backgroundColor: '#E1C1C1'});
429                     $('#base .saveNotify').fadeOut(7000, function(){
430                         $(this).remove(); 
431                         $("#save-button").css({border: '1px solid black'});
432                     });
433                 }
434
435                 $('.akap-edit-button', $overlay).click(function(){
436                         var textAreaOpened = $('textarea', $overlay)[0];
437                         var startTag = "";
438                         var endTag = "";
439                         var buttonName = this.innerHTML;
440
441                         if(buttonName == "słowo obce") {
442                                 startTag = "<slowo_obce>";
443                                 endTag = "</slowo_obce>";
444                         } else if (buttonName == "wyróżnienie") {
445                                 startTag = "<wyroznienie>";
446                                 endTag = "</wyroznienie>";
447                         } else if (buttonName == "tytuł dzieła") {
448                                 startTag = "<tytul_dziela>";
449                                 endTag = "</tytul_dziela>";
450                         } else if(buttonName == "znak spec."){
451                             addSymbol();
452                             return false;
453                         }
454                         
455                         var myField = textAreaOpened;                   
456                         
457                         //IE support
458                         if (document.selection) {
459                             textAreaOpened.focus();
460                             sel = document.selection.createRange();
461                             sel.text = startTag + sel.text + endTag;
462                         }
463                         //MOZILLA/NETSCAPE support
464                         else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') {
465                             var startPos = textAreaOpened.selectionStart;
466                             var endPos = textAreaOpened.selectionEnd;
467                             textAreaOpened.value = textAreaOpened.value.substring(0, startPos)
468                                   + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length);
469                         }
470                 });
471
472                 $('.accept-button', $overlay).click(function(){
473                     save();
474                 });
475
476                 $(document).bind('click.blur-overlay', function(event){
477                     if ($(event.target).parents('.html-editarea').length > 0) {
478                         return;
479                     }
480                     save();
481                     $(document).unbind('click.blur-overlay');
482                 });
483
484             },
485             error: function(text){
486                 alert('Błąd! ' + text);
487             }
488         });
489     }
490
491     function VisualPerspective(options){
492
493         var old_callback = options.callback;
494
495         options.callback = function(){
496             var element = $("#html-view");
497             var button = $('<button class="edit-button">Edytuj</button>');
498
499             if (!CurrentDocument.readonly) {
500                 $('#html-view').bind('mousemove', function(event){
501                     var editable = $(event.target).closest('*[x-editable]');
502                     $('.active', element).not(editable).removeClass('active').children('.edit-button').remove();
503
504                     if (!editable.hasClass('active')) {
505                         editable.addClass('active').append(button);
506                     }
507                     if (editable.is('.annotation-inline-box')) {
508                         $('*[x-annotation-box]', editable).css({
509                             position: 'absolute',
510                             left: event.clientX - editable.offset().left + 5,
511                             top: event.clientY - editable.offset().top + 5
512                         }).show();
513                     }
514                     else {
515                         $('*[x-annotation-box]').hide();
516                     }
517                 });
518
519                 $('#insert-annotation-button').click(function(){
520                     addAnnotation();
521                     return false;
522                 });
523
524                 $('#insert-theme-button').click(function(){
525                     addTheme();
526                     return false;
527                 });            
528
529                 $('.edit-button').live('click', function(event){
530                     event.preventDefault();
531                     openForEdit($(this).parent());
532                 });
533
534             }
535
536             $('.motyw').live('click', function(){
537                 selectTheme($(this).attr('theme-class'));
538             });
539
540             old_callback.call(this);
541         };
542
543         $.wiki.Perspective.call(this, options);
544     };
545
546     VisualPerspective.prototype = new $.wiki.Perspective();
547
548     VisualPerspective.prototype.freezeState = function(){
549
550     };
551
552     VisualPerspective.prototype.onEnter = function(success, failure){
553         $.wiki.Perspective.prototype.onEnter.call(this);
554
555         $.blockUI({
556             message: 'Uaktualnianie widoku...'
557         });
558
559         function _finalize(callback){
560             $.unblockUI();
561             if (callback)
562                 callback();
563         }
564
565         xml2html({
566             xml: this.doc.text,
567             success: function(element){
568                 $('#html-view').html(element);
569                 _finalize(success);
570             },
571             error: function(text, source){
572                 err = '<p class="error">Wystąpił błąd:</p><p>'+text+'</p>';
573                 if (source)
574                     err += '<pre>'+source.replace(/&/g, '&amp;').replace(/</g, '&lt;')+'</pre>'
575                 $('#html-view').html(err);
576                 _finalize(failure);
577             }
578         });
579     };
580
581     VisualPerspective.prototype.onExit = function(success, failure){
582         var self = this;
583
584         $.blockUI({
585             message: 'Zapisywanie widoku...'
586         });
587
588         function _finalize(callback){
589             $.unblockUI();
590             if (callback)
591                 callback();
592         }
593
594         if ($('#html-view .error').length > 0)
595             return _finalize(failure);
596
597         html2text({
598             element: $('#html-view div').get(0),
599             success: function(text){
600                 self.doc.setText(text);
601                 _finalize(success);
602             },
603             error: function(text){
604                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
605                 _finalize(failure);
606             }
607         });
608     };
609
610     $.wiki.VisualPerspective = VisualPerspective;
611
612 })(jQuery);