* Readonly document view.
[redakcja.git] / platforma / 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_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             if (!CurrentDocument.readonly) {
312                 $('#html-view').bind('mousemove', function(event){
313                     var editable = $(event.target).closest('*[x-editable]');
314                     $('.active', element).not(editable).removeClass('active').children('.edit-button').remove();
315
316                     if (!editable.hasClass('active')) {
317                         editable.addClass('active').append(button);
318                     }
319                     if (editable.is('.annotation-inline-box')) {
320                         $('*[x-annotation-box]', editable).css({
321                             position: 'absolute',
322                             left: event.clientX - editable.offset().left + 5,
323                             top: event.clientY - editable.offset().top + 5
324                         }).show();
325                     }
326                     else {
327                         $('*[x-annotation-box]').hide();
328                     }
329                 });
330
331                 $('#insert-annotation-button').click(function(){
332                     addAnnotation();
333                     return false;
334                 });
335
336                 $('#insert-theme-button').click(function(){
337                     addTheme();
338                     return false;
339                 });
340
341                 $('.edit-button').live('click', function(event){
342                     event.preventDefault();
343                     openForEdit($(this).parent());
344                 });
345
346             }
347
348             $('.motyw').live('click', function(){
349                 selectTheme($(this).attr('theme-class'));
350             });
351
352             old_callback.call(this);
353         };
354
355         $.wiki.Perspective.call(this, options);
356     };
357
358     VisualPerspective.prototype = new $.wiki.Perspective();
359
360     VisualPerspective.prototype.freezeState = function(){
361
362     };
363
364     VisualPerspective.prototype.onEnter = function(success, failure){
365         $.wiki.Perspective.prototype.onEnter.call(this);
366
367         $.blockUI({
368             message: 'Uaktualnianie widoku...'
369         });
370
371         function _finalize(callback){
372             $.unblockUI();
373             if (callback)
374                 callback();
375         }
376
377         xml2html({
378             xml: this.doc.text,
379             success: function(element){
380                 $('#html-view').html(element);
381                 _finalize(success);
382             },
383             error: function(text){
384                 var message = $('<pre></pre>');
385                 message.text(text);
386                 $('#html-view').html('<p class="error">Wystąpił błąd:</p><pre>' +
387                 message.html() +
388                 '</pre>');
389                 _finalize(failure);
390             }
391         });
392     };
393
394     VisualPerspective.prototype.onExit = function(success, failure){
395         var self = this;
396
397         $.blockUI({
398             message: 'Zapisywanie widoku...'
399         });
400
401         function _finalize(callback){
402             $.unblockUI();
403             if (callback)
404                 callback();
405         }
406
407         if ($('#html-view .error').length > 0)
408             return _finalize(failure);
409
410         html2text({
411             element: $('#html-view div').get(0),
412             success: function(text){
413                 self.doc.setText(text);
414                 _finalize(success);
415             },
416             error: function(text){
417                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
418                 _finalize(failure);
419             }
420         });
421     };
422
423     $.wiki.VisualPerspective = VisualPerspective;
424
425 })(jQuery);