Image editor fix: make sure toolbar content breaks properly for long motif and object...
[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.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             $("#content").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             withThemes(function(canonThemes){
403                 $('textarea', $overlay).autocomplete(canonThemes, {
404                     autoFill: true,
405                     multiple: true,
406                     selectFirst: true,
407                     highlight: false
408                 });
409             })
410         }
411
412         if ($origin.is('.motyw')){
413             $('.delete-button', $overlay).click(function(){
414                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten motyw ?")) {
415                     $('[theme-class=' + $origin.attr('theme-class') + ']').remove();
416                     $overlay.remove();
417                     $(document).unbind('click.blur-overlay');
418                     return false;
419                 };
420             });
421         }
422         else if($box.is('*[x-annotation-box]')) {
423             $('.delete-button', $overlay).click(function(){
424                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten przypis?")) {
425                     $origin.remove();
426                     $overlay.remove();
427                     $(document).unbind('click.blur-overlay');
428                     return false;
429                 };
430             });
431         }
432         else {
433             $('.delete-button', $overlay).html("Anuluj");
434             $('.delete-button', $overlay).click(function(){
435                 if (window.confirm("Czy jesteś pewien, że chcesz anulować zmiany?")) {
436                     $overlay.remove();
437                     $(document).unbind('click.blur-overlay');
438                     return false;
439                 };
440             });
441         }
442
443
444         var serializer = new XMLSerializer();
445
446         html2text({
447             element: $box[0],
448             stripOuter: true,
449             success: function(text){
450                 $('textarea', $overlay).val($.trim(text));
451
452                 setTimeout(function(){
453                     $('textarea', $overlay).elastic().focus();
454                 }, 50);
455
456                 function save(argument){
457                     var nodeName = $box.attr('x-node') || 'pe';
458                     var insertedText = $('textarea', $overlay).val();
459
460                     if ($origin.is('.motyw')) {
461                         insertedText = insertedText.replace(/,\s*$/, '');
462                     }
463
464                     xml2html({
465                         xml: '<' + nodeName + '>' + insertedText + '</' + nodeName + '>',
466                         success: function(element){
467                             if (nodeName == 'out-of-flow-text') {
468                                 $(element).children().insertAfter($origin);
469                                 $origin.remove()
470                             }
471                             else {
472                                 $origin.html($(element).html());
473                             }
474                             $overlay.remove();
475                         },
476                         error: function(text){
477                             alert('Błąd! ' + text);
478                         }
479                     })
480                     
481                     var msg = $("<div class='saveNotify'><p>Pamiętaj, żeby zapisać swoje zmiany.</p></div>");
482                     $("#base").prepend(msg);
483                     $('#base .saveNotify').fadeOut(3000, function(){
484                         $(this).remove(); 
485                     });
486                 }
487
488                 $('.akap-edit-button', $overlay).click(function(){
489                         var textAreaOpened = $('textarea', $overlay)[0];
490                         var startTag = "";
491                         var endTag = "";
492                         var buttonName = this.innerHTML;
493
494                         if(buttonName == "słowo obce") {
495                                 startTag = "<slowo_obce>";
496                                 endTag = "</slowo_obce>";
497                         } else if (buttonName == "wyróżnienie") {
498                                 startTag = "<wyroznienie>";
499                                 endTag = "</wyroznienie>";
500                         } else if (buttonName == "tytuł dzieła") {
501                                 startTag = "<tytul_dziela>";
502                                 endTag = "</tytul_dziela>";
503                         } else if(buttonName == "znak spec."){
504                             addSymbol();
505                             return false;
506                         }
507                         
508                         var myField = textAreaOpened;                   
509                         
510                         //IE support
511                         if (document.selection) {
512                             textAreaOpened.focus();
513                             sel = document.selection.createRange();
514                             sel.text = startTag + sel.text + endTag;
515                         }
516                         //MOZILLA/NETSCAPE support
517                         else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') {
518                             var startPos = textAreaOpened.selectionStart;
519                             var endPos = textAreaOpened.selectionEnd;
520                             textAreaOpened.value = textAreaOpened.value.substring(0, startPos)
521                                   + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length);
522                         }
523                 });
524
525                 $('.accept-button', $overlay).click(function(){
526                     save();
527                     $(document).unbind('click.blur-overlay');
528                 });
529
530                 $(document).bind('click.blur-overlay', function(event){
531                     if ($(event.target).closest('.html-editarea, #specialCharsContainer').length > 0) {
532                         return;
533                     }
534                     save();
535                     $(document).unbind('click.blur-overlay');
536                 });
537
538             },
539             error: function(text){
540                 alert('Błąd! ' + text);
541             }
542         });
543     }
544
545     function VisualPerspective(options){
546
547         var old_callback = options.callback;
548
549         options.callback = function(){
550             var element = $("#html-view");
551             var button = $('<button class="edit-button">Edytuj</button>');
552
553             if (!CurrentDocument.readonly) {
554                 $('#html-view').bind('mousemove', function(event){
555                     var editable = $(event.target).closest('*[x-editable]');
556                     $('.active', element).not(editable).removeClass('active').children('.edit-button').remove();
557
558                     if (!editable.hasClass('active')) {
559                         editable.addClass('active').append(button);
560                     }
561                     if (editable.is('.annotation-inline-box')) {
562                         $('*[x-annotation-box]', editable).css({
563                             position: 'absolute',
564                             left: event.clientX - editable.offset().left + 5,
565                             top: event.clientY - editable.offset().top + 5
566                         }).show();
567                     }
568                     else {
569                         $('*[x-annotation-box]').hide();
570                     }
571                 });
572
573                 $('#insert-annotation-button').click(function(){
574                     addAnnotation();
575                     return false;
576                 });
577
578                 $('#insert-theme-button').click(function(){
579                     addTheme();
580                     return false;
581                 });            
582
583                 $('.edit-button').live('click', function(event){
584                     event.preventDefault();
585                     openForEdit($(this).parent());
586                 });
587
588             }
589
590             $('.motyw').live('click', function(){
591                 selectTheme($(this).attr('theme-class'));
592             });
593
594             old_callback.call(this);
595         };
596
597         $.wiki.Perspective.call(this, options);
598     };
599
600     VisualPerspective.prototype = new $.wiki.Perspective();
601
602     VisualPerspective.prototype.freezeState = function(){
603
604     };
605
606     VisualPerspective.prototype.onEnter = function(success, failure){
607         $.wiki.Perspective.prototype.onEnter.call(this);
608
609         $.blockUI({
610             message: 'Uaktualnianie widoku...'
611         });
612
613         function _finalize(callback){
614             $.unblockUI();
615             if (callback)
616                 callback();
617         }
618
619         xml2html({
620             xml: this.doc.text,
621             success: function(element){
622                 var htmlView = $('#html-view');
623                 htmlView.html(element);
624                 htmlView.find('*[x-node]').dblclick(function(e) {
625                     if($(e.target).is('textarea'))
626                         return;
627                     var selection = window.getSelection();
628                     selection.collapseToStart();
629                     selection.modify('extend', 'forward', 'word');
630                     e.stopPropagation();
631                 });
632                 _finalize(success);
633             },
634             error: function(text, source){
635                 err = '<p class="error">Wystąpił błąd:</p><p>'+text+'</p>';
636                 if (source)
637                     err += '<pre>'+source.replace(/&/g, '&amp;').replace(/</g, '&lt;')+'</pre>'
638                 $('#html-view').html(err);
639                 _finalize(failure);
640             }
641         });
642     };
643
644     VisualPerspective.prototype.onExit = function(success, failure){
645         var self = this;
646
647         $.blockUI({
648             message: 'Zapisywanie widoku...'
649         });
650
651         function _finalize(callback){
652             $.unblockUI();
653             if (callback)
654                 callback();
655         }
656
657         if ($('#html-view .error').length > 0)
658             return _finalize(failure);
659
660         html2text({
661             element: $('#html-view').get(0),
662             stripOuter: true,
663             success: function(text){
664                 self.doc.setText(text);
665                 _finalize(success);
666             },
667             error: function(text){
668                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
669                 _finalize(failure);
670             }
671         });
672     };
673
674     $.wiki.VisualPerspective = VisualPerspective;
675
676 })(jQuery);