Merge branch 'master' of git@github.com:fnp/redakcja
[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 fragment 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: '<pe><slowo_obce>' + text + '</slowo_obce> --- </pe>',
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                 highlight: false
234             });
235         }
236
237         if ($origin.is('.motyw')){
238             $('.delete-button', $overlay).click(function(){
239                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten motyw ?")) {
240                     $('[theme-class=' + $origin.attr('theme-class') + ']').remove();
241                     $overlay.remove();
242                     $(document).unbind('click.blur-overlay');
243                     return false;
244                 };
245             });
246         }
247         else if($box.is('*[x-annotation-box]')) {
248             $('.delete-button', $overlay).click(function(){
249                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten przypis?")) {
250                     $origin.remove();
251                     $overlay.remove();
252                     $(document).unbind('click.blur-overlay');
253                     return false;
254                 };
255             });
256         }
257         else {
258             $('.delete-button', $overlay).hide();
259         }
260
261
262         var serializer = new XMLSerializer();
263
264         html2text({
265             element: $box[0],
266             stripOuter: true,
267             success: function(text){
268                 $('textarea', $overlay).val($.trim(text));
269
270                 setTimeout(function(){
271                     $('textarea', $overlay).elastic().focus();
272                 }, 50);
273
274                 function save(argument){
275                     var nodeName = $box.attr('x-node') || 'pe';
276                     var insertedText = $('textarea', $overlay).val();
277
278                     if ($origin.is('.motyw')) {
279                         insertedText = insertedText.replace(/,\s*$/, '');
280                     }
281
282                     xml2html({
283                         xml: '<' + nodeName + '>' + insertedText + '</' + nodeName + '>',
284                         success: function(element){
285                             $origin.html($(element).html());
286                             $overlay.remove();
287                         },
288                         error: function(text){
289                             $overlay.remove();
290                             alert('Błąd! ' + text);
291                         }
292                     })
293                 }
294
295                 $('.accept-button', $overlay).click(function(){
296                     save();
297                 });
298
299                 $(document).bind('click.blur-overlay', function(event){
300                     if ($(event.target).parents('.html-editarea').length > 0) {
301                         return;
302                     }
303                     save();
304
305                     $(document).unbind('click.blur-overlay');
306                 });
307
308             },
309             error: function(text){
310                 alert('Błąd! ' + text);
311             }
312         });
313     }
314
315     function VisualPerspective(options){
316
317         var old_callback = options.callback;
318
319         options.callback = function(){
320             var element = $("#html-view");
321             var button = $('<button class="edit-button">Edytuj</button>');
322
323             if (!CurrentDocument.readonly) {
324                 $('#html-view').bind('mousemove', function(event){
325                     var editable = $(event.target).closest('*[x-editable]');
326                     $('.active', element).not(editable).removeClass('active').children('.edit-button').remove();
327
328                     if (!editable.hasClass('active')) {
329                         editable.addClass('active').append(button);
330                     }
331                     if (editable.is('.annotation-inline-box')) {
332                         $('*[x-annotation-box]', editable).css({
333                             position: 'absolute',
334                             left: event.clientX - editable.offset().left + 5,
335                             top: event.clientY - editable.offset().top + 5
336                         }).show();
337                     }
338                     else {
339                         $('*[x-annotation-box]').hide();
340                     }
341                 });
342
343                 $('#insert-annotation-button').click(function(){
344                     addAnnotation();
345                     return false;
346                 });
347
348                 $('#insert-theme-button').click(function(){
349                     addTheme();
350                     return false;
351                 });
352
353                 $('.edit-button').live('click', function(event){
354                     event.preventDefault();
355                     openForEdit($(this).parent());
356                 });
357
358             }
359
360             $('.motyw').live('click', function(){
361                 selectTheme($(this).attr('theme-class'));
362             });
363
364             old_callback.call(this);
365         };
366
367         $.wiki.Perspective.call(this, options);
368     };
369
370     VisualPerspective.prototype = new $.wiki.Perspective();
371
372     VisualPerspective.prototype.freezeState = function(){
373
374     };
375
376     VisualPerspective.prototype.onEnter = function(success, failure){
377         $.wiki.Perspective.prototype.onEnter.call(this);
378
379         $.blockUI({
380             message: 'Uaktualnianie widoku...'
381         });
382
383         function _finalize(callback){
384             $.unblockUI();
385             if (callback)
386                 callback();
387         }
388
389         xml2html({
390             xml: this.doc.text,
391             success: function(element){
392                 $('#html-view').html(element);
393                 _finalize(success);
394             },
395             error: function(text){
396                 var message = $('<pre></pre>');
397                 message.text(text);
398                 $('#html-view').html('<p class="error">Wystąpił błąd:</p><pre>' +
399                 message.html() +
400                 '</pre>');
401                 _finalize(failure);
402             }
403         });
404     };
405
406     VisualPerspective.prototype.onExit = function(success, failure){
407         var self = this;
408
409         $.blockUI({
410             message: 'Zapisywanie widoku...'
411         });
412
413         function _finalize(callback){
414             $.unblockUI();
415             if (callback)
416                 callback();
417         }
418
419         if ($('#html-view .error').length > 0)
420             return _finalize(failure);
421
422         html2text({
423             element: $('#html-view div').get(0),
424             success: function(text){
425                 self.doc.setText(text);
426                 _finalize(success);
427             },
428             error: function(text){
429                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
430                 _finalize(failure);
431             }
432         });
433     };
434
435     $.wiki.VisualPerspective = VisualPerspective;
436
437 })(jQuery);