f39f7a87727ab1b8229a193690fd7e7d78b19888
[redakcja.git] / src / 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 = $("[x-node='motyw'][theme-class='" + themeId + "']")[0];
10         var e = $("[x-node='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 == Node.TEXT_NODE) {
22             node = node.parentNode;
23         }
24
25         if (node.nodeType != Node.ELEMENT_NODE) {
26             return false;
27         }
28
29         node = $(node);
30         if (node.attr('id') == 'caret') {
31             node = node.parent();
32         }
33         while (node.attr('x-pass-thru')) {
34             node = node.parent();
35         }
36         var xtype = node.attr('x-node');
37
38         if (!xtype || (xtype.search(':') >= 0) ||
39         xtype == 'motyw' ||
40         xtype == 'begin' ||
41         xtype == 'end') {
42             return false;
43         }
44
45         return true;
46     }
47
48     function verifyThemeBoundaryPoint(node) {
49         if (!verifyTagInsertPoint(node)) return false;
50         node = $(node);
51         // don't allow themes inside annotations
52         if (node.closest('[x-node="pe"]').length > 0)
53             return false;
54
55         return true;
56     }
57
58     /* Convert HTML fragment to plaintext */
59     var ANNOT_FORBIDDEN = ['pt', 'pa', 'pr', 'pe', 'begin', 'end', 'motyw'];
60
61     function html2plainText(fragment){
62         var text = "";
63
64         $(fragment.childNodes).each(function(){
65             if (this.nodeType == Node.TEXT_NODE)
66                 text += this.nodeValue;
67             else {
68                 if (this.nodeType == Node.ELEMENT_NODE &&
69                         $.inArray($(this).attr('x-node'), ANNOT_FORBIDDEN) == -1) {
70                     text += html2plainText(this);
71                 }
72             };
73         });
74
75         return text;
76     }
77
78
79     /* Insert annotation using current selection */
80     function addAnnotation(){
81         var selection = window.getSelection();
82         var n = selection.rangeCount;
83
84         if (selection.isCollapsed) {
85             window.alert("Nie zaznaczono żadnego obszaru");
86             return false;
87         }
88
89         var range = selection.getRangeAt(n - 1);
90
91         if (!verifyTagInsertPoint(range.endContainer)) {
92             window.alert("Nie można wstawić w to miejsce przypisu.");
93             return false;
94         }
95
96         text = '';
97         for (let i = 0; i < n; ++ i) {
98             let rangeI = selection.getRangeAt(i);
99             if (verifyTagInsertPoint(rangeI.startContainer) &&
100                 verifyTagInsertPoint(rangeI.endContainer)) {
101                 text += html2plainText(rangeI.cloneContents());
102             }
103         }
104         var tag = $('<span></span>');
105         range.collapse(false);
106         range.insertNode(tag[0]);
107
108         xml2html({
109             xml: '<pe><slowo_obce>' + text + '</slowo_obce> --- </pe>',
110             success: function(text){
111                 var t = $(text);
112                 tag.replaceWith(t);
113                 openForEdit(t);
114             },
115             error: function(){
116                 tag.remove();
117                 alert('Błąd przy dodawaniu przypisu:' + errors);
118             }
119         })
120     }
121
122
123
124     /* Insert theme using current selection */
125
126     function addTheme(){
127         var selection = window.getSelection();
128         var n = selection.rangeCount;
129
130         if (n == 0) {
131             window.alert("Nie zaznaczono żadnego obszaru");
132             return false;
133         }
134
135         // for now allow only 1 range
136         if (n > 1) {
137             window.alert("Zaznacz jeden obszar.");
138             return false;
139         }
140
141         // remember the selected range
142         var range = selection.getRangeAt(0);
143
144         if ($(range.startContainer).is('.html-editarea') ||
145         $(range.endContainer).is('.html-editarea')) {
146             window.alert("Motywy można oznaczać tylko na tekście nie otwartym do edycji. \n Zamknij edytowany fragment i spróbuj ponownie.");
147             return false;
148         }
149
150         // verify if the start/end points make even sense -
151         // they must be inside a x-node (otherwise they will be discarded)
152         // and the x-node must be a main text
153         if (!verifyThemeBoundaryPoint(range.startContainer)) {
154             window.alert("Motyw nie może się zaczynać w tym miejscu.");
155             return false;
156         }
157
158         if (!verifyThemeBoundaryPoint(range.endContainer)) {
159             window.alert("Motyw nie może się kończyć w tym miejscu.");
160             return false;
161         }
162
163         var date = (new Date()).getTime();
164         var random = Math.floor(4000000000 * Math.random());
165         var id = ('' + date) + '-' + ('' + random);
166
167         var createPoint = function(container, offset) {
168             var offsetBetweenCommas = function(text, offset) {
169                 if(text.length < 2 || offset < 1 || offset > text.length)
170                     return false;
171                 return text[offset-1] === ',' && text[offset] === ',';
172             }
173             var point = document.createRange();
174             offset = offsetBetweenCommas(container.textContent, offset) ? offset - 1 : offset;
175             point.setStart(container, offset);
176             return point;
177         }
178
179         var spoint = createPoint(range.startContainer, range.startOffset);
180         var epoint = createPoint(range.endContainer, range.endOffset);
181
182         var mtag, btag, etag, errors;
183
184         // insert theme-ref
185
186         xml2html({
187             xml: '<end id="e' + id + '" />',
188             success: function(text){
189                 etag = $('<span></span>');
190                 epoint.insertNode(etag[0]);
191                 etag.replaceWith(text);
192                 xml2html({
193                     xml: '<motyw id="m' + id + '"></motyw>',
194                     success: function(text){
195                         mtag = $('<span></span>');
196                         spoint.insertNode(mtag[0]);
197                         mtag.replaceWith(text);
198                         xml2html({
199                             xml: '<begin id="b' + id + '" />',
200                             success: function(text){
201                                 btag = $('<span></span>');
202                                 spoint.insertNode(btag[0])
203                                 btag.replaceWith(text);
204                                 selection.removeAllRanges();
205                                 openForEdit($('[x-node="motyw"][theme-class="' + id + '"]'));
206                             }
207                         });
208                     }
209                 });
210             }
211         });
212     }
213
214     function addSymbol(caret) {
215         let editArea;
216
217         if (caret) {
218             editArea = $("textarea", caret.element)[0];
219         } else {
220             editArea = $('div.html-editarea textarea')[0];
221         }
222
223         if(editArea) {
224             var specialCharsContainer = $("<div id='specialCharsContainer'><a href='#' id='specialCharsClose'>Zamknij</a><table id='tableSpecialChars' style='width: 600px;'></table></div>");
225
226             var specialChars = [' ', 'Ą','ą','Ć','ć','Ę','ę','Ł','ł','Ń','ń','Ó','ó','Ś','ś','Ż','ż','Ź','ź','Á','á','À','à',
227             'Â','â','Ä','ä','Å','å','Ā','ā','Ă','ă','Ã','ã',
228             'Æ','æ','Ç','ç','Č','č','Ċ','ċ','Ď','ď','É','é','È','è',
229             'Ê','ê','Ë','ë','Ē','ē','Ě','ě','Ġ','ġ','Ħ','ħ','Í','í','Î','î',
230             'Ī','ī','Ĭ','ĭ','Ľ','ľ','Ñ','ñ','Ň','ň','Ó','ó','Ö','ö',
231             'Ô','ô','Ō','ō','Ǒ','ǒ','Œ','œ','Ø','ø','Ř','ř','Š',
232             'š','Ş','ş','Ť','ť','Ţ','ţ','Ű','ű','Ú','ú','Ù','ù',
233             'Ü','ü','Ů','ů','Ū','ū','Û','û','Ŭ','ŭ',
234             'Ý','ý','Ž','ž','ß','Ð','ð','Þ','þ','А','а','Б',
235             'б','В','в','Г','г','Д','д','Е','е','Ё','ё','Ж',
236             'ж','З','з','И','и','Й','й','К','к','Л','л','М',
237             'м','Н','н','О','о','П','п','Р','р','С','с',
238             'Т','т','У','у','Ф','ф','Х','х','Ц','ц','Ч',
239             'ч','Ш','ш','Щ','щ','Ъ','ъ','Ы','ы','Ь','ь','Э',
240             'э','Ю','ю','Я','я','ѓ','є','і','ї','ј','љ','њ',
241             'Ґ','ґ','Α','α','Β','β','Γ','γ','Δ','δ','Ε','ε',
242             'Ζ','ζ','Η','η','Θ','θ','Ι','ι','Κ','κ','Λ','λ','Μ',
243             'μ','Ν','ν','Ξ','ξ','Ο','ο','Π','π','Ρ','ρ','Σ','ς','σ',
244             'Τ','τ','Υ','υ','Φ','φ','Χ','χ','Ψ','ψ','Ω','ω','–',
245             '—','¡','¿','$','¢','£','€','©','®','°','¹','²','³',
246             '¼','½','¾','†','§','‰','•','←','↑','→','↓',
247             '„','”','„”','«','»','«»','»«','’','[',']','~','|','−','·',
248             '×','÷','≈','≠','±','≤','≥','∈'];
249             var tableContent = "<tr>";
250
251             for(var i in specialChars) {
252                 if(i % 14 == 0 && i > 0) {
253                     tableContent += "</tr><tr>";
254                 }
255                 tableContent += "<td><input type='button' class='specialBtn' value='"+specialChars[i]+"'/></td>";
256             }
257
258             tableContent += "</tr>";
259             $("body").append(specialCharsContainer);
260
261
262              // localStorage for recently used characters - reading
263              if (typeof(localStorage) != 'undefined') {
264                  if (localStorage.getItem("recentSymbols")) {
265                      var recent = localStorage.getItem("recentSymbols");
266                      var recentArray = recent.split(";");
267                      var recentRow = "";
268                      for(var i in recentArray.reverse()) {
269                         recentRow += "<td><input type='button' class='specialBtn recentSymbol' value='"+recentArray[i]+"'/></td>";
270                      }
271                      recentRow = "<tr>" + recentRow + "</tr>";
272                  }
273              }
274             $("#tableSpecialChars").append(recentRow);
275             $("#tableSpecialChars").append(tableContent);
276
277             /* events */
278
279             $('.specialBtn').click(function(){
280                 var insertVal = $(this).val();
281
282                 // if we want to surround text with quotes
283                 // not sure if just check if value has length == 2
284
285                 if (caret) {
286                     caret.insertChar(insertVal);
287                     caret.focus();
288                 } else {
289                     if (insertVal.length == 2) {
290                         var startTag = insertVal[0];
291                         var endTag = insertVal[1];
292                         var textAreaOpened = editArea;
293                         //IE support
294                         if (document.selection) {
295                             textAreaOpened.focus();
296                             sel = document.selection.createRange();
297                             sel.text = startTag + sel.text + endTag;
298                         }
299                         //MOZILLA/NETSCAPE support
300                         else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') {
301                             var startPos = textAreaOpened.selectionStart;
302                             var endPos = textAreaOpened.selectionEnd;
303                             textAreaOpened.value = textAreaOpened.value.substring(0, startPos)
304                                 + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length);
305                         }
306                     } else {
307                         insertAtCaret(editArea, insertVal);
308                     }
309                 }
310
311                 // localStorage for recently used characters - saving
312                 if (typeof(localStorage) != 'undefined') {
313                     if (localStorage.getItem("recentSymbols")) {
314                         var recent = localStorage.getItem("recentSymbols");
315                         var recentArray = recent.split(";");
316                         var valIndex = $.inArray(insertVal, recentArray);
317                         //alert(valIndex);
318                         if(valIndex == -1) {
319                             // value not present in array yet
320                             if(recentArray.length > 13){
321                                 recentArray.shift();
322                                 recentArray.push(insertVal);
323                             } else {
324                                 recentArray.push(insertVal);
325                             }
326                         } else  {
327                             // value already in the array
328                             for(var i = valIndex; i < recentArray.length; i++){
329                                 recentArray[i] = recentArray[i+1];
330                             }
331                             recentArray[recentArray.length-1] = insertVal;
332                         }
333                         localStorage.setItem("recentSymbols", recentArray.join(";"));
334                     } else {
335                         localStorage.setItem("recentSymbols", insertVal);
336                     }
337                 }
338                 $(specialCharsContainer).remove();
339             });
340             $('#specialCharsClose').click(function(){
341                 $(specialCharsContainer).remove();
342             });
343
344         } else {
345             window.alert('Najedź na fragment tekstu, wybierz "Edytuj" i ustaw kursor na miejscu gdzie chcesz wstawić symbol.');
346         }
347     }
348
349     function insertAtCaret(txtarea,text) {
350         /* http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/ */
351         var scrollPos = txtarea.scrollTop;
352         var strPos = 0;
353         var backStart = 0;
354         var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
355         if (br == "ie") {
356             txtarea.focus();
357             var range = document.selection.createRange();
358             range.moveStart ('character', -txtarea.value.length);
359             strPos = backStart = range.text.length;
360         } else if (br == "ff") {
361             strPos = txtarea.selectionStart;
362             backStart = txtarea.selectionEnd;
363         }
364         var front = (txtarea.value).substring(0,strPos);
365         var back = (txtarea.value).substring(backStart,txtarea.value.length);
366         txtarea.value=front+text+back;
367         strPos = strPos + text.length;
368         if (br == "ie") {
369             txtarea.focus();
370             var range = document.selection.createRange();
371             range.moveStart ('character', -txtarea.value.length);
372             range.moveStart ('character', strPos);
373             range.moveEnd ('character', 0);
374             range.select();
375         } else if (br == "ff") {
376             txtarea.selectionStart = strPos;
377             txtarea.selectionEnd = strPos;
378             txtarea.focus();
379         }
380         txtarea.scrollTop = scrollPos;
381     }
382
383     /* open edition window for selected fragment */
384     function openForEdit($origin){
385         var $box = null
386
387         // annotations overlay their sub box - not their own box //
388         if ($origin.is(".annotation-inline-box")) {
389             $box = $("*[x-annotation-box]", $origin);
390         }
391         else {
392             $box = $origin;
393         }
394         var x = $box[0].offsetLeft;
395         var y = $box[0].offsetTop;
396
397         var w = $box.outerWidth();
398         var h = $box.innerHeight();
399
400         if ($origin.is(".annotation-inline-box")) {
401             w = Math.max(w, 400);
402             h = Math.max(h, 60);
403             if($('.htmlview div').offset().left + $('.htmlview div').width() > ($('.vsplitbar').offset().left - 480)){
404                 x = -(Math.max($origin.offset().left, $origin.width()));
405             } else {
406                 x = 100;
407             }
408         }
409         if ($origin.is('.reference-inline-box')) {
410             w = 400;
411             h = 32;
412             y -= 32;
413             x = Math.min(
414                 x,
415                 $('.htmlview div').offset().left + $('.htmlview div').width() - 400
416             );
417         }
418
419         // start edition on this node
420         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({
421             position: 'absolute',
422             height: h,
423             left: x,
424             top: y,
425             width: w
426         }).appendTo($box[0].offsetParent || $box.parent()).show();
427
428
429         if ($origin.is('*[x-edit-no-format]')) {
430             $('.akap-edit-button').remove();
431         }
432
433         if ($origin.is('[x-node="motyw"]')) {
434             $.themes.autocomplete($('textarea', $overlay));
435         }
436
437         if ($origin.is('[x-node="motyw"]')){
438             $('.delete-button', $overlay).click(function(){
439                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten motyw?")) {
440                     $('[theme-class="' + $origin.attr('theme-class') + '"]').remove();
441                     $overlay.remove();
442                     $(document).unbind('click.blur-overlay');
443                     return false;
444                 };
445             });
446         }
447         else if($box.is('*[x-annotation-box]') || $origin.is('*[x-edit-attribute]') || $origin.is('*[x-node="uwaga"]')) {
448             let q;
449             switch ($origin.attr('x-node')) {
450             case 'uwaga':
451                 q = 'tę uwagę';
452                 break;
453             case 'ref':
454                 q = 'tę referencję';
455                 break
456             default:
457                 q = 'ten przypis';
458             }
459             $('.delete-button', $overlay).click(function(){
460                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć " + q + "?")) {
461                     $origin.remove();
462                     $overlay.remove();
463                     $(document).unbind('click.blur-overlay');
464                     return false;
465                 };
466             });
467         }
468         else {
469             $('.delete-button', $overlay).html("Anuluj");
470             $('.delete-button', $overlay).click(function(){
471                 if (window.confirm("Czy jesteś pewien, że chcesz anulować zmiany?")) {
472                     $overlay.remove();
473                     $(document).unbind('click.blur-overlay');
474                     return false;
475                 };
476             });
477         }
478
479
480         var serializer = new XMLSerializer();
481
482         if($box.attr("x-edit-attribute")) {
483             source = $('<span x-pass-thru="true"/>');
484             source.text($box.attr("x-a-wl-" + $box.attr("x-edit-attribute")));
485             source = source[0];
486         } else {
487             source = $box[0];
488         }
489
490         html2text({
491             element: source,
492             stripOuter: true,
493             success: function(text){
494                 $('textarea', $overlay).val($.trim(text));
495
496                 setTimeout(function(){
497                     $('textarea', $overlay).elastic().focus();
498                 }, 50);
499
500                 function save(argument){
501                     var nodeName = $box.attr('x-node') || 'pe';
502                     var insertedText = $('textarea', $overlay).val();
503
504                     if ($origin.is('[x-node="motyw"]')) {
505                         insertedText = insertedText.replace(/,\s*$/, '');
506                     }
507
508                     if($box.attr("x-edit-attribute")) {
509                         xml = '<' + nodeName + ' ' + $box.attr("x-edit-attribute") + '="' + insertedText + '"/>';
510                     } else {
511                         xml = '<' + nodeName + '>' + insertedText + '</' + nodeName + '>';
512                     }
513
514                     xml2html({
515                         xml: xml,
516                         success: function(element){
517                             if (nodeName == 'out-of-flow-text') {
518                                 $(element).children().insertAfter($origin);
519                                 $origin.remove()
520                             }
521                             else if ($box.attr('x-edit-attribute')) {
522                                 $(element).insertAfter($origin);
523                                 $origin.remove();
524                             }
525                             else {
526                                 $origin.html($(element).html());
527                             }
528                             $overlay.remove();
529                         },
530                         error: function(text){
531                             alert('Błąd! ' + text);
532                         }
533                     })
534
535                     var msg = $("<div class='saveNotify'><p>Pamiętaj, żeby zapisać swoje zmiany.</p></div>");
536                     $("#base").prepend(msg);
537                     $('#base .saveNotify').fadeOut(3000, function(){
538                         $(this).remove();
539                     });
540                 }
541
542                 $('.akap-edit-button', $overlay).click(function(){
543                     var textAreaOpened = $('textarea', $overlay)[0];
544                     var startTag = "";
545                     var endTag = "";
546                     var buttonName = this.innerHTML;
547
548                     if(buttonName == "słowo obce") {
549                         startTag = "<slowo_obce>";
550                         endTag = "</slowo_obce>";
551                     } else if (buttonName == "wyróżnienie") {
552                         startTag = "<wyroznienie>";
553                         endTag = "</wyroznienie>";
554                     } else if (buttonName == "tytuł dzieła") {
555                         startTag = "<tytul_dziela>";
556                         endTag = "</tytul_dziela>";
557                     } else if(buttonName == "znak spec."){
558                         addSymbol();
559                         return false;
560                     }
561
562                     var myField = textAreaOpened;
563
564                     //IE support
565                     if (document.selection) {
566                         textAreaOpened.focus();
567                         sel = document.selection.createRange();
568                         sel.text = startTag + sel.text + endTag;
569                     }
570                     //MOZILLA/NETSCAPE support
571                     else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') {
572                         var startPos = textAreaOpened.selectionStart;
573                         var endPos = textAreaOpened.selectionEnd;
574                         textAreaOpened.value = textAreaOpened.value.substring(0, startPos)
575                             + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length);
576                     }
577                 });
578
579                 $('.accept-button', $overlay).click(function(){
580                     save();
581                     $(document).unbind('click.blur-overlay');
582                 });
583
584                 $(document).bind('click.blur-overlay', function(event){
585                     if ($(event.target).closest('.html-editarea, #specialCharsContainer').length > 0) {
586                         return;
587                     }
588                     save();
589                     $(document).unbind('click.blur-overlay');
590                 });
591
592             },
593             error: function(text){
594                 alert('Błąd! ' + text);
595             }
596         });
597     }
598
599     function createUwagaBefore(before) {
600         xml2html({
601             xml: '<uwaga/>',
602             success: function(element){
603                 let $element = $(element);
604                 $element.insertBefore(before);
605                 openForEdit($element);
606             }
607         });
608     }
609
610     class VisualPerspective extends $.wiki.Perspective {
611         constructor(options) {
612             super(options);
613             let self = this;
614             var element = $("#html-view");
615             var button = $('<button class="edit-button active-block-button">Edytuj</button>');
616             var uwagaButton = $('<button class="uwaga-button active-block-button">Uwaga</button>');
617
618             if (!CurrentDocument.readonly) {
619
620                 $('#html-view').bind('mousemove', function(event){
621                     var editable = $(event.target).closest('*[x-editable]');
622                     $('.active', element).not(editable).removeClass('active').children('.active-block-button').remove();
623
624                     if (!editable.hasClass('active')) {
625                         editable.addClass('active').append(button);
626                         if (!editable.is('[x-edit-attribute]') &&
627                             !editable.is('.annotation-inline-box') &&
628                             !editable.is('[x-edit-no-format]')
629                            ) {
630                             editable.append(uwagaButton);
631                         }
632                     }
633                     if (editable.is('.annotation-inline-box')) {
634                         $('*[x-annotation-box]', editable).css({
635                         }).show();
636                     }
637                 });
638
639                 self.caret = new Caret(element);
640
641                 $('#insert-reference-button').click(function(){
642                     self.addReference();
643                     return false;
644                 });
645
646                 $('#insert-annotation-button').click(function(){
647                     addAnnotation();
648                     return false;
649                 });
650
651                 $('#insert-theme-button').click(function(){
652                     addTheme();
653                     return false;
654                 });
655
656                 $(".insert-inline-tag").click(function() {
657                     self.insertInlineTag($(this).attr('data-tag'));
658                     return false;
659                 });
660
661                 $(".insert-char").click(function() {
662                     addSymbol(caret=self.caret);
663                     return false;
664                 });
665
666                 $(document).on('click', '.edit-button', function(event){
667                     event.preventDefault();
668                     openForEdit($(this).parent());
669                 });
670
671                 $(document).on('click', '.uwaga-button', function(event){
672                     event.preventDefault();
673                     createUwagaBefore($(this).parent());
674                 });
675             }
676
677             $(document).on('click', '[x-node="motyw"]', function(){
678                 selectTheme($(this).attr('theme-class'));
679             });
680
681             element.on('click', '.annotation', function(event) {
682                 event.preventDefault();
683                 event.redakcja_caret_ignore = true;
684                 $('[x-annotation-box]', $(this).parent()).toggleClass('editing');
685                 self.caret.detach();
686             });
687         }
688
689         onEnter(success, failure) {
690             super.onEnter();
691
692             $.blockUI({
693                 message: 'Uaktualnianie widoku...'
694             });
695
696             function _finalize(callback){
697                 $.unblockUI();
698                 if (callback)
699                     callback();
700             }
701
702             xml2html({
703                 xml: this.doc.text,
704                 base: this.doc.getBase(),
705                 success: function(element){
706
707                     var htmlView = $('#html-view');
708                     htmlView.html(element);
709
710                     _finalize(success);
711                 },
712                 error: function(text, source){
713                     let err = '<p class="error">Wystąpił błąd:</p><p>'+text+'</p>';
714                     if (source)
715                         err += '<pre>'+source.replace(/&/g, '&amp;').replace(/</g, '&lt;')+'</pre>'
716                     $('#html-view').html(err);
717                     _finalize(failure);
718                 }
719             });
720         };
721
722         onExit(success, failure) {
723             var self = this;
724
725             self.caret.detach();
726
727             $.wiki.exitTab('#PropertiesPerspective');
728
729             $.blockUI({
730                 message: 'Zapisywanie widoku...'
731             });
732
733             function _finalize(callback){
734                 $.unblockUI();
735                 if (callback)
736                     callback();
737             }
738
739             if ($('#html-view .error').length > 0)
740                 return _finalize(failure);
741
742             html2text({
743                 element: $('#html-view').get(0),
744                 stripOuter: true,
745                 success: function(text){
746                     self.doc.setText(text);
747                     _finalize(success);
748                 },
749                 error: function(text){
750                     $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
751                     _finalize(failure);
752                 }
753             });
754         };
755
756         insertInlineTag(tag) {
757             this.caret.detach();
758
759             let selection = window.getSelection();
760             var n = selection.rangeCount;
761             if (n != 1 || selection.isCollapsed) {
762                 window.alert("Nie zaznaczono obszaru");
763                 return false
764             }
765             let range = selection.getRangeAt(0);
766
767             // Make sure that:
768             // Both ends are in the same x-node container.
769             // Both ends are set to text nodes.
770             // TODO: That the container is a inline-text container.
771             let commonNode = range.endContainer;
772
773             if (commonNode.nodeType == Node.TEXT_NODE) {
774                 commonNode = commonNode.parentNode;
775             }
776             let node = range.startContainer;
777             if (node.nodeType == Node.TEXT_NODE) {
778                 node = node.parentNode;
779             }
780             if (node != commonNode) {
781                 window.alert("Zły obszar.");
782                 return false;
783             }
784
785             let end;
786             if (range.endContainer.nodeType == Node.TEXT_NODE) {
787                 end = range.endContainer.splitText(range.endOffset);
788             } else {
789                 end = document.createTextNode('');
790                 let cont = $(range.endContainer).contents();
791                 if (range.endOffset < cont.length) {
792                     range.endContainer.insertBefore(end, cont[range.endOffset])
793                 } else {
794                     range.endContainer.append(end);
795                 }
796             }
797
798             let current;
799             if (range.startContainer.nodeType == Node.TEXT_NODE) {
800                 current = range.startContainer.splitText(range.startOffset);
801             } else {
802                 current = document.createTextNode('');
803                 let cont = $(range.startContainer).contents();
804                 if (range.startOffset < cont.length) {
805                     range.startContainer.insertBefore(current, cont[range.startOffset])
806                 } else {
807                     startNode.append(current);
808                 }
809             }
810
811             // We will construct a HTML element with the range selected.
812             let div = $("<span x-pass-thru='true'>");
813             while (current != end) {
814                 n = current.nextSibling;
815                 $(current).appendTo(div);
816                 current = n;
817             }
818
819             html2text({
820                 element: div[0],
821                 success: function(d) {
822                     xml2html({
823                         xml: d = '<' + tag + '>' + d + '</' + tag + '>',
824                         success: function(html) {
825                             // What if no end?
826                             node.insertBefore($(html)[0], end);
827                         }
828                     });
829                 },
830                 error: function(a, b) {
831                     console.log(a, b);
832                 }
833             });
834         }
835
836         insertAtRange(range, elem) {
837             let self = this;
838             let $end = $(range.endContainer);
839             if ($end.attr('id') == 'caret') {
840                 self.caret.insert(elem);
841             } else {
842                 range.insertNode(elem[0]);
843             }
844         }
845
846         addReference() {
847             let self = this;
848             var selection = window.getSelection();
849             var n = selection.rangeCount;
850
851             // TODO: if no selection, take caret position..
852             if (n == 0) {
853                 window.alert("Nie zaznaczono żadnego obszaru");
854                 return false;
855             }
856
857             var range = selection.getRangeAt(n - 1);
858             if (!verifyTagInsertPoint(range.endContainer)) {
859                 window.alert("Nie można wstawić w to miejsce referencji.");
860                 return false;
861             }
862
863             var tag = $('<span></span>');
864
865             range.collapse(false);
866             self.insertAtRange(range, tag);
867
868             xml2html({
869                 xml: '<ref href=""/>',
870                 success: function(text){
871                     var t = $(text);
872                     tag.replaceWith(t);
873                     openForEdit(t);
874                 },
875                 error: function(){
876                     tag.remove();
877                     alert('Błąd przy dodawaniu referncji:' + errors);
878                 }
879             })
880         }
881     }
882
883     $.wiki.VisualPerspective = VisualPerspective;
884
885 })(jQuery);