97db6f07ff36ef7e9fd5cc5d946306aee0dfeaf8
[redakcja.git] / platforma / static / js / views / html.js
1 /*global View render_template panels */
2 var HTMLView = View.extend({
3     _className: 'HTMLView',
4     element: null,
5     model: null,
6     template: 'html-view-template',
7   
8     init: function(element, model, parent, template) {
9         this._super(element, model, template);
10         this.parent = parent;
11     
12         this.model
13         .addObserver(this, 'data', this.modelDataChanged.bind(this))        
14         .addObserver(this, 'state', this.modelStateChanged.bind(this));
15
16
17         this.$menuTemplate = $(render_template('html-view-frag-menu-template', this));
18         this.modelStateChanged('state', this.model.get('state'));
19         this.modelDataChanged('data', this.model.get('data'));
20                 
21         this.model.load();
22
23         this.currentOpen = null;
24         this.currentFocused = null;
25         this.themeBoxes = [];
26     },
27
28     modelDataChanged: function(property, value) {
29         $('.htmlview', this.element).html(value);
30         this.updatePrintLink();
31         var self = this;
32
33         /* upgrade editable elements */
34         $("*[x-editable]").each(function() {
35             $(this).append( self.$menuTemplate.clone() );
36         });        
37
38         var doc_base = $('.htmlview .utwor', this.element);
39
40         /* mark themes */
41         $(".theme-ref").each(function() {
42             var id = $(this).attr('x-theme-class');
43
44             var end = $("span.theme-end[x-theme-class = " + id+"]");
45             var begin = $("span.theme-begin[x-theme-class = " + id+"]");
46
47             var h = $(this).outerHeight();
48
49             h = Math.max(h, end.offset().top - begin.offset().top);
50             $(this).css('height', h);
51         }); 
52     },
53
54     updatePrintLink: function() {
55         var base = this.$printLink.attr('ui:baseref');
56         this.$printLink.attr('href', base + "?user="+this.model.document.get('user')+"&revision=" + this.model.get('revision'));
57     },
58   
59     modelStateChanged: function(property, value) 
60     {
61         var self = $(this);
62
63         if (value == 'synced' || value == 'dirty') {
64             this.unfreeze();
65         } else if (value == 'unsynced') {
66             if(this.currentOpen) this.closeWithoutSave(this.currentOpen);
67             this.freeze('Niezsynchronizowany...');
68         } else if (value == 'loading') {
69             this.freeze('Ɓadowanie...');
70         } else if (value == 'saving') {
71             this.freeze('Zapisywanie...');
72         } else if (value == 'error') {
73             this.freeze(this.model.get('error'));
74             $('.xml-editor-ref', this.overlay).click(
75             function(event) {
76                 console.log("Sending scroll rq.", this);
77                 try {
78                     var href = $(this).attr('href').split('-');
79                     var line = parseInt(href[1]);
80                     var column = parseInt(href[2]);
81                     
82                     $(document).trigger('xml-scroll-request', {line:line, column:column});
83                 } catch(e) {
84                     console.log(e);
85                 }
86                 
87                 return false;
88             });
89         }
90     },
91
92     render: function() {
93         this.element.unbind('click');
94
95         if(this.$printLink) this.$printLink.unbind();
96         this._super();
97         this.$printLink = $('.html-print-link', this.element);
98         this.updatePrintLink();
99
100         this.element.bind('click', this.itemClicked.bind(this));
101         // this.element.bind('mouseover', this.itemHover.bind(this));
102     },
103   
104     reload: function() {
105         this.model.load(true);
106     },
107   
108     dispose: function() {
109         this.model.removeObserver(this);
110         this._super();
111     },
112
113     itemClicked: function(event) 
114     {
115         var self = this;
116         
117         console.log('click:', event, event.ctrlKey, event.target);        
118         var $e = $(event.target);
119
120         if($e.hasClass('annotation'))
121         {
122             if(this.currentOpen) return false;
123             
124             var $p = $e.parent();
125             if(this.currentFocused) 
126             {
127                 console.log(this.currentFocused, $p);
128                 if($p[0] == this.currentFocused[0]) {
129                     console.log('unfocus of current');
130                     this.unfocusAnnotation();
131                     return false;
132                 }
133
134                 console.log('switch unfocus');
135                 this.unfocusAnnotation();                
136             }
137
138             this.focusAnnotation($p);
139             return false;
140         }
141
142         /*
143          * Clicking outside of focused area doesn't unfocus by default
144          *  - this greatly simplifies the whole click check
145          */
146
147         /* other buttons */
148         if($e.hasClass('edit-button'))
149             this.openForEdit( this.editableFor($e) );
150
151         if($e.hasClass('accept-button'))
152             this.closeWithSave( this.editableFor($e) );
153
154         if($e.hasClass('reject-button'))
155             this.closeWithoutSave( this.editableFor($e) );        
156     },
157
158     unfocusAnnotation: function()
159     {
160         if(!this.currentFocused)
161         {
162             console.log('Redundant unfocus');
163             return false;
164         }
165
166         if(this.currentOpen 
167           && this.currentOpen.is("*[x-annotation-box]")
168           && this.currentOpen.parent()[0] == this.currentFocused[0])
169         {
170             console.log("Can't unfocus open box");
171             return false;
172         }
173
174         var $box = $("*[x-annotation-box]", this.currentFocused);
175         $box.css({'display': 'none'});
176         // this.currentFocused.removeAttr('x-focused');
177         // this.currentFocused.hide();
178         this.currentFocused = null;
179     },
180
181     focusAnnotation: function($e) {
182         this.currentFocused = $e;
183         var $box = $("*[x-annotation-box]", $e);
184         $box.css({'display': 'block'});
185         
186         // $e.attr('x-focused', 'focused');        
187     },
188
189     closeWithSave: function($e) {
190         var $edit = $e.data('edit-overlay');
191         var newText = $('textarea', $edit).val();
192
193         this.model.putXMLPart($e, newText, function($e, html) {
194             this.renderPart($e, html);
195             $edit.remove();
196             $e.removeAttr('x-open');            
197         }.bind(this) );
198         this.currentOpen = null;
199     },
200
201     closeWithoutSave: function($e) {
202         var $edit = $e.data('edit-overlay');
203         $edit.remove();
204         $e.removeAttr('x-open');
205         this.currentOpen = null;
206     },
207
208     renderPart: function($e, html) {
209         // exceptions aren't good, but I don't have a better idea right now
210         if($e.attr('x-annotation-box')) {
211             // replace the whole annotation
212             var $p = $e.parent();
213             $p.html(html);
214             var $box = $('*[x-annotation-box]', $p);
215             $box.append( this.$menuTemplate.clone() );
216             
217             if(this.currentFocused && $p[0] == this.currentFocused[0])
218             {                
219                 this.currentFocused = $p;
220                 $box.css({'display': 'block'});
221             }
222             
223             return;
224         }
225
226         $e.html(html);
227         $e.append( this.$menuTemplate.clone() );
228     },
229
230     editableFor: function($button) 
231     {
232         var $e = $button;
233         var n = 0;
234         
235         while( ($e[0] != this.element[0]) && !($e.attr('x-editable')) && n < 50)
236         {
237             // console.log($e, $e.parent(), this.element);
238             $e = $e.parent();
239             n += 1;
240         }
241
242         if(!$e.attr('x-editable'))
243             throw Exception("Click outside of editable")
244
245         console.log("Trigger", $button, " yields editable: ", $e);
246         return $e;
247     },
248
249     openForEdit: function($origin)
250     {       
251         if(this.currentOpen && this.currentOpen != $origin) {
252             this.closeWithSave(this.currentOpen);    
253         }
254         
255         var x = $origin[0].offsetLeft;
256         var y = $origin[0].offsetTop;
257         var w = $origin.outerWidth();
258         var h = $origin.innerHeight();
259
260         console.log("Editable:", $origin, " offsetParent:", $origin[0].offsetParent);
261         console.log("Dimensions: ", x, y, w , h);
262
263         // start edition on this node
264         var $overlay = $('<div class="html-editarea"><textarea></textarea></div>');
265         
266         $overlay.css({position: 'absolute', height: h, left: x, top: y, width: '95%'});        
267         $($origin[0].offsetParent).append($overlay);
268         $origin.data('edit-overlay', $overlay);
269
270         this.model.getXMLPart($origin, function(path, data) {
271             $('textarea', $overlay).val(data);
272         });      
273
274         if($origin.is("*[x-annotation-box]"))
275         {
276             var $b =  $origin.parent();
277             if(this.currentFocused) {
278                 // if some other is focused
279                 if($b[0] != this.currentFocused[0]) {
280                     this.unfocusAnnotation();
281                     this.focusAnnotation($b);
282                 }
283                 // already focues
284             }
285             else { // nothing was focused
286                 this.focusAnnotation($b);
287             }
288         }
289         else { // this item is not focusable
290             if(this.currentFocused) this.unfocusAnnotation();
291         }
292
293         this.currentOpen = $origin;
294         $origin.attr('x-open', 'open');
295                 
296         return false;
297     }
298   
299 });
300
301 // Register view
302 panels['html'] = HTMLView;