bugfix
[redakcja.git] / src / 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.closest('[x-node="pe"]').length > 0)
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 createPoint = function(container, offset) {
159             var offsetBetweenCommas = function(text, offset) {
160                 if(text.length < 2 || offset < 1 || offset > text.length)
161                     return false;
162                 return text[offset-1] === ',' && text[offset] === ',';
163             }
164             var point = document.createRange();
165             offset = offsetBetweenCommas(container.textContent, offset) ? offset - 1 : offset;
166             point.setStart(container, offset);
167             return point;
168         }
169         
170         var spoint = createPoint(range.startContainer, range.startOffset);
171         var epoint = createPoint(range.endContainer, range.endOffset);
172                
173         var mtag, btag, etag, errors;
174
175         // insert theme-ref
176
177         xml2html({
178             xml: '<end id="e' + id + '" />',
179             success: function(text){
180                 etag = $('<span></span>');
181                 epoint.insertNode(etag[0]);
182                 etag.replaceWith(text);
183                 xml2html({
184                     xml: '<motyw id="m' + id + '"></motyw>',
185                     success: function(text){
186                         mtag = $('<span></span>');
187                         spoint.insertNode(mtag[0]);
188                         mtag.replaceWith(text);
189                         xml2html({
190                             xml: '<begin id="b' + id + '" />',
191                             success: function(text){
192                                 btag = $('<span></span>');
193                                 spoint.insertNode(btag[0])
194                                 btag.replaceWith(text);
195                                 selection.removeAllRanges();
196                                 openForEdit($('.motyw[theme-class="' + id + '"]'));
197                             }
198                         });
199                     }
200                 });
201             }
202         });
203     }
204
205     function addSymbol() {
206         if($('div.html-editarea textarea')[0]) {
207             var specialCharsContainer = $("<div id='specialCharsContainer'><a href='#' id='specialCharsClose'>Zamknij</a><table id='tableSpecialChars' style='width: 600px;'></table></div>");
208                         
209             var specialChars = [' ', 'Ą','ą','Ć','ć','Ę','ę','Ł','ł','Ń','ń','Ó','ó','Ś','ś','Ż','ż','Ź','ź','Á','á','À','à',
210             'Â','â','Ä','ä','Å','å','Ā','ā','Ă','ă','Ã','ã',
211             'Æ','æ','Ç','ç','Č','č','Ċ','ċ','Ď','ď','É','é','È','è',
212             'Ê','ê','Ë','ë','Ē','ē','Ě','ě','Ġ','ġ','Ħ','ħ','Í','í','Î','î',
213             'Ī','ī','Ĭ','ĭ','Ľ','ľ','Ñ','ñ','Ň','ň','Ó','ó','Ö','ö',
214             'Ô','ô','Ō','ō','Ǒ','ǒ','Œ','œ','Ø','ø','Ř','ř','Š',
215             'š','Ş','ş','Ť','ť','Ţ','ţ','Ű','ű','Ú','ú','Ù','ù',
216             'Ü','ü','Ů','ů','Ū','ū','Û','û','Ŭ','ŭ',
217             'Ý','ý','Ž','ž','ß','Ð','ð','Þ','þ','А','а','Б',
218             'б','В','в','Г','г','Д','д','Е','е','Ё','ё','Ж',
219             'ж','З','з','И','и','Й','й','К','к','Л','л','М',
220             'м','Н','н','О','о','П','п','Р','р','С','с',
221             'Т','т','У','у','Ф','ф','Х','х','Ц','ц','Ч',
222             'ч','Ш','ш','Щ','щ','Ъ','ъ','Ы','ы','Ь','ь','Э',
223             'э','Ю','ю','Я','я','ѓ','є','і','ї','ј','љ','њ',
224             'Ґ','ґ','Α','α','Β','β','Γ','γ','Δ','δ','Ε','ε',
225             'Ζ','ζ','Η','η','Θ','θ','Ι','ι','Κ','κ','Λ','λ','Μ',
226             'μ','Ν','ν','Ξ','ξ','Ο','ο','Π','π','Ρ','ρ','Σ','ς','σ',
227             'Τ','τ','Υ','υ','Φ','φ','Χ','χ','Ψ','ψ','Ω','ω','–',
228             '—','¡','¿','$','¢','£','€','©','®','°','¹','²','³',
229             '¼','½','¾','†','§','‰','•','←','↑','→','↓',
230             '„','”','„”','«','»','«»','»«','’','[',']','~','|','−','·',
231             '×','÷','≈','≠','±','≤','≥','∈'];
232             var tableContent = "<tr>";
233             
234             for(var i in specialChars) {
235                 if(i % 14 == 0 && i > 0) {
236                     tableContent += "</tr><tr>";
237                 }              
238                 tableContent += "<td><input type='button' class='specialBtn' value='"+specialChars[i]+"'/></td>";              
239             }
240             
241             tableContent += "</tr>";                                   
242             $("body").append(specialCharsContainer);
243             
244             
245              // localStorage for recently used characters - reading
246              if (typeof(localStorage) != 'undefined') {
247                  if (localStorage.getItem("recentSymbols")) {
248                      var recent = localStorage.getItem("recentSymbols");
249                      var recentArray = recent.split(";");
250                      var recentRow = "";
251                      for(var i in recentArray.reverse()) {
252                         recentRow += "<td><input type='button' class='specialBtn recentSymbol' value='"+recentArray[i]+"'/></td>";              
253                      }
254                      recentRow = "<tr>" + recentRow + "</tr>";                              
255                  }
256              }            
257             $("#tableSpecialChars").append(recentRow);
258             $("#tableSpecialChars").append(tableContent);
259             
260             /* events */
261             
262             $('.specialBtn').click(function(){
263                 var editArea = $('div.html-editarea textarea')[0];
264                 var insertVal = $(this).val();
265                 
266                 // if we want to surround text with quotes
267                 // not sure if just check if value has length == 2
268                 
269                 if (insertVal.length == 2) {
270                     var startTag = insertVal[0];
271                     var endTag = insertVal[1];
272                                 var textAreaOpened = editArea;                                                  
273                                 //IE support
274                                 if (document.selection) {
275                                     textAreaOpened.focus();
276                                     sel = document.selection.createRange();
277                                     sel.text = startTag + sel.text + endTag;
278                                 }
279                                 //MOZILLA/NETSCAPE support
280                                 else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') {
281                                     var startPos = textAreaOpened.selectionStart;
282                                     var endPos = textAreaOpened.selectionEnd;
283                                     textAreaOpened.value = textAreaOpened.value.substring(0, startPos)
284                                           + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length);
285                                 }                
286                 } else {
287                     // if we just want to insert single symbol
288                     insertAtCaret(editArea, insertVal);
289                 }
290                 
291                 // localStorage for recently used characters - saving
292                 if (typeof(localStorage) != 'undefined') {
293                     if (localStorage.getItem("recentSymbols")) {
294                         var recent = localStorage.getItem("recentSymbols");
295                         var recentArray = recent.split(";");
296                         var valIndex = $.inArray(insertVal, recentArray);
297                         //alert(valIndex);
298                         if(valIndex == -1) {
299                             // value not present in array yet
300                             if(recentArray.length > 13){
301                                 recentArray.shift();
302                                 recentArray.push(insertVal);
303                             } else {
304                                 recentArray.push(insertVal);
305                             }
306                         } else  {
307                             // value already in the array
308                             for(var i = valIndex; i < recentArray.length; i++){
309                                 recentArray[i] = recentArray[i+1];
310                             }
311                             recentArray[recentArray.length-1] = insertVal;
312                         }
313                         localStorage.setItem("recentSymbols", recentArray.join(";"));
314                     } else {
315                         localStorage.setItem("recentSymbols", insertVal);
316                     }
317                 }
318                 $(specialCharsContainer).remove();
319             });         
320             $('#specialCharsClose').click(function(){
321                 $(specialCharsContainer).remove();
322             });                   
323             
324         } else {
325             window.alert('Najedź na fragment tekstu, wybierz "Edytuj" i ustaw kursor na miejscu gdzie chcesz wstawić symbol.');
326         }
327     }
328
329     function insertAtCaret(txtarea,text) { 
330         /* http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/ */
331         var scrollPos = txtarea.scrollTop; 
332         var strPos = 0; 
333         var backStart = 0;
334         var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
335         if (br == "ie") { 
336             txtarea.focus();
337             var range = document.selection.createRange(); 
338             range.moveStart ('character', -txtarea.value.length); 
339             strPos = backStart = range.text.length; 
340         } else if (br == "ff") {
341             strPos = txtarea.selectionStart; 
342             backStart = txtarea.selectionEnd;
343         }
344         var front = (txtarea.value).substring(0,strPos); 
345         var back = (txtarea.value).substring(backStart,txtarea.value.length); 
346         txtarea.value=front+text+back; 
347         strPos = strPos + text.length; 
348         if (br == "ie") { 
349             txtarea.focus(); 
350             var range = document.selection.createRange(); 
351             range.moveStart ('character', -txtarea.value.length); 
352             range.moveStart ('character', strPos); 
353             range.moveEnd ('character', 0); 
354             range.select(); 
355         } else if (br == "ff") { 
356             txtarea.selectionStart = strPos; 
357             txtarea.selectionEnd = strPos; 
358             txtarea.focus(); 
359         } 
360         txtarea.scrollTop = scrollPos; 
361     } 
362
363     /* open edition window for selected fragment */
364     function openForEdit($origin){
365         var $box = null
366
367         // annotations overlay their sub box - not their own box //
368         if ($origin.is(".annotation-inline-box")) {
369             $box = $("*[x-annotation-box]", $origin);
370         }
371         else {
372             $box = $origin;
373         }
374         var x = $box[0].offsetLeft;
375         var y = $box[0].offsetTop;        
376         
377         var w = $box.outerWidth();
378         var h = $box.innerHeight();
379
380         if ($origin.is(".annotation-inline-box")) {
381             w = Math.max(w, 400);
382             h = Math.max(h, 60);
383             if($('.htmlview div').offset().left + $('.htmlview div').width() > ($('.vsplitbar').offset().left - 480)){
384                 x = -(Math.max($origin.offset().left, $origin.width())); 
385             } else {
386                 x = 100;
387             }
388         }
389
390         // start edition on this node
391         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({
392             position: 'absolute',
393             height: h,
394             left: x,
395             top: y,
396             width: w
397         }).appendTo($box[0].offsetParent || $box.parent()).show();
398         
399
400         if ($origin.is('.motyw')) {
401             $('.akap-edit-button').remove();
402             $.themes.autocomplete($('textarea', $overlay));
403         }
404
405         if ($origin.is('.motyw')){
406             $('.delete-button', $overlay).click(function(){
407                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten motyw?")) {
408                     $('[theme-class="' + $origin.attr('theme-class') + '"]').remove();
409                     $overlay.remove();
410                     $(document).unbind('click.blur-overlay');
411                     return false;
412                 };
413             });
414         }
415         else if($box.is('*[x-annotation-box]')) {
416             $('.delete-button', $overlay).click(function(){
417                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten przypis?")) {
418                     $origin.remove();
419                     $overlay.remove();
420                     $(document).unbind('click.blur-overlay');
421                     return false;
422                 };
423             });
424         }
425         else {
426             $('.delete-button', $overlay).html("Anuluj");
427             $('.delete-button', $overlay).click(function(){
428                 if (window.confirm("Czy jesteś pewien, że chcesz anulować zmiany?")) {
429                     $overlay.remove();
430                     $(document).unbind('click.blur-overlay');
431                     return false;
432                 };
433             });
434         }
435
436
437         var serializer = new XMLSerializer();
438
439         html2text({
440             element: $box[0],
441             stripOuter: true,
442             success: function(text){
443                 $('textarea', $overlay).val($.trim(text));
444
445                 setTimeout(function(){
446                     $('textarea', $overlay).elastic().focus();
447                 }, 50);
448
449                 function save(argument){
450                     var nodeName = $box.attr('x-node') || 'pe';
451                     var insertedText = $('textarea', $overlay).val();
452
453                     if ($origin.is('.motyw')) {
454                         insertedText = insertedText.replace(/,\s*$/, '');
455                     }
456
457                     xml2html({
458                         xml: '<' + nodeName + '>' + insertedText + '</' + nodeName + '>',
459                         success: function(element){
460                             if (nodeName == 'out-of-flow-text') {
461                                 $(element).children().insertAfter($origin);
462                                 $origin.remove()
463                             }
464                             else {
465                                 $origin.html($(element).html());
466                             }
467                             $overlay.remove();
468                         },
469                         error: function(text){
470                             alert('Błąd! ' + text);
471                         }
472                     })
473                     
474                     var msg = $("<div class='saveNotify'><p>Pamiętaj, żeby zapisać swoje zmiany.</p></div>");
475                     $("#base").prepend(msg);
476                     $('#base .saveNotify').fadeOut(3000, function(){
477                         $(this).remove(); 
478                     });
479                 }
480
481                 $('.akap-edit-button', $overlay).click(function(){
482                         var textAreaOpened = $('textarea', $overlay)[0];
483                         var startTag = "";
484                         var endTag = "";
485                         var buttonName = this.innerHTML;
486
487                         if(buttonName == "słowo obce") {
488                                 startTag = "<slowo_obce>";
489                                 endTag = "</slowo_obce>";
490                         } else if (buttonName == "wyróżnienie") {
491                                 startTag = "<wyroznienie>";
492                                 endTag = "</wyroznienie>";
493                         } else if (buttonName == "tytuł dzieła") {
494                                 startTag = "<tytul_dziela>";
495                                 endTag = "</tytul_dziela>";
496                         } else if(buttonName == "znak spec."){
497                             addSymbol();
498                             return false;
499                         }
500                         
501                         var myField = textAreaOpened;                   
502                         
503                         //IE support
504                         if (document.selection) {
505                             textAreaOpened.focus();
506                             sel = document.selection.createRange();
507                             sel.text = startTag + sel.text + endTag;
508                         }
509                         //MOZILLA/NETSCAPE support
510                         else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') {
511                             var startPos = textAreaOpened.selectionStart;
512                             var endPos = textAreaOpened.selectionEnd;
513                             textAreaOpened.value = textAreaOpened.value.substring(0, startPos)
514                                   + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length);
515                         }
516                 });
517
518                 $('.accept-button', $overlay).click(function(){
519                     save();
520                     $(document).unbind('click.blur-overlay');
521                 });
522
523                 $(document).bind('click.blur-overlay', function(event){
524                     if ($(event.target).closest('.html-editarea, #specialCharsContainer').length > 0) {
525                         return;
526                     }
527                     save();
528                     $(document).unbind('click.blur-overlay');
529                 });
530
531             },
532             error: function(text){
533                 alert('Błąd! ' + text);
534             }
535         });
536     }
537
538     function VisualPerspective(options){
539
540         var old_callback = options.callback;
541
542         options.callback = function(){
543             var element = $("#html-view");
544             var button = $('<button class="edit-button">Edytuj</button>');
545
546             if (!CurrentDocument.readonly) {
547                 $('#html-view').bind('mousemove', function(event){
548                     var editable = $(event.target).closest('*[x-editable]');
549                     $('.active', element).not(editable).removeClass('active').children('.edit-button').remove();
550
551                     if (!editable.hasClass('active')) {
552                         editable.addClass('active').append(button);
553                     }
554                     if (editable.is('.annotation-inline-box')) {
555                         $('*[x-annotation-box]', editable).css({
556                             position: 'absolute',
557                             left: event.clientX - editable.offset().left + 5,
558                             top: event.clientY - editable.offset().top + 5
559                         }).show();
560                     }
561                     else {
562                         $('*[x-annotation-box]').hide();
563                     }
564                 });
565
566                 $('#insert-annotation-button').click(function(){
567                     addAnnotation();
568                     return false;
569                 });
570
571                 $('#insert-theme-button').click(function(){
572                     addTheme();
573                     return false;
574                 });            
575
576                 $(document).on('click', '.edit-button', function(event){
577                     event.preventDefault();
578                     openForEdit($(this).parent());
579                 });
580
581             }
582
583             $(document).on('click', '.motyw', function(){
584                 selectTheme($(this).attr('theme-class'));
585             });
586
587             old_callback.call(this);
588         };
589
590         $.wiki.Perspective.call(this, options);
591     };
592
593     VisualPerspective.prototype = new $.wiki.Perspective();
594
595     VisualPerspective.prototype.freezeState = function(){
596
597     };
598
599     VisualPerspective.prototype.onEnter = function(success, failure){
600         $.wiki.Perspective.prototype.onEnter.call(this);
601
602         $.blockUI({
603             message: 'Uaktualnianie widoku...'
604         });
605
606         function _finalize(callback){
607             $.unblockUI();
608             if (callback)
609                 callback();
610         }
611
612         xml2html({
613             xml: this.doc.text,
614             success: function(element){
615                 var htmlView = $('#html-view');
616                 htmlView.html(element);
617                 htmlView.find('*[x-node]').dblclick(function(e) {
618                     if($(e.target).is('textarea'))
619                         return;
620                     var selection = window.getSelection();
621                     selection.collapseToStart();
622                     selection.modify('extend', 'forward', 'word');
623                     e.stopPropagation();
624                 });
625                 _finalize(success);
626             },
627             error: function(text, source){
628                 err = '<p class="error">Wystąpił błąd:</p><p>'+text+'</p>';
629                 if (source)
630                     err += '<pre>'+source.replace(/&/g, '&amp;').replace(/</g, '&lt;')+'</pre>'
631                 $('#html-view').html(err);
632                 _finalize(failure);
633             }
634         });
635     };
636
637     VisualPerspective.prototype.onExit = function(success, failure){
638         var self = this;
639
640         $.blockUI({
641             message: 'Zapisywanie widoku...'
642         });
643
644         function _finalize(callback){
645             $.unblockUI();
646             if (callback)
647                 callback();
648         }
649
650         if ($('#html-view .error').length > 0)
651             return _finalize(failure);
652
653         html2text({
654             element: $('#html-view').get(0),
655             stripOuter: true,
656             success: function(text){
657                 self.doc.setText(text);
658                 _finalize(success);
659             },
660             error: function(text){
661                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
662                 _finalize(failure);
663             }
664         });
665     };
666
667     $.wiki.VisualPerspective = VisualPerspective;
668
669 })(jQuery);