Merge branch 'master' of git@github.com:fnp/redakcja
[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', 'theme'];
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
95         var tag = $('<span></span>');
96         range.collapse(false);
97         range.insertNode(tag[0]);
98
99         xml2html({
100             xml: '<pe><slowo_obce>' + text + '</slowo_obce> --- </pe>',
101             success: function(text){
102                 var t = $(text);
103                 tag.replaceWith(t);
104                 openForEdit(t);
105             },
106             error: function(){
107                 tag.remove();
108                 alert('Błąd przy dodawaniu przypisu:' + errors);
109             }
110         })
111     }
112
113
114     /* Insert theme using current selection */
115
116     function addTheme(){
117         var selection = window.getSelection();
118         var n = selection.rangeCount;
119
120         if (n == 0) {
121             window.alert("Nie zaznaczono żadnego obszaru");
122             return false;
123         }
124
125         // for now allow only 1 range
126         if (n > 1) {
127             window.alert("Zaznacz jeden obszar.");
128             return false;
129         }
130
131
132         // remember the selected range
133         var range = selection.getRangeAt(0);
134
135
136         if ($(range.startContainer).is('.html-editarea') ||
137         $(range.endContainer).is('.html-editarea')) {
138             window.alert("Motywy można oznaczać tylko na tekście nie otwartym do edycji. \n Zamknij edytowany fragment i spróbuj ponownie.");
139             return false;
140         }
141
142         // verify if the start/end points make even sense -
143         // they must be inside a x-node (otherwise they will be discarded)
144         // and the x-node must be a main text
145         if (!verifyTagInsertPoint(range.startContainer)) {
146             window.alert("Motyw nie może się zaczynać w tym miejscu.");
147             return false;
148         }
149
150         if (!verifyTagInsertPoint(range.endContainer)) {
151             window.alert("Motyw nie może się kończyć w tym miejscu.");
152             return false;
153         }
154
155         var date = (new Date()).getTime();
156         var random = Math.floor(4000000000 * Math.random());
157         var id = ('' + date) + '-' + ('' + random);
158
159         var spoint = document.createRange();
160         var epoint = document.createRange();
161
162         spoint.setStart(range.startContainer, range.startOffset);
163         epoint.setStart(range.endContainer, range.endOffset);
164
165         var mtag, btag, etag, errors;
166
167         // insert theme-ref
168
169         xml2html({
170             xml: '<end id="e' + id + '" />',
171             success: function(text){
172                 etag = $('<span></span>');
173                 epoint.insertNode(etag[0]);
174                 etag.replaceWith(text);
175                 xml2html({
176                     xml: '<motyw id="m' + id + '"></motyw>',
177                     success: function(text){
178                         mtag = $('<span></span>');
179                         spoint.insertNode(mtag[0]);
180                         mtag.replaceWith(text);
181                         xml2html({
182                             xml: '<begin id="b' + id + '" />',
183                             success: function(text){
184                                 btag = $('<span></span>');
185                                 spoint.insertNode(btag[0])
186                                 btag.replaceWith(text);
187                                 selection.removeAllRanges();
188                                 openForEdit($('.motyw[theme-class=' + id + ']'));
189                             }
190                         });
191                     }
192                 });
193             }
194         });
195     }
196
197     function addSymbol() {
198         if($('div.html-editarea textarea')[0]) {
199             var specialCharsContainer = $("<div id='specialCharsContainer'><a href='#' id='specialCharsClose'>Zamknij</a><table id='tableSpecialChars' style='width: 600px;'></table></div>");
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             $("#tableSpecialChars").append(tableContent);
235             
236             /* events */
237             
238             $('.specialBtn').click(function(){
239                 insertAtCaret($('div.html-editarea textarea')[0], $(this).val());
240                 $(specialCharsContainer).remove();
241             });         
242             $('#specialCharsClose').click(function(){
243                 $(specialCharsContainer).remove();
244             });                   
245             
246         } else {
247             window.alert('Najedź na fragment tekstu, wybierz "Edytuj" i ustaw kursor na miejscu gdzie chcesz wstawić symbol.');
248         }
249     }
250
251     function insertAtCaret(txtarea,text) { 
252         /* http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/ */
253         var scrollPos = txtarea.scrollTop; 
254         var strPos = 0; 
255         var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
256         if (br == "ie") { 
257             txtarea.focus();
258             var range = document.selection.createRange(); 
259             range.moveStart ('character', -txtarea.value.length); 
260             strPos = range.text.length; 
261         } else if (br == "ff") strPos = txtarea.selectionStart; 
262         var front = (txtarea.value).substring(0,strPos); 
263         var back = (txtarea.value).substring(strPos,txtarea.value.length); 
264         txtarea.value=front+text+back; 
265         strPos = strPos + text.length; 
266         if (br == "ie") { 
267             txtarea.focus(); 
268             var range = document.selection.createRange(); 
269             range.moveStart ('character', -txtarea.value.length); 
270             range.moveStart ('character', strPos); 
271             range.moveEnd ('character', 0); 
272             range.select(); 
273         } else if (br == "ff") { 
274             txtarea.selectionStart = strPos; 
275             txtarea.selectionEnd = strPos; 
276             txtarea.focus(); 
277         } 
278         txtarea.scrollTop = scrollPos; 
279     } 
280
281     /* open edition window for selected fragment */
282     function openForEdit($origin){
283         var $box = null
284
285         // annotations overlay their sub box - not their own box //
286         if ($origin.is(".annotation-inline-box")) {
287             $box = $("*[x-annotation-box]", $origin);
288         }
289         else {
290             $box = $origin;
291         }
292
293         var x = $box[0].offsetLeft;
294         var y = $box[0].offsetTop;
295         var w = $box.outerWidth();
296         var h = $box.innerHeight();
297
298         if ($origin.is(".annotation-inline-box")) {
299             w = Math.max(w, 400);
300             h = Math.max(h, 60);
301         }
302
303         // start edition on this node
304         var $overlay = $('<div class="html-editarea"><button class="accept-button">Zapisz</button><button class="delete-button">Usuń</button><textarea></textarea></div>').css({
305             position: 'absolute',
306             height: h,
307             left: x,
308             top: y,
309             width: w
310         }).appendTo($box[0].offsetParent || $box.parent()).show();
311
312         if ($origin.is('.motyw')) {
313             $('textarea', $overlay).autocomplete('/themes', {
314                 autoFill: true,
315                 multiple: true,
316                 selectFirst: true,
317                 highlight: false
318             });
319         }
320
321         if ($origin.is('.motyw')){
322             $('.delete-button', $overlay).click(function(){
323                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten motyw ?")) {
324                     $('[theme-class=' + $origin.attr('theme-class') + ']').remove();
325                     $overlay.remove();
326                     $(document).unbind('click.blur-overlay');
327                     return false;
328                 };
329             });
330         }
331         else if($box.is('*[x-annotation-box]')) {
332             $('.delete-button', $overlay).click(function(){
333                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten przypis?")) {
334                     $origin.remove();
335                     $overlay.remove();
336                     $(document).unbind('click.blur-overlay');
337                     return false;
338                 };
339             });
340         }
341         else {
342             $('.delete-button', $overlay).hide();
343         }
344
345
346         var serializer = new XMLSerializer();
347
348         html2text({
349             element: $box[0],
350             stripOuter: true,
351             success: function(text){
352                 $('textarea', $overlay).val($.trim(text));
353
354                 setTimeout(function(){
355                     $('textarea', $overlay).elastic().focus();
356                 }, 50);
357
358                 function save(argument){
359                     var nodeName = $box.attr('x-node') || 'pe';
360                     var insertedText = $('textarea', $overlay).val();
361
362                     if ($origin.is('.motyw')) {
363                         insertedText = insertedText.replace(/,\s*$/, '');
364                     }
365
366                     xml2html({
367                         xml: '<' + nodeName + '>' + insertedText + '</' + nodeName + '>',
368                         success: function(element){
369                             $origin.html($(element).html());
370                             $overlay.remove();
371                         },
372                         error: function(text){
373                             $overlay.remove();
374                             alert('Błąd! ' + text);
375                         }
376                     })
377                 }
378
379                 $('.accept-button', $overlay).click(function(){
380                     save();
381                 });
382
383                 $(document).bind('click.blur-overlay', function(event){
384                     if ($(event.target).parents('.html-editarea').length > 0) {
385                         return;
386                     }
387                     save();
388
389                     $(document).unbind('click.blur-overlay');
390                 });
391
392             },
393             error: function(text){
394                 alert('Błąd! ' + text);
395             }
396         });
397     }
398
399     function VisualPerspective(options){
400
401         var old_callback = options.callback;
402
403         options.callback = function(){
404             var element = $("#html-view");
405             var button = $('<button class="edit-button">Edytuj</button>');
406
407             if (!CurrentDocument.readonly) {
408                 $('#html-view').bind('mousemove', function(event){
409                     var editable = $(event.target).closest('*[x-editable]');
410                     $('.active', element).not(editable).removeClass('active').children('.edit-button').remove();
411
412                     if (!editable.hasClass('active')) {
413                         editable.addClass('active').append(button);
414                     }
415                     if (editable.is('.annotation-inline-box')) {
416                         $('*[x-annotation-box]', editable).css({
417                             position: 'absolute',
418                             left: event.clientX - editable.offset().left + 5,
419                             top: event.clientY - editable.offset().top + 5
420                         }).show();
421                     }
422                     else {
423                         $('*[x-annotation-box]').hide();
424                     }
425                 });
426
427                 $('#insert-annotation-button').click(function(){
428                     addAnnotation();
429                     return false;
430                 });
431
432                 $('#insert-theme-button').click(function(){
433                     addTheme();
434                     return false;
435                 });
436                 
437                 $('#insert-symbol-button').click(function(){
438                     addSymbol();
439                     return false;
440                 });                
441
442                 $('.edit-button').live('click', function(event){
443                     event.preventDefault();
444                     openForEdit($(this).parent());
445                 });
446
447             }
448
449             $('.motyw').live('click', function(){
450                 selectTheme($(this).attr('theme-class'));
451             });
452
453             old_callback.call(this);
454         };
455
456         $.wiki.Perspective.call(this, options);
457     };
458
459     VisualPerspective.prototype = new $.wiki.Perspective();
460
461     VisualPerspective.prototype.freezeState = function(){
462
463     };
464
465     VisualPerspective.prototype.onEnter = function(success, failure){
466         $.wiki.Perspective.prototype.onEnter.call(this);
467
468         $.blockUI({
469             message: 'Uaktualnianie widoku...'
470         });
471
472         function _finalize(callback){
473             $.unblockUI();
474             if (callback)
475                 callback();
476         }
477
478         xml2html({
479             xml: this.doc.text,
480             success: function(element){
481                 $('#html-view').html(element);
482                 _finalize(success);
483             },
484             error: function(text){
485                 var message = $('<pre></pre>');
486                 message.text(text);
487                 $('#html-view').html('<p class="error">Wystąpił błąd:</p><pre>' +
488                 message.html() +
489                 '</pre>');
490                 _finalize(failure);
491             }
492         });
493     };
494
495     VisualPerspective.prototype.onExit = function(success, failure){
496         var self = this;
497
498         $.blockUI({
499             message: 'Zapisywanie widoku...'
500         });
501
502         function _finalize(callback){
503             $.unblockUI();
504             if (callback)
505                 callback();
506         }
507
508         if ($('#html-view .error').length > 0)
509             return _finalize(failure);
510
511         html2text({
512             element: $('#html-view div').get(0),
513             success: function(text){
514                 self.doc.setText(text);
515                 _finalize(success);
516             },
517             error: function(text){
518                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
519                 _finalize(failure);
520             }
521         });
522     };
523
524     $.wiki.VisualPerspective = VisualPerspective;
525
526 })(jQuery);