Shorter XML error message in WYSIWYG editor.
[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         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             var specialChars = ['Ą','ą','Ć','ć','Ę','ę','Ł','ł','Ń','ń','Ó','ó','Ś','ś','Ż','ż','Ź','ź','Á','á','À','à',
200             'Â','â','Ä','ä','Å','å','Ā','ā','Ă','ă','Ã','ã',
201             'Æ','æ','Ç','ç','Č','č','Ċ','ċ','Ď','ď','É','é','È','è',
202             'Ê','ê','Ë','ë','Ē','ē','Ě','ě','Ġ','ġ','Ħ','ħ','Í','í','Î','î',
203             'Ī','ī','Ĭ','ĭ','Ľ','ľ','Ñ','ñ','Ň','ň','Ó','ó','Ö','ö',
204             'Ô','ô','Ō','ō','Ǒ','ǒ','Œ','œ','Ø','ø','Ř','ř','Š',
205             'š','Ş','ş','Ť','ť','Ţ','ţ','Ű','ű','Ú','ú',
206             'Ü','ü','Ů','ů','Ū','ū','Û','û','Ŭ','ŭ',
207             'Ý','ý','Ž','ž','ß','Ð','ð','Þ','þ','А','а','Б',
208             'б','В','в','Г','г','Д','д','Е','е','Ё','ё','Ж',
209             'ж','З','з','И','и','Й','й','К','к','Л','л','М',
210             'м','Н','н','О','о','П','п','Р','р','С','с',
211             'Т','т','У','у','Ф','ф','Х','х','Ц','ц','Ч',
212             'ч','Ш','ш','Щ','щ','Ъ','ъ','Ы','ы','Ь','ь','Э',
213             'э','Ю','ю','Я','я','ѓ','є','і','ї','ј','љ','њ',
214             'Ґ','ґ','Α','α','Β','β','Γ','γ','Δ','δ','Ε','ε',
215             'Ζ','ζ','Η','η','Θ','θ','Ι','ι','Κ','κ','Λ','λ','Μ',
216             'μ','Ν','ν','Ξ','ξ','Ο','ο','Π','π','Ρ','ρ','Σ','ς','σ',
217             'Τ','τ','Υ','υ','Φ','φ','Χ','χ','Ψ','ψ','Ω','ω','–',
218             '—','¡','¿','$','¢','£','€','©','®','°','¹','²','³',
219             '¼','½','¾','†','§','‰','•','←','↑','→','↓',
220             '„”','«»','’','[',']','[','~','|','−','·',
221             '×','÷','≈','≠','±','≤','≥','∈'];
222             var tableContent = "<tr>";
223             
224             for(var i in specialChars) {
225                 if(i % 14 == 0 && i > 0) {
226                     tableContent += "</tr><tr>";
227                 }              
228                 tableContent += "<td><input type='button' class='specialBtn' value='"+specialChars[i]+"'/></td>";              
229             }
230             
231             tableContent += "</tr>";                                   
232             $("#content").append(specialCharsContainer);
233             $("#tableSpecialChars").append(tableContent);
234             
235             /* events */
236             
237             $('.specialBtn').click(function(){
238                 insertAtCaret($('div.html-editarea textarea')[0], $(this).val());
239                 $(specialCharsContainer).remove();
240             });         
241             $('#specialCharsClose').click(function(){
242                 $(specialCharsContainer).remove();
243             });                   
244             
245         } else {
246             window.alert('Najedź na fragment tekstu, wybierz "Edytuj" i ustaw kursor na miejscu gdzie chcesz wstawić symbol.');
247         }
248     }
249
250     function insertAtCaret(txtarea,text) { 
251         /* http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/ */
252         var scrollPos = txtarea.scrollTop; 
253         var strPos = 0; 
254         var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
255         if (br == "ie") { 
256             txtarea.focus();
257             var range = document.selection.createRange(); 
258             range.moveStart ('character', -txtarea.value.length); 
259             strPos = range.text.length; 
260         } else if (br == "ff") strPos = txtarea.selectionStart; 
261         var front = (txtarea.value).substring(0,strPos); 
262         var back = (txtarea.value).substring(strPos,txtarea.value.length); 
263         txtarea.value=front+text+back; 
264         strPos = strPos + text.length; 
265         if (br == "ie") { 
266             txtarea.focus(); 
267             var range = document.selection.createRange(); 
268             range.moveStart ('character', -txtarea.value.length); 
269             range.moveStart ('character', strPos); 
270             range.moveEnd ('character', 0); 
271             range.select(); 
272         } else if (br == "ff") { 
273             txtarea.selectionStart = strPos; 
274             txtarea.selectionEnd = strPos; 
275             txtarea.focus(); 
276         } 
277         txtarea.scrollTop = scrollPos; 
278     } 
279
280     /* open edition window for selected fragment */
281     function openForEdit($origin){
282         var $box = null
283
284         // annotations overlay their sub box - not their own box //
285         if ($origin.is(".annotation-inline-box")) {
286             $box = $("*[x-annotation-box]", $origin);
287         }
288         else {
289             $box = $origin;
290         }
291
292         /* always stick to the left to avoid interfering with gallery */
293         var x = 20;
294         var y = $origin.offset().top + $("#html-view").scrollTop();
295         
296         
297         var w = $box.outerWidth();
298         var h = $box.innerHeight();
299
300         if ($origin.is(".annotation-inline-box")) {
301             w = Math.max(w, 400);
302             h = Math.max(h, 60);
303         }
304
305         // start edition on this node
306         var $overlay = $('<div class="html-editarea"><button class="accept-button">Zapisz</button><button class="delete-button">Usuń</button><textarea></textarea></div>').css({
307             position: 'absolute',
308             height: h,
309             left: x,
310             top: y,
311             width: w
312         }).appendTo($('#html-view')).show();  /* appending outside of the document structure */
313         
314
315         if ($origin.is('.motyw')) {
316             $('textarea', $overlay).autocomplete('/themes', {
317                 autoFill: true,
318                 multiple: true,
319                 selectFirst: true,
320                 highlight: false
321             });
322         }
323
324         if ($origin.is('.motyw')){
325             $('.delete-button', $overlay).click(function(){
326                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten motyw ?")) {
327                     $('[theme-class=' + $origin.attr('theme-class') + ']').remove();
328                     $overlay.remove();
329                     $(document).unbind('click.blur-overlay');
330                     return false;
331                 };
332             });
333         }
334         else if($box.is('*[x-annotation-box]')) {
335             $('.delete-button', $overlay).click(function(){
336                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten przypis?")) {
337                     $origin.remove();
338                     $overlay.remove();
339                     $(document).unbind('click.blur-overlay');
340                     return false;
341                 };
342             });
343         }
344         else {
345             $('.delete-button', $overlay).hide();
346         }
347
348
349         var serializer = new XMLSerializer();
350
351         html2text({
352             element: $box[0],
353             stripOuter: true,
354             success: function(text){
355                 $('textarea', $overlay).val($.trim(text));
356
357                 setTimeout(function(){
358                     $('textarea', $overlay).elastic().focus();
359                 }, 50);
360
361                 function save(argument){
362                     var nodeName = $box.attr('x-node') || 'pe';
363                     var insertedText = $('textarea', $overlay).val();
364
365                     if ($origin.is('.motyw')) {
366                         insertedText = insertedText.replace(/,\s*$/, '');
367                     }
368
369                     xml2html({
370                         xml: '<' + nodeName + '>' + insertedText + '</' + nodeName + '>',
371                         success: function(element){
372                             $origin.html($(element).html());
373                             $overlay.remove();
374                         },
375                         error: function(text){
376                             $overlay.remove();
377                             alert('Błąd! ' + text);
378                         }
379                     })
380                 }
381
382                 $('.accept-button', $overlay).click(function(){
383                     save();
384                 });
385
386                 $(document).bind('click.blur-overlay', function(event){
387                     if ($(event.target).parents('.html-editarea').length > 0) {
388                         return;
389                     }
390                     save();
391
392                     $(document).unbind('click.blur-overlay');
393                 });
394
395             },
396             error: function(text){
397                 alert('Błąd! ' + text);
398             }
399         });
400     }
401
402     function VisualPerspective(options){
403
404         var old_callback = options.callback;
405
406         options.callback = function(){
407             var element = $("#html-view");
408             var button = $('<button class="edit-button">Edytuj</button>');
409
410             if (!CurrentDocument.readonly) {
411                 $('#html-view').bind('mousemove', function(event){
412                     var editable = $(event.target).closest('*[x-editable]');
413                     $('.active', element).not(editable).removeClass('active').children('.edit-button').remove();
414
415                     if (!editable.hasClass('active')) {
416                         editable.addClass('active').append(button);
417                     }
418                     if (editable.is('.annotation-inline-box')) {
419                         $('*[x-annotation-box]', editable).css({
420                             position: 'absolute',
421                             left: event.clientX - editable.offset().left + 5,
422                             top: event.clientY - editable.offset().top + 5
423                         }).show();
424                     }
425                     else {
426                         $('*[x-annotation-box]').hide();
427                     }
428                 });
429
430                 $('#insert-annotation-button').click(function(){
431                     addAnnotation();
432                     return false;
433                 });
434
435                 $('#insert-theme-button').click(function(){
436                     addTheme();
437                     return false;
438                 });
439                 
440                 $('#insert-symbol-button').click(function(){
441                     addSymbol();
442                     return false;
443                 });                
444
445                 $('.edit-button').live('click', function(event){
446                     event.preventDefault();
447                     openForEdit($(this).parent());
448                 });
449
450             }
451
452             $('.motyw').live('click', function(){
453                 selectTheme($(this).attr('theme-class'));
454             });
455
456             old_callback.call(this);
457         };
458
459         $.wiki.Perspective.call(this, options);
460     };
461
462     VisualPerspective.prototype = new $.wiki.Perspective();
463
464     VisualPerspective.prototype.freezeState = function(){
465
466     };
467
468     VisualPerspective.prototype.onEnter = function(success, failure){
469         $.wiki.Perspective.prototype.onEnter.call(this);
470
471         $.blockUI({
472             message: 'Uaktualnianie widoku...'
473         });
474
475         function _finalize(callback){
476             $.unblockUI();
477             if (callback)
478                 callback();
479         }
480
481         xml2html({
482             xml: this.doc.text,
483             success: function(element){
484                 $('#html-view').html(element);
485                 _finalize(success);
486             },
487             error: function(text){
488                 /* only basic error message */
489                 var errorArray = text.split("\n");
490                 var errorLocation = errorArray[2].split(":")[0];
491                 text = errorLocation;
492                 $('#html-view').html('<p class="error">Wystąpił błąd: '+ text + '</p>');
493                 _finalize(failure);
494             }
495         });
496     };
497
498     VisualPerspective.prototype.onExit = function(success, failure){
499         var self = this;
500
501         $.blockUI({
502             message: 'Zapisywanie widoku...'
503         });
504
505         function _finalize(callback){
506             $.unblockUI();
507             if (callback)
508                 callback();
509         }
510
511         if ($('#html-view .error').length > 0)
512             return _finalize(failure);
513
514         html2text({
515             element: $('#html-view div').get(0),
516             success: function(text){
517                 self.doc.setText(text);
518                 _finalize(success);
519             },
520             error: function(text){
521                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
522                 _finalize(failure);
523             }
524         });
525     };
526
527     $.wiki.VisualPerspective = VisualPerspective;
528
529 })(jQuery);