c8f84e1f53c78b6e7a3f29fbf7fc09a823e7a3d0
[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             var old_callback = options.callback;
613
614             options.callback = function(){
615                 let self = this;
616                 var element = $("#html-view");
617                 var button = $('<button class="edit-button active-block-button">Edytuj</button>');
618                 var uwagaButton = $('<button class="uwaga-button active-block-button">Uwaga</button>');
619
620                 if (!CurrentDocument.readonly) {
621
622                     $('#html-view').bind('mousemove', function(event){
623                         var editable = $(event.target).closest('*[x-editable]');
624                         $('.active', element).not(editable).removeClass('active').children('.active-block-button').remove();
625
626                         if (!editable.hasClass('active')) {
627                             editable.addClass('active').append(button);
628                             if (!editable.is('[x-edit-attribute]') &&
629                                 !editable.is('.annotation-inline-box') &&
630                                 !editable.is('[x-edit-no-format]')
631                                ) {
632                                 editable.append(uwagaButton);
633                             }
634                         }
635                         if (editable.is('.annotation-inline-box')) {
636                             $('*[x-annotation-box]', editable).css({
637                             }).show();
638                         }
639                     });
640
641                     self.caret = new Caret(element);
642
643                     $('#insert-reference-button').click(function(){
644                         self.addReference();
645                         return false;
646                     });
647
648                     $('#insert-annotation-button').click(function(){
649                         addAnnotation();
650                         return false;
651                     });
652
653                     $('#insert-theme-button').click(function(){
654                         addTheme();
655                         return false;
656                     });
657
658
659                     $(".insert-inline-tag").click(function() {
660                         self.insertInlineTag($(this).attr('data-tag'));
661                         return false;
662                     });
663
664                     $(".insert-char").click(function() {
665                         addSymbol(caret=self.caret);
666                         return false;
667                     });
668
669                     $(document).on('click', '.edit-button', function(event){
670                         event.preventDefault();
671                         openForEdit($(this).parent());
672                     });
673
674                     $(document).on('click', '.uwaga-button', function(event){
675                         event.preventDefault();
676                         createUwagaBefore($(this).parent());
677                     });
678                 }
679
680                 $(document).on('click', '[x-node="motyw"]', function(){
681                     selectTheme($(this).attr('theme-class'));
682                 });
683
684                 element.on('click', '.annotation', function(event) {
685                     event.preventDefault();
686                     event.redakcja_caret_ignore = true;
687                     $('[x-annotation-box]', $(this).parent()).toggleClass('editing');
688                     self.caret.detach();
689                 });
690
691                 old_callback.call(this);
692             };
693
694             super(options);
695         }
696
697         onEnter(success, failure) {
698             super.onEnter();
699
700             $.blockUI({
701                 message: 'Uaktualnianie widoku...'
702             });
703
704             function _finalize(callback){
705                 $.unblockUI();
706                 if (callback)
707                     callback();
708             }
709
710             xml2html({
711                 xml: this.doc.text,
712                 base: this.doc.getBase(),
713                 success: function(element){
714
715                     var htmlView = $('#html-view');
716                     htmlView.html(element);
717
718                     _finalize(success);
719                 },
720                 error: function(text, source){
721                     let err = '<p class="error">Wystąpił błąd:</p><p>'+text+'</p>';
722                     if (source)
723                         err += '<pre>'+source.replace(/&/g, '&amp;').replace(/</g, '&lt;')+'</pre>'
724                     $('#html-view').html(err);
725                     _finalize(failure);
726                 }
727             });
728         };
729
730         onExit(success, failure) {
731             var self = this;
732
733             self.caret.detach();
734
735             $.wiki.exitTab('#PropertiesPerspective');
736
737             $.blockUI({
738                 message: 'Zapisywanie widoku...'
739             });
740
741             function _finalize(callback){
742                 $.unblockUI();
743                 if (callback)
744                     callback();
745             }
746
747             if ($('#html-view .error').length > 0)
748                 return _finalize(failure);
749
750             html2text({
751                 element: $('#html-view').get(0),
752                 stripOuter: true,
753                 success: function(text){
754                     self.doc.setText(text);
755                     _finalize(success);
756                 },
757                 error: function(text){
758                     $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
759                     _finalize(failure);
760                 }
761             });
762         };
763
764         insertInlineTag(tag) {
765             this.caret.detach();
766
767             let selection = window.getSelection();
768             var n = selection.rangeCount;
769             if (n != 1 || selection.isCollapsed) {
770                 window.alert("Nie zaznaczono obszaru");
771                 return false
772             }
773             let range = selection.getRangeAt(0);
774
775             // Make sure that:
776             // Both ends are in the same x-node container.
777             // Both ends are set to text nodes.
778             // TODO: That the container is a inline-text container.
779             let commonNode = range.endContainer;
780
781             if (commonNode.nodeType == Node.TEXT_NODE) {
782                 commonNode = commonNode.parentNode;
783             }
784             let node = range.startContainer;
785             if (node.nodeType == Node.TEXT_NODE) {
786                 node = node.parentNode;
787             }
788             if (node != commonNode) {
789                 window.alert("Zły obszar.");
790                 return false;
791             }
792
793             let end;
794             if (range.endContainer.nodeType == Node.TEXT_NODE) {
795                 end = range.endContainer.splitText(range.endOffset);
796             } else {
797                 end = document.createTextNode('');
798                 let cont = $(range.endContainer).contents();
799                 if (range.endOffset < cont.length) {
800                     range.endContainer.insertBefore(end, cont[range.endOffset])
801                 } else {
802                     range.endContainer.append(end);
803                 }
804             }
805
806             let current;
807             if (range.startContainer.nodeType == Node.TEXT_NODE) {
808                 current = range.startContainer.splitText(range.startOffset);
809             } else {
810                 current = document.createTextNode('');
811                 let cont = $(range.startContainer).contents();
812                 if (range.startOffset < cont.length) {
813                     range.startContainer.insertBefore(current, cont[range.startOffset])
814                 } else {
815                     startNode.append(current);
816                 }
817             }
818
819             // We will construct a HTML element with the range selected.
820             let div = $("<span x-pass-thru='true'>");
821             while (current != end) {
822                 n = current.nextSibling;
823                 $(current).appendTo(div);
824                 current = n;
825             }
826
827             html2text({
828                 element: div[0],
829                 success: function(d) {
830                     xml2html({
831                         xml: d = '<' + tag + '>' + d + '</' + tag + '>',
832                         success: function(html) {
833                             // What if no end?
834                             node.insertBefore($(html)[0], end);
835                         }
836                     });
837                 },
838                 error: function(a, b) {
839                     console.log(a, b);
840                 }
841             });
842         }
843
844         insertAtRange(range, elem) {
845             let self = this;
846             let $end = $(range.endContainer);
847             if ($end.attr('id') == 'caret') {
848                 self.caret.insert(elem);
849             } else {
850                 range.insertNode(elem[0]);
851             }
852         }
853
854         addReference() {
855             let self = this;
856             var selection = window.getSelection();
857             var n = selection.rangeCount;
858
859             // TODO: if no selection, take caret position..
860             if (n == 0) {
861                 window.alert("Nie zaznaczono żadnego obszaru");
862                 return false;
863             }
864
865             var range = selection.getRangeAt(n - 1);
866             if (!verifyTagInsertPoint(range.endContainer)) {
867                 window.alert("Nie można wstawić w to miejsce referencji.");
868                 return false;
869             }
870
871             var tag = $('<span></span>');
872
873             range.collapse(false);
874             self.insertAtRange(range, tag);
875
876             xml2html({
877                 xml: '<ref href=""/>',
878                 success: function(text){
879                     var t = $(text);
880                     tag.replaceWith(t);
881                     openForEdit(t);
882                 },
883                 error: function(){
884                     tag.remove();
885                     alert('Błąd przy dodawaniu referncji:' + errors);
886                 }
887             })
888         }
889     }
890
891     $.wiki.VisualPerspective = VisualPerspective;
892
893 })(jQuery);