reversion
[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                             $.wiki.activePerspective().flush();
530                         },
531                         error: function(text){
532                             alert('Błąd! ' + text);
533                         }
534                     })
535
536                     var msg = $("<div class='saveNotify'><p>Pamiętaj, żeby zapisać swoje zmiany.</p></div>");
537                     $("#base").prepend(msg);
538                     $('#base .saveNotify').fadeOut(3000, function(){
539                         $(this).remove();
540                     });
541                 }
542
543                 $('.akap-edit-button', $overlay).click(function(){
544                     var textAreaOpened = $('textarea', $overlay)[0];
545                     var startTag = "";
546                     var endTag = "";
547                     var buttonName = this.innerHTML;
548
549                     if(buttonName == "słowo obce") {
550                         startTag = "<slowo_obce>";
551                         endTag = "</slowo_obce>";
552                     } else if (buttonName == "wyróżnienie") {
553                         startTag = "<wyroznienie>";
554                         endTag = "</wyroznienie>";
555                     } else if (buttonName == "tytuł dzieła") {
556                         startTag = "<tytul_dziela>";
557                         endTag = "</tytul_dziela>";
558                     } else if(buttonName == "znak spec."){
559                         addSymbol();
560                         return false;
561                     }
562
563                     var myField = textAreaOpened;
564
565                     //IE support
566                     if (document.selection) {
567                         textAreaOpened.focus();
568                         sel = document.selection.createRange();
569                         sel.text = startTag + sel.text + endTag;
570                     }
571                     //MOZILLA/NETSCAPE support
572                     else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') {
573                         var startPos = textAreaOpened.selectionStart;
574                         var endPos = textAreaOpened.selectionEnd;
575                         textAreaOpened.value = textAreaOpened.value.substring(0, startPos)
576                             + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length);
577                     }
578                 });
579
580                 $('.accept-button', $overlay).click(function(){
581                     save();
582                     $(document).unbind('click.blur-overlay');
583                 });
584
585                 $(document).bind('click.blur-overlay', function(event){
586                     if ($(event.target).closest('.html-editarea, #specialCharsContainer').length > 0) {
587                         return;
588                     }
589                     save();
590                     $(document).unbind('click.blur-overlay');
591                 });
592
593             },
594             error: function(text){
595                 alert('Błąd! ' + text);
596             }
597         });
598     }
599
600     function createUwagaBefore(before) {
601         xml2html({
602             xml: '<uwaga/>',
603             success: function(element){
604                 let $element = $(element);
605                 $element.insertBefore(before);
606                 openForEdit($element);
607             }
608         });
609     }
610
611     class VisualPerspective extends $.wiki.Perspective {
612         constructor(options) {
613             super(options);
614             let self = this;
615             var element = $("#html-view");
616             var button = $('<button class="edit-button active-block-button">Edytuj</button>');
617             var uwagaButton = $('<button class="uwaga-button active-block-button">Uwaga</button>');
618
619             if (!CurrentDocument.readonly) {
620
621                 $('#html-view').bind('mousemove', function(event){
622                     var editable = $(event.target).closest('*[x-editable]');
623                     $('.active', element).not(editable).removeClass('active').children('.active-block-button').remove();
624
625                     if (!editable.hasClass('active')) {
626                         editable.addClass('active').append(button);
627                         if (!editable.is('[x-edit-attribute]') &&
628                             !editable.is('.annotation-inline-box') &&
629                             !editable.is('[x-edit-no-format]')
630                            ) {
631                             editable.append(uwagaButton);
632                         }
633                     }
634                     if (editable.is('.annotation-inline-box')) {
635                         $('*[x-annotation-box]', editable).css({
636                         }).show();
637                     }
638                 });
639
640                 self.caret = new Caret(element);
641
642                 $('#insert-reference-button').click(function(){
643                     self.flush();
644                     self.addReference();
645                     return false;
646                 });
647
648                 $('#insert-annotation-button').click(function(){
649                     self.flush();
650                     addAnnotation();
651                     return false;
652                 });
653
654                 $('#insert-theme-button').click(function(){
655                     self.flush();
656                     addTheme();
657                     return false;
658                 });
659
660                 $(".insert-inline-tag").click(function() {
661                     self.flush();
662                     self.insertInlineTag($(this).attr('data-tag'));
663                     return false;
664                 });
665
666                 $(".insert-char").click(function() {
667                     self.flush();
668                     addSymbol(caret=self.caret);
669                     return false;
670                 });
671
672                 $(document).on('click', '.edit-button', function(event){
673                     self.flush();
674                     event.preventDefault();
675                     openForEdit($(this).parent());
676                 });
677
678                 $(document).on('click', '.uwaga-button', function(event){
679                     self.flush();
680                     event.preventDefault();
681                     createUwagaBefore($(this).parent());
682                 });
683             }
684
685             $(document).on('click', '[x-node="motyw"]', function(){
686                 selectTheme($(this).attr('theme-class'));
687             });
688
689             element.on('click', '.annotation', function(event) {
690                 self.flush();
691                 event.preventDefault();
692                 event.redakcja_caret_ignore = true;
693                 $('[x-annotation-box]', $(this).parent()).toggleClass('editing');
694                 self.caret.detach();
695             });
696         }
697
698         onEnter(success, failure) {
699             super.onEnter();
700
701             $.blockUI({
702                 message: 'Uaktualnianie widoku...'
703             });
704
705             function _finalize(callback){
706                 $.unblockUI();
707                 if (callback)
708                     callback();
709             }
710
711             xml2html({
712                 xml: this.doc.text,
713                 base: this.doc.getBase(),
714                 success: function(element){
715
716                     var htmlView = $('#html-view');
717                     htmlView.html(element);
718                     if ('PropertiesPerspective' in $.wiki.perspectives)
719                         $.wiki.perspectives.PropertiesPerspective.enable();
720
721                     _finalize(success);
722                 },
723                 error: function(text, source){
724                     let err = '<p class="error">Wystąpił błąd:</p><p>'+text+'</p>';
725                     if (source)
726                         err += '<pre>'+source.replace(/&/g, '&amp;').replace(/</g, '&lt;')+'</pre>'
727                     $('#html-view').html(err);
728                     _finalize(failure);
729                 }
730             });
731         }
732
733         flush() {
734             let self = this;
735             return new Promise((resolve, reject) => {
736                 if ($('#html-view .error').length > 0) {
737                     reject()
738                 } else {
739                     //return _finalize(failure);
740                     html2text({
741                         element: $('#html-view').get(0),
742                         stripOuter: true,
743                         success: (text) => {
744                             self.doc.setText(text);
745                             resolve();
746                         },
747                         error: (text) => {
748                             reject(text);
749                             //$('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
750                         }
751                     });
752                 }
753             });
754         }
755
756         onExit(success, failure) {
757             var self = this;
758
759             self.caret.detach();
760
761             if ('PropertiesPerspective' in $.wiki.perspectives)
762                 $.wiki.perspectives.PropertiesPerspective.disable();
763
764             self.flush().then(() => {
765                 success && success();
766             }).catch((e) => {
767                 // TODO report
768                 console.log('REJECTED!', e);
769                 failure && failure();
770             });
771         };
772
773         insertInlineTag(tag) {
774             this.caret.detach();
775             let self = this;
776
777             let selection = window.getSelection();
778             var n = selection.rangeCount;
779             if (n != 1 || selection.isCollapsed) {
780                 window.alert("Nie zaznaczono obszaru");
781                 return false
782             }
783             let range = selection.getRangeAt(0);
784
785             // Make sure that:
786             // Both ends are in the same x-node container.
787             // Both ends are set to text nodes.
788             // TODO: That the container is a inline-text container.
789             let commonNode = range.endContainer;
790
791             if (commonNode.nodeType == Node.TEXT_NODE) {
792                 commonNode = commonNode.parentNode;
793             }
794             let node = range.startContainer;
795             if (node.nodeType == Node.TEXT_NODE) {
796                 node = node.parentNode;
797             }
798             if (node != commonNode) {
799                 window.alert("Zły obszar.");
800                 return false;
801             }
802
803             let end;
804             if (range.endContainer.nodeType == Node.TEXT_NODE) {
805                 end = range.endContainer.splitText(range.endOffset);
806             } else {
807                 end = document.createTextNode('');
808                 let cont = $(range.endContainer).contents();
809                 if (range.endOffset < cont.length) {
810                     range.endContainer.insertBefore(end, cont[range.endOffset])
811                 } else {
812                     range.endContainer.append(end);
813                 }
814             }
815
816             let current;
817             if (range.startContainer.nodeType == Node.TEXT_NODE) {
818                 current = range.startContainer.splitText(range.startOffset);
819             } else {
820                 current = document.createTextNode('');
821                 let cont = $(range.startContainer).contents();
822                 if (range.startOffset < cont.length) {
823                     range.startContainer.insertBefore(current, cont[range.startOffset])
824                 } else {
825                     startNode.append(current);
826                 }
827             }
828
829             // We will construct a HTML element with the range selected.
830             let div = $("<span x-pass-thru='true'>");
831             while (current != end) {
832                 n = current.nextSibling;
833                 $(current).appendTo(div);
834                 current = n;
835             }
836
837             html2text({
838                 element: div[0],
839                 success: function(d) {
840                     xml2html({
841                         xml: d = '<' + tag + '>' + d + '</' + tag + '>',
842                         success: function(html) {
843                             // What if no end?
844                             node.insertBefore($(html)[0], end);
845                             self.flush();
846                         }
847                     });
848                 },
849                 error: function(a, b) {
850                     console.log(a, b);
851                 }
852             });
853         }
854
855         insertAtRange(range, elem) {
856             let self = this;
857             let $end = $(range.endContainer);
858             if ($end.attr('id') == 'caret') {
859                 self.caret.insert(elem);
860             } else {
861                 range.insertNode(elem[0]);
862             }
863         }
864
865         addReference() {
866             let self = this;
867             var selection = window.getSelection();
868             var n = selection.rangeCount;
869
870             // TODO: if no selection, take caret position..
871             if (n == 0) {
872                 window.alert("Nie zaznaczono żadnego obszaru");
873                 return false;
874             }
875
876             var range = selection.getRangeAt(n - 1);
877             if (!verifyTagInsertPoint(range.endContainer)) {
878                 window.alert("Nie można wstawić w to miejsce referencji.");
879                 return false;
880             }
881
882             var tag = $('<span></span>');
883
884             range.collapse(false);
885             self.insertAtRange(range, tag);
886
887             xml2html({
888                 xml: '<ref href=""/>',
889                 success: function(text){
890                     var t = $(text);
891                     tag.replaceWith(t);
892                     openForEdit(t);
893                 },
894                 error: function(){
895                     tag.remove();
896                     alert('Błąd przy dodawaniu referncji:' + errors);
897                 }
898             })
899         }
900     }
901
902     $.wiki.VisualPerspective = VisualPerspective;
903
904 })(jQuery);