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());
530 error: function(text){
531 alert('Błąd! ' + text);
535 var msg = $("<div class='saveNotify'><p>Pamiętaj, żeby zapisać swoje zmiany.</p></div>");
536 $("#base").prepend(msg);
537 $('#base .saveNotify').fadeOut(3000, function(){
542 $('.akap-edit-button', $overlay).click(function(){
543 var textAreaOpened = $('textarea', $overlay)[0];
546 var buttonName = this.innerHTML;
548 if(buttonName == "słowo obce") {
549 startTag = "<slowo_obce>";
550 endTag = "</slowo_obce>";
551 } else if (buttonName == "wyróżnienie") {
552 startTag = "<wyroznienie>";
553 endTag = "</wyroznienie>";
554 } else if (buttonName == "tytuł dzieła") {
555 startTag = "<tytul_dziela>";
556 endTag = "</tytul_dziela>";
557 } else if(buttonName == "znak spec."){
562 var myField = textAreaOpened;
565 if (document.selection) {
566 textAreaOpened.focus();
567 sel = document.selection.createRange();
568 sel.text = startTag + sel.text + endTag;
570 //MOZILLA/NETSCAPE support
571 else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') {
572 var startPos = textAreaOpened.selectionStart;
573 var endPos = textAreaOpened.selectionEnd;
574 textAreaOpened.value = textAreaOpened.value.substring(0, startPos)
575 + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length);
579 $('.accept-button', $overlay).click(function(){
581 $(document).unbind('click.blur-overlay');
584 $(document).bind('click.blur-overlay', function(event){
585 if ($(event.target).closest('.html-editarea, #specialCharsContainer').length > 0) {
589 $(document).unbind('click.blur-overlay');
593 error: function(text){
594 alert('Błąd! ' + text);
599 function createUwagaBefore(before) {
602 success: function(element){
603 let $element = $(element);
604 $element.insertBefore(before);
605 openForEdit($element);
610 class VisualPerspective extends $.wiki.Perspective {
611 constructor(options) {
614 var element = $("#html-view");
615 var button = $('<button class="edit-button active-block-button">Edytuj</button>');
616 var uwagaButton = $('<button class="uwaga-button active-block-button">Uwaga</button>');
618 if (!CurrentDocument.readonly) {
620 $('#html-view').bind('mousemove', function(event){
621 var editable = $(event.target).closest('*[x-editable]');
622 $('.active', element).not(editable).removeClass('active').children('.active-block-button').remove();
624 if (!editable.hasClass('active')) {
625 editable.addClass('active').append(button);
626 if (!editable.is('[x-edit-attribute]') &&
627 !editable.is('.annotation-inline-box') &&
628 !editable.is('[x-edit-no-format]')
630 editable.append(uwagaButton);
633 if (editable.is('.annotation-inline-box')) {
634 $('*[x-annotation-box]', editable).css({
639 self.caret = new Caret(element);
641 $('#insert-reference-button').click(function(){
646 $('#insert-annotation-button').click(function(){
651 $('#insert-theme-button').click(function(){
656 $(".insert-inline-tag").click(function() {
657 self.insertInlineTag($(this).attr('data-tag'));
661 $(".insert-char").click(function() {
662 addSymbol(caret=self.caret);
666 $(document).on('click', '.edit-button', function(event){
667 event.preventDefault();
668 openForEdit($(this).parent());
671 $(document).on('click', '.uwaga-button', function(event){
672 event.preventDefault();
673 createUwagaBefore($(this).parent());
677 $(document).on('click', '[x-node="motyw"]', function(){
678 selectTheme($(this).attr('theme-class'));
681 element.on('click', '.annotation', function(event) {
682 event.preventDefault();
683 event.redakcja_caret_ignore = true;
684 $('[x-annotation-box]', $(this).parent()).toggleClass('editing');
689 onEnter(success, failure) {
693 message: 'Uaktualnianie widoku...'
696 function _finalize(callback){
704 base: this.doc.getBase(),
705 success: function(element){
707 var htmlView = $('#html-view');
708 htmlView.html(element);
712 error: function(text, source){
713 let err = '<p class="error">Wystąpił błąd:</p><p>'+text+'</p>';
715 err += '<pre>'+source.replace(/&/g, '&').replace(/</g, '<')+'</pre>'
716 $('#html-view').html(err);
722 onExit(success, failure) {
727 $.wiki.exitTab('#PropertiesPerspective');
730 message: 'Zapisywanie widoku...'
733 function _finalize(callback){
739 if ($('#html-view .error').length > 0)
740 return _finalize(failure);
743 element: $('#html-view').get(0),
745 success: function(text){
746 self.doc.setText(text);
749 error: function(text){
750 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
756 insertInlineTag(tag) {
759 let selection = window.getSelection();
760 var n = selection.rangeCount;
761 if (n != 1 || selection.isCollapsed) {
762 window.alert("Nie zaznaczono obszaru");
765 let range = selection.getRangeAt(0);
768 // Both ends are in the same x-node container.
769 // Both ends are set to text nodes.
770 // TODO: That the container is a inline-text container.
771 let commonNode = range.endContainer;
773 if (commonNode.nodeType == Node.TEXT_NODE) {
774 commonNode = commonNode.parentNode;
776 let node = range.startContainer;
777 if (node.nodeType == Node.TEXT_NODE) {
778 node = node.parentNode;
780 if (node != commonNode) {
781 window.alert("Zły obszar.");
786 if (range.endContainer.nodeType == Node.TEXT_NODE) {
787 end = range.endContainer.splitText(range.endOffset);
789 end = document.createTextNode('');
790 let cont = $(range.endContainer).contents();
791 if (range.endOffset < cont.length) {
792 range.endContainer.insertBefore(end, cont[range.endOffset])
794 range.endContainer.append(end);
799 if (range.startContainer.nodeType == Node.TEXT_NODE) {
800 current = range.startContainer.splitText(range.startOffset);
802 current = document.createTextNode('');
803 let cont = $(range.startContainer).contents();
804 if (range.startOffset < cont.length) {
805 range.startContainer.insertBefore(current, cont[range.startOffset])
807 startNode.append(current);
811 // We will construct a HTML element with the range selected.
812 let div = $("<span x-pass-thru='true'>");
813 while (current != end) {
814 n = current.nextSibling;
815 $(current).appendTo(div);
821 success: function(d) {
823 xml: d = '<' + tag + '>' + d + '</' + tag + '>',
824 success: function(html) {
826 node.insertBefore($(html)[0], end);
830 error: function(a, b) {
836 insertAtRange(range, elem) {
838 let $end = $(range.endContainer);
839 if ($end.attr('id') == 'caret') {
840 self.caret.insert(elem);
842 range.insertNode(elem[0]);
848 var selection = window.getSelection();
849 var n = selection.rangeCount;
851 // TODO: if no selection, take caret position..
853 window.alert("Nie zaznaczono żadnego obszaru");
857 var range = selection.getRangeAt(n - 1);
858 if (!verifyTagInsertPoint(range.endContainer)) {
859 window.alert("Nie można wstawić w to miejsce referencji.");
863 var tag = $('<span></span>');
865 range.collapse(false);
866 self.insertAtRange(range, tag);
869 xml: '<ref href=""/>',
870 success: function(text){
877 alert('Błąd przy dodawaniu referncji:' + errors);
883 $.wiki.VisualPerspective = VisualPerspective;