Added "delete" button to annotations. Fixes #554.
[redakcja.git] / 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 = $(".motyw[theme-class='" + themeId + "']")[0];
10         var e = $(".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.is('*[x-annotation-box] *'))
41             return false;
42
43         return true;
44     }
45
46     /* Convert HTML frament to plaintext */
47     var ANNOT_FORBIDDEN = ['pt', 'pa', 'pr', 'pe', 'begin', 'end', 'theme'];
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
95         var tag = $('<span></span>');
96         range.collapse(false);
97         range.insertNode(tag[0]);
98
99         xml2html({
100             xml: '<pr><slowo_obce>' + text + '</slowo_obce> --- </pr>',
101             success: function(text){
102                 var t = $(text);
103                 tag.replaceWith(t);
104                 openForEdit(t);
105             },
106             error: function(){
107                 tag.remove();
108                 alert('Błąd przy dodawaniu przypisu:' + errors);
109             }
110         })
111     }
112
113
114     /* Insert theme using current selection */
115
116     function addTheme(){
117         var selection = window.getSelection();
118         var n = selection.rangeCount;
119
120         if (n == 0) {
121             window.alert("Nie zaznaczono żadnego obszaru");
122             return false;
123         }
124
125         // for now allow only 1 range
126         if (n > 1) {
127             window.alert("Zaznacz jeden obszar.");
128             return false;
129         }
130
131
132         // remember the selected range
133         var range = selection.getRangeAt(0);
134
135
136         if ($(range.startContainer).is('.html-editarea') ||
137         $(range.endContainer).is('.html-editarea')) {
138             window.alert("Motywy można oznaczać tylko na tekście nie otwartym do edycji. \n Zamknij edytowany fragment i spróbuj ponownie.");
139             return false;
140         }
141
142         // verify if the start/end points make even sense -
143         // they must be inside a x-node (otherwise they will be discarded)
144         // and the x-node must be a main text
145         if (!verifyTagInsertPoint(range.startContainer)) {
146             window.alert("Motyw nie może się zaczynać w tym miejscu.");
147             return false;
148         }
149
150         if (!verifyTagInsertPoint(range.endContainer)) {
151             window.alert("Motyw nie może się kończyć w tym miejscu.");
152             return false;
153         }
154
155         var date = (new Date()).getTime();
156         var random = Math.floor(4000000000 * Math.random());
157         var id = ('' + date) + '-' + ('' + random);
158
159         var spoint = document.createRange();
160         var epoint = document.createRange();
161
162         spoint.setStart(range.startContainer, range.startOffset);
163         epoint.setStart(range.endContainer, range.endOffset);
164
165         var mtag, btag, etag, errors;
166
167         // insert theme-ref
168
169         xml2html({
170             xml: '<end id="e' + id + '" />',
171             success: function(text){
172                 etag = $('<span></span>');
173                 epoint.insertNode(etag[0]);
174                 etag.replaceWith(text);
175                 xml2html({
176                     xml: '<motyw id="m' + id + '"></motyw>',
177                     success: function(text){
178                         mtag = $('<span></span>');
179                         spoint.insertNode(mtag[0]);
180                         mtag.replaceWith(text);
181                         xml2html({
182                             xml: '<begin id="b' + id + '" />',
183                             success: function(text){
184                                 btag = $('<span></span>');
185                                 spoint.insertNode(btag[0])
186                                 btag.replaceWith(text);
187                                 selection.removeAllRanges();
188                                 openForEdit($('.motyw[theme-class=' + id + ']'));
189                             }
190                         });
191                     }
192                 });
193             }
194         });
195     }
196
197     /* open edition window for selected fragment */
198     function openForEdit($origin){
199         var $box = null
200
201         // annotations overlay their sub box - not their own box //
202         if ($origin.is(".annotation-inline-box")) {
203             $box = $("*[x-annotation-box]", $origin);
204         }
205         else {
206             $box = $origin;
207         }
208
209         var x = $box[0].offsetLeft;
210         var y = $box[0].offsetTop;
211         var w = $box.outerWidth();
212         var h = $box.innerHeight();
213
214         if ($origin.is(".annotation-inline-box")) {
215             w = Math.max(w, 400);
216             h = Math.max(h, 60);
217         }
218
219         // start edition on this node
220         var $overlay = $('<div class="html-editarea"><button class="accept-button">Zapisz</button><button class="delete-button">Usuń</button><textarea></textarea></div>').css({
221             position: 'absolute',
222             height: h,
223             left: x,
224             top: y,
225             width: w
226         }).appendTo($box[0].offsetParent || $box.parent()).show();
227
228         if ($origin.is('.motyw')) {
229             $('textarea', $overlay).autocomplete(THEMES, {
230                 autoFill: true,
231                 multiple: true,
232                 selectFirst: true
233             });
234         }
235
236         if ($origin.is('.motyw')){
237             $('.delete-button', $overlay).click(function(){
238                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten motyw ?")) {
239                     $('[theme-class=' + $origin.attr('theme-class') + ']').remove();
240                     $overlay.remove();
241                     $(document).unbind('click.blur-overlay');
242                     return false;
243                 };
244             });
245         }
246         else if($box.is('*[x-annotation-box]')) {
247             $('.delete-button', $overlay).click(function(){
248                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten przypis?")) {
249                     $origin.remove();
250                     $overlay.remove();
251                     $(document).unbind('click.blur-overlay');
252                     return false;
253                 };
254             });
255         }
256         else {
257             $('.delete-button', $overlay).hide();
258         }
259
260
261         var serializer = new XMLSerializer();
262
263         html2text({
264             element: $box[0],
265             stripOuter: true,
266             success: function(text){
267                 $('textarea', $overlay).val($.trim(text));
268
269                 setTimeout(function(){
270                     $('textarea', $overlay).elastic().focus();
271                 }, 50);
272
273                 function save(argument){
274                     var nodeName = $box.attr('x-node') || 'pe';
275                     var insertedText = $('textarea', $overlay).val();
276
277                     if ($origin.is('.motyw')) {
278                         insertedText = insertedText.replace(/,\s*$/, '');
279                     }
280
281                     xml2html({
282                         xml: '<' + nodeName + '>' + insertedText + '</' + nodeName + '>',
283                         success: function(element){
284                             $origin.html($(element).html());
285                             $overlay.remove();
286                         },
287                         error: function(text){
288                             $overlay.remove();
289                             alert('Błąd! ' + text);
290                         }
291                     })
292                 }
293
294                 $('.accept-button', $overlay).click(function(){
295                     save();
296                 });
297
298                 $(document).bind('click.blur-overlay', function(event){
299                     if ($(event.target).parents('.html-editarea').length > 0) {
300                         return;
301                     }
302                     save();
303
304                     $(document).unbind('click.blur-overlay');
305                 });
306
307             },
308             error: function(text){
309                 alert('Błąd! ' + text);
310             }
311         });
312     }
313
314     function VisualPerspective(options){
315
316         var old_callback = options.callback;
317
318         options.callback = function(){
319             var element = $("#html-view");
320             var button = $('<button class="edit-button">Edytuj</button>');
321
322             if (!CurrentDocument.readonly) {
323                 $('#html-view').bind('mousemove', function(event){
324                     var editable = $(event.target).closest('*[x-editable]');
325                     $('.active', element).not(editable).removeClass('active').children('.edit-button').remove();
326
327                     if (!editable.hasClass('active')) {
328                         editable.addClass('active').append(button);
329                     }
330                     if (editable.is('.annotation-inline-box')) {
331                         $('*[x-annotation-box]', editable).css({
332                             position: 'absolute',
333                             left: event.clientX - editable.offset().left + 5,
334                             top: event.clientY - editable.offset().top + 5
335                         }).show();
336                     }
337                     else {
338                         $('*[x-annotation-box]').hide();
339                     }
340                 });
341
342                 $('#insert-annotation-button').click(function(){
343                     addAnnotation();
344                     return false;
345                 });
346
347                 $('#insert-theme-button').click(function(){
348                     addTheme();
349                     return false;
350                 });
351
352                 $('.edit-button').live('click', function(event){
353                     event.preventDefault();
354                     openForEdit($(this).parent());
355                 });
356
357             }
358
359             $('.motyw').live('click', function(){
360                 selectTheme($(this).attr('theme-class'));
361             });
362
363             old_callback.call(this);
364         };
365
366         $.wiki.Perspective.call(this, options);
367     };
368
369     VisualPerspective.prototype = new $.wiki.Perspective();
370
371     VisualPerspective.prototype.freezeState = function(){
372
373     };
374
375     VisualPerspective.prototype.onEnter = function(success, failure){
376         $.wiki.Perspective.prototype.onEnter.call(this);
377
378         $.blockUI({
379             message: 'Uaktualnianie widoku...'
380         });
381
382         function _finalize(callback){
383             $.unblockUI();
384             if (callback)
385                 callback();
386         }
387
388         xml2html({
389             xml: this.doc.text,
390             success: function(element){
391                 $('#html-view').html(element);
392                 _finalize(success);
393             },
394             error: function(text){
395                 var message = $('<pre></pre>');
396                 message.text(text);
397                 $('#html-view').html('<p class="error">Wystąpił błąd:</p><pre>' +
398                 message.html() +
399                 '</pre>');
400                 _finalize(failure);
401             }
402         });
403     };
404
405     VisualPerspective.prototype.onExit = function(success, failure){
406         var self = this;
407
408         $.blockUI({
409             message: 'Zapisywanie widoku...'
410         });
411
412         function _finalize(callback){
413             $.unblockUI();
414             if (callback)
415                 callback();
416         }
417
418         if ($('#html-view .error').length > 0)
419             return _finalize(failure);
420
421         html2text({
422             element: $('#html-view div').get(0),
423             success: function(text){
424                 self.doc.setText(text);
425                 _finalize(success);
426             },
427             error: function(text){
428                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
429                 _finalize(failure);
430             }
431         });
432     };
433
434     $.wiki.VisualPerspective = VisualPerspective;
435
436 })(jQuery);