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