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         /* always stick to the left to avoid interfering with gallery */
294         var x = 20;
295         var y = $origin.offset().top + $("#html-view").scrollTop();
296         
297         
298         var w = $box.outerWidth();
299         var h = $box.innerHeight();
300
301         if ($origin.is(".annotation-inline-box")) {
302             w = Math.max(w, 400);
303             h = Math.max(h, 60);
304         }
305
306         // start edition on this node
307         var $overlay = $('<div class="html-editarea"><button class="accept-button">Zapisz</button><button class="delete-button">Usuń</button><textarea></textarea></div>').css({
308             position: 'absolute',
309             height: h,
310             left: x,
311             top: y,
312             width: w
313         }).appendTo($('#html-view')).show();  /* appending outside of the document structure */
314         
315
316         if ($origin.is('.motyw')) {
317             $('textarea', $overlay).autocomplete('/themes', {
318                 autoFill: true,
319                 multiple: true,
320                 selectFirst: true,
321                 highlight: false
322             });
323         }
324
325         if ($origin.is('.motyw')){
326             $('.delete-button', $overlay).click(function(){
327                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten motyw ?")) {
328                     $('[theme-class=' + $origin.attr('theme-class') + ']').remove();
329                     $overlay.remove();
330                     $(document).unbind('click.blur-overlay');
331                     return false;
332                 };
333             });
334         }
335         else if($box.is('*[x-annotation-box]')) {
336             $('.delete-button', $overlay).click(function(){
337                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten przypis?")) {
338                     $origin.remove();
339                     $overlay.remove();
340                     $(document).unbind('click.blur-overlay');
341                     return false;
342                 };
343             });
344         }
345         else {
346             $('.delete-button', $overlay).hide();
347         }
348
349
350         var serializer = new XMLSerializer();
351
352         html2text({
353             element: $box[0],
354             stripOuter: true,
355             success: function(text){
356                 $('textarea', $overlay).val($.trim(text));
357
358                 setTimeout(function(){
359                     $('textarea', $overlay).elastic().focus();
360                 }, 50);
361
362                 function save(argument){
363                     var nodeName = $box.attr('x-node') || 'pe';
364                     var insertedText = $('textarea', $overlay).val();
365
366                     if ($origin.is('.motyw')) {
367                         insertedText = insertedText.replace(/,\s*$/, '');
368                     }
369
370                     xml2html({
371                         xml: '<' + nodeName + '>' + insertedText + '</' + nodeName + '>',
372                         success: function(element){
373                             $origin.html($(element).html());
374                             $overlay.remove();
375                         },
376                         error: function(text){
377                             $overlay.remove();
378                             alert('Błąd! ' + text);
379                         }
380                     })
381                 }
382
383                 $('.accept-button', $overlay).click(function(){
384                     save();
385                 });
386
387                 $(document).bind('click.blur-overlay', function(event){
388                     if ($(event.target).parents('.html-editarea').length > 0) {
389                         return;
390                     }
391                     save();
392
393                     $(document).unbind('click.blur-overlay');
394                 });
395
396             },
397             error: function(text){
398                 alert('Błąd! ' + text);
399             }
400         });
401     }
402
403     function VisualPerspective(options){
404
405         var old_callback = options.callback;
406
407         options.callback = function(){
408             var element = $("#html-view");
409             var button = $('<button class="edit-button">Edytuj</button>');
410
411             if (!CurrentDocument.readonly) {
412                 $('#html-view').bind('mousemove', function(event){
413                     var editable = $(event.target).closest('*[x-editable]');
414                     $('.active', element).not(editable).removeClass('active').children('.edit-button').remove();
415
416                     if (!editable.hasClass('active')) {
417                         editable.addClass('active').append(button);
418                     }
419                     if (editable.is('.annotation-inline-box')) {
420                         $('*[x-annotation-box]', editable).css({
421                             position: 'absolute',
422                             left: event.clientX - editable.offset().left + 5,
423                             top: event.clientY - editable.offset().top + 5
424                         }).show();
425                     }
426                     else {
427                         $('*[x-annotation-box]').hide();
428                     }
429                 });
430
431                 $('#insert-annotation-button').click(function(){
432                     addAnnotation();
433                     return false;
434                 });
435
436                 $('#insert-theme-button').click(function(){
437                     addTheme();
438                     return false;
439                 });
440                 
441                 $('#insert-symbol-button').click(function(){
442                     addSymbol();
443                     return false;
444                 });                
445
446                 $('.edit-button').live('click', function(event){
447                     event.preventDefault();
448                     openForEdit($(this).parent());
449                 });
450
451             }
452
453             $('.motyw').live('click', function(){
454                 selectTheme($(this).attr('theme-class'));
455             });
456
457             old_callback.call(this);
458         };
459
460         $.wiki.Perspective.call(this, options);
461     };
462
463     VisualPerspective.prototype = new $.wiki.Perspective();
464
465     VisualPerspective.prototype.freezeState = function(){
466
467     };
468
469     VisualPerspective.prototype.onEnter = function(success, failure){
470         $.wiki.Perspective.prototype.onEnter.call(this);
471
472         $.blockUI({
473             message: 'Uaktualnianie widoku...'
474         });
475
476         function _finalize(callback){
477             $.unblockUI();
478             if (callback)
479                 callback();
480         }
481
482         xml2html({
483             xml: this.doc.text,
484             success: function(element){
485                 $('#html-view').html(element);
486                 _finalize(success);
487             },
488             error: function(text){
489                 var message = $('<pre></pre>');
490                 message.text(text);
491                 $('#html-view').html('<p class="error">Wystąpił błąd:</p><pre>' +
492                 message.html() +
493                 '</pre>');
494                 _finalize(failure);
495             }
496         });
497     };
498
499     VisualPerspective.prototype.onExit = function(success, failure){
500         var self = this;
501
502         $.blockUI({
503             message: 'Zapisywanie widoku...'
504         });
505
506         function _finalize(callback){
507             $.unblockUI();
508             if (callback)
509                 callback();
510         }
511
512         if ($('#html-view .error').length > 0)
513             return _finalize(failure);
514
515         html2text({
516             element: $('#html-view div').get(0),
517             success: function(text){
518                 self.doc.setText(text);
519                 _finalize(success);
520             },
521             error: function(text){
522                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
523                 _finalize(failure);
524             }
525         });
526     };
527
528     $.wiki.VisualPerspective = VisualPerspective;
529
530 })(jQuery);