3 /* Show theme to the user */
4 function selectTheme(themeId){
5 var selection = window.getSelection();
6 selection.removeAllRanges();
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];
13 range.setStartAfter(s);
14 range.setEndBefore(e);
15 selection.addRange(range);
19 /* Verify insertion port for annotation or theme */
20 function verifyTagInsertPoint(node){
21 if (node.nodeType == Node.TEXT_NODE) {
22 node = node.parentNode;
25 if (node.nodeType != Node.ELEMENT_NODE) {
30 if (node.attr('id') == 'caret') {
33 while (node.attr('x-pass-thru')) {
36 var xtype = node.attr('x-node');
38 if (!xtype || (xtype.search(':') >= 0) ||
48 function verifyThemeBoundaryPoint(node) {
49 if (!verifyTagInsertPoint(node)) return false;
51 // don't allow themes inside annotations
52 if (node.closest('[x-node="pe"]').length > 0)
58 /* Convert HTML fragment to plaintext */
59 var ANNOT_FORBIDDEN = ['pt', 'pa', 'pr', 'pe', 'begin', 'end', 'motyw'];
61 function html2plainText(fragment){
64 $(fragment.childNodes).each(function(){
65 if (this.nodeType == Node.TEXT_NODE)
66 text += this.nodeValue;
68 if (this.nodeType == Node.ELEMENT_NODE &&
69 $.inArray($(this).attr('x-node'), ANNOT_FORBIDDEN) == -1) {
70 text += html2plainText(this);
79 /* Insert annotation using current selection */
80 function addAnnotation(){
81 var selection = window.getSelection();
82 var n = selection.rangeCount;
84 if (selection.isCollapsed) {
85 window.alert("Nie zaznaczono żadnego obszaru");
89 var range = selection.getRangeAt(n - 1);
91 if (!verifyTagInsertPoint(range.endContainer)) {
92 window.alert("Nie można wstawić w to miejsce przypisu.");
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());
104 var tag = $('<span></span>');
105 range.collapse(false);
106 range.insertNode(tag[0]);
109 xml: '<pe><slowo_obce>' + text + '</slowo_obce> --- </pe>',
110 success: function(text){
117 alert('Błąd przy dodawaniu przypisu:' + errors);
124 /* Insert theme using current selection */
127 var selection = window.getSelection();
128 var n = selection.rangeCount;
131 window.alert("Nie zaznaczono żadnego obszaru");
135 // for now allow only 1 range
137 window.alert("Zaznacz jeden obszar.");
141 // remember the selected range
142 var range = selection.getRangeAt(0);
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.");
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.");
158 if (!verifyThemeBoundaryPoint(range.endContainer)) {
159 window.alert("Motyw nie może się kończyć w tym miejscu.");
163 var date = (new Date()).getTime();
164 var random = Math.floor(4000000000 * Math.random());
165 var id = ('' + date) + '-' + ('' + random);
167 var createPoint = function(container, offset) {
168 var offsetBetweenCommas = function(text, offset) {
169 if(text.length < 2 || offset < 1 || offset > text.length)
171 return text[offset-1] === ',' && text[offset] === ',';
173 var point = document.createRange();
174 offset = offsetBetweenCommas(container.textContent, offset) ? offset - 1 : offset;
175 point.setStart(container, offset);
179 var spoint = createPoint(range.startContainer, range.startOffset);
180 var epoint = createPoint(range.endContainer, range.endOffset);
182 var mtag, btag, etag, errors;
187 xml: '<end id="e' + id + '" />',
188 success: function(text){
189 etag = $('<span></span>');
190 epoint.insertNode(etag[0]);
191 etag.replaceWith(text);
193 xml: '<motyw id="m' + id + '"></motyw>',
194 success: function(text){
195 mtag = $('<span></span>');
196 spoint.insertNode(mtag[0]);
197 mtag.replaceWith(text);
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 + '"]'));
214 function addSymbol(caret) {
218 editArea = $("textarea", caret.element)[0];
220 editArea = $('div.html-editarea textarea')[0];
224 var specialCharsContainer = $("<div id='specialCharsContainer'><a href='#' id='specialCharsClose'>Zamknij</a><table id='tableSpecialChars' style='width: 600px;'></table></div>");
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>";
251 for(var i in specialChars) {
252 if(i % 14 == 0 && i > 0) {
253 tableContent += "</tr><tr>";
255 tableContent += "<td><input type='button' class='specialBtn' value='"+specialChars[i]+"'/></td>";
258 tableContent += "</tr>";
259 $("body").append(specialCharsContainer);
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(";");
268 for(var i in recentArray.reverse()) {
269 recentRow += "<td><input type='button' class='specialBtn recentSymbol' value='"+recentArray[i]+"'/></td>";
271 recentRow = "<tr>" + recentRow + "</tr>";
274 $("#tableSpecialChars").append(recentRow);
275 $("#tableSpecialChars").append(tableContent);
279 $('.specialBtn').click(function(){
280 var insertVal = $(this).val();
282 // if we want to surround text with quotes
283 // not sure if just check if value has length == 2
286 caret.insertChar(insertVal);
289 if (insertVal.length == 2) {
290 var startTag = insertVal[0];
291 var endTag = insertVal[1];
292 var textAreaOpened = editArea;
294 if (document.selection) {
295 textAreaOpened.focus();
296 sel = document.selection.createRange();
297 sel.text = startTag + sel.text + endTag;
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);
307 insertAtCaret(editArea, insertVal);
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);
319 // value not present in array yet
320 if(recentArray.length > 13){
322 recentArray.push(insertVal);
324 recentArray.push(insertVal);
327 // value already in the array
328 for(var i = valIndex; i < recentArray.length; i++){
329 recentArray[i] = recentArray[i+1];
331 recentArray[recentArray.length-1] = insertVal;
333 localStorage.setItem("recentSymbols", recentArray.join(";"));
335 localStorage.setItem("recentSymbols", insertVal);
338 $(specialCharsContainer).remove();
340 $('#specialCharsClose').click(function(){
341 $(specialCharsContainer).remove();
345 window.alert('Najedź na fragment tekstu, wybierz "Edytuj" i ustaw kursor na miejscu gdzie chcesz wstawić symbol.');
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;
354 var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
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;
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;
370 var range = document.selection.createRange();
371 range.moveStart ('character', -txtarea.value.length);
372 range.moveStart ('character', strPos);
373 range.moveEnd ('character', 0);
375 } else if (br == "ff") {
376 txtarea.selectionStart = strPos;
377 txtarea.selectionEnd = strPos;
380 txtarea.scrollTop = scrollPos;
383 /* open edition window for selected fragment */
384 function openForEdit($origin){
387 // annotations overlay their sub box - not their own box //
388 if ($origin.is(".annotation-inline-box")) {
389 $box = $("*[x-annotation-box]", $origin);
394 var x = $box[0].offsetLeft;
395 var y = $box[0].offsetTop;
397 var w = $box.outerWidth();
398 var h = $box.innerHeight();
400 if ($origin.is(".annotation-inline-box")) {
401 w = Math.max(w, 400);
403 if($('.htmlview div').offset().left + $('.htmlview div').width() > ($('.vsplitbar').offset().left - 480)){
404 x = -(Math.max($origin.offset().left, $origin.width()));
409 if ($origin.is('.reference-inline-box')) {
415 $('.htmlview div').offset().left + $('.htmlview div').width() - 400
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',
426 }).appendTo($box[0].offsetParent || $box.parent()).show();
429 if ($origin.is('*[x-edit-no-format]')) {
430 $('.akap-edit-button').remove();
433 if ($origin.is('[x-node="motyw"]')) {
434 $.themes.autocomplete($('textarea', $overlay));
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();
442 $(document).unbind('click.blur-overlay');
447 else if($box.is('*[x-annotation-box]') || $origin.is('*[x-edit-attribute]') || $origin.is('*[x-node="uwaga"]')) {
449 switch ($origin.attr('x-node')) {
459 $('.delete-button', $overlay).click(function(){
460 if (window.confirm("Czy jesteś pewien, że chcesz usunąć " + q + "?")) {
463 $(document).unbind('click.blur-overlay');
469 $('.delete-button', $overlay).html("Anuluj");
470 $('.delete-button', $overlay).click(function(){
471 if (window.confirm("Czy jesteś pewien, że chcesz anulować zmiany?")) {
473 $(document).unbind('click.blur-overlay');
480 var serializer = new XMLSerializer();
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")));
493 success: function(text){
494 $('textarea', $overlay).val($.trim(text));
496 setTimeout(function(){
497 $('textarea', $overlay).elastic().focus();
500 function save(argument){
501 var nodeName = $box.attr('x-node') || 'pe';
502 var insertedText = $('textarea', $overlay).val();
504 if ($origin.is('[x-node="motyw"]')) {
505 insertedText = insertedText.replace(/,\s*$/, '');
508 if($box.attr("x-edit-attribute")) {
509 xml = '<' + nodeName + ' ' + $box.attr("x-edit-attribute") + '="' + insertedText + '"/>';
511 xml = '<' + nodeName + '>' + insertedText + '</' + nodeName + '>';
516 success: function(element){
517 if (nodeName == 'out-of-flow-text') {
518 $(element).children().insertAfter($origin);
521 else if ($box.attr('x-edit-attribute')) {
522 $(element).insertAfter($origin);
526 $origin.html($(element).html());
529 $.wiki.activePerspective().flush();
531 error: function(text){
532 alert('Błąd! ' + text);
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(){
543 $('.akap-edit-button', $overlay).click(function(){
544 var textAreaOpened = $('textarea', $overlay)[0];
547 var buttonName = this.innerHTML;
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."){
563 var myField = textAreaOpened;
566 if (document.selection) {
567 textAreaOpened.focus();
568 sel = document.selection.createRange();
569 sel.text = startTag + sel.text + endTag;
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);
580 $('.accept-button', $overlay).click(function(){
582 $(document).unbind('click.blur-overlay');
585 $(document).bind('click.blur-overlay', function(event){
586 if ($(event.target).closest('.html-editarea, #specialCharsContainer').length > 0) {
590 $(document).unbind('click.blur-overlay');
594 error: function(text){
595 alert('Błąd! ' + text);
600 function createUwagaBefore(before) {
603 success: function(element){
604 let $element = $(element);
605 $element.insertBefore(before);
606 openForEdit($element);
611 class VisualPerspective extends $.wiki.Perspective {
612 constructor(options) {
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>');
619 if (!CurrentDocument.readonly) {
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();
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]')
631 editable.append(uwagaButton);
634 if (editable.is('.annotation-inline-box')) {
635 $('*[x-annotation-box]', editable).css({
640 self.caret = new Caret(element);
642 $('#insert-reference-button').click(function(){
648 $('#insert-annotation-button').click(function(){
654 $('#insert-theme-button').click(function(){
660 $(".insert-inline-tag").click(function() {
662 self.insertInlineTag($(this).attr('data-tag'));
666 $(".insert-char").click(function() {
668 addSymbol(caret=self.caret);
672 $(document).on('click', '.edit-button', function(event){
674 event.preventDefault();
675 openForEdit($(this).parent());
678 $(document).on('click', '.uwaga-button', function(event){
680 event.preventDefault();
681 createUwagaBefore($(this).parent());
685 $(document).on('click', '[x-node="motyw"]', function(){
686 selectTheme($(this).attr('theme-class'));
689 element.on('click', '.annotation', function(event) {
691 event.preventDefault();
692 event.redakcja_caret_ignore = true;
693 $('[x-annotation-box]', $(this).parent()).toggleClass('editing');
698 onEnter(success, failure) {
702 message: 'Uaktualnianie widoku...'
705 function _finalize(callback){
713 base: this.doc.getBase(),
714 success: function(element){
716 var htmlView = $('#html-view');
717 htmlView.html(element);
718 if ('PropertiesPerspective' in $.wiki.perspectives)
719 $.wiki.perspectives.PropertiesPerspective.enable();
723 error: function(text, source){
724 let err = '<p class="error">Wystąpił błąd:</p><p>'+text+'</p>';
726 err += '<pre>'+source.replace(/&/g, '&').replace(/</g, '<')+'</pre>'
727 $('#html-view').html(err);
735 return new Promise((resolve, reject) => {
736 if ($('#html-view .error').length > 0) {
739 //return _finalize(failure);
741 element: $('#html-view').get(0),
744 self.doc.setText(text);
749 //$('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
756 onExit(success, failure) {
761 if ('PropertiesPerspective' in $.wiki.perspectives)
762 $.wiki.perspectives.PropertiesPerspective.disable();
764 self.flush().then(() => {
765 success && success();
768 console.log('REJECTED!', e);
769 failure && failure();
773 insertInlineTag(tag) {
777 let selection = window.getSelection();
778 var n = selection.rangeCount;
779 if (n != 1 || selection.isCollapsed) {
780 window.alert("Nie zaznaczono obszaru");
783 let range = selection.getRangeAt(0);
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;
791 if (commonNode.nodeType == Node.TEXT_NODE) {
792 commonNode = commonNode.parentNode;
794 let node = range.startContainer;
795 if (node.nodeType == Node.TEXT_NODE) {
796 node = node.parentNode;
798 if (node != commonNode) {
799 window.alert("Zły obszar.");
804 if (range.endContainer.nodeType == Node.TEXT_NODE) {
805 end = range.endContainer.splitText(range.endOffset);
807 end = document.createTextNode('');
808 let cont = $(range.endContainer).contents();
809 if (range.endOffset < cont.length) {
810 range.endContainer.insertBefore(end, cont[range.endOffset])
812 range.endContainer.append(end);
817 if (range.startContainer.nodeType == Node.TEXT_NODE) {
818 current = range.startContainer.splitText(range.startOffset);
820 current = document.createTextNode('');
821 let cont = $(range.startContainer).contents();
822 if (range.startOffset < cont.length) {
823 range.startContainer.insertBefore(current, cont[range.startOffset])
825 startNode.append(current);
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);
839 success: function(d) {
841 xml: d = '<' + tag + '>' + d + '</' + tag + '>',
842 success: function(html) {
844 node.insertBefore($(html)[0], end);
849 error: function(a, b) {
855 insertAtRange(range, elem) {
857 let $end = $(range.endContainer);
858 if ($end.attr('id') == 'caret') {
859 self.caret.insert(elem);
861 range.insertNode(elem[0]);
867 var selection = window.getSelection();
868 var n = selection.rangeCount;
870 // TODO: if no selection, take caret position..
872 window.alert("Nie zaznaczono żadnego obszaru");
876 var range = selection.getRangeAt(n - 1);
877 if (!verifyTagInsertPoint(range.endContainer)) {
878 window.alert("Nie można wstawić w to miejsce referencji.");
882 var tag = $('<span></span>');
884 range.collapse(false);
885 self.insertAtRange(range, tag);
888 xml: '<ref href=""/>',
889 success: function(text){
896 alert('Błąd przy dodawaniu referncji:' + errors);
902 $.wiki.VisualPerspective = VisualPerspective;