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