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