1 /*global View render_template panels */
2 var HTMLView = View.extend({
3 _className: 'HTMLView',
6 template: 'html-view-template',
8 init: function(element, model, parent, template) {
9 var submodel = model.contentModels['html'];
10 this._super(element, submodel, template);
13 this.themeEditor = new ThemeEditDialog( $('#theme-edit-dialog') );
16 .addObserver(this, 'data', this.modelDataChanged.bind(this))
17 .addObserver(this, 'state', this.modelStateChanged.bind(this));
19 this.modelStateChanged('state', this.model.get('state'));
20 this.modelDataChanged('data', this.model.get('data'));
24 this.currentOpen = null;
25 this.currentFocused = null;
29 modelDataChanged: function(property, value)
33 // the xml model changed
34 var container = $('.htmlview', this.element);
36 container.append(value);
38 this.updatePrintLink();
41 /* $(".theme-ref", this.$docbase).each(function() {
42 var id = $(this).attr('x-theme-class');
44 var end = $("span.theme-end[x-theme-class = " + id+"]");
45 var begin = $("span.theme-begin[x-theme-class = " + id+"]");
47 var h = $(this).outerHeight();
49 h = Math.max(h, end.offset().top - begin.offset().top);
50 $(this).css('height', h);
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'));
59 modelStateChanged: function(property, value)
63 if (value == 'synced' || value == 'dirty') {
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(
76 console.log("Sending scroll rq.", this);
78 var href = $(this).attr('href').split('-');
79 var line = parseInt(href[1]);
80 var column = parseInt(href[2]);
82 $(document).trigger('xml-scroll-request', {
97 this.$docbase.unbind('click');
100 this.$printLink.unbind();
102 if(this.$addThemeButton)
103 this.$addThemeButton.unbind();
107 this.$printLink = $('.htmlview-toolbar .html-print-link', this.element);
108 this.$docbase = $('.htmlview', this.element);
109 this.$addThemeButton = $('.htmlview-toolbar .html-add-motive', this.element);
110 // this.$debugButton = $('.htmlview-toolbar .html-serialize', this.element);
112 this.updatePrintLink();
113 this.$docbase.bind('click', this.itemClicked.bind(this));
114 this.$addThemeButton.click( this.addTheme.bind(this) );
115 // this.$debugButton.click( this.serialized.bind(this) );
118 /* serialized: function() {
119 this.model.set('state', 'dirty');
120 console.log( this.model.serializer.serializeToString(this.model.get('data')) );
124 this.model.load(true);
127 dispose: function() {
128 this.model.removeObserver(this);
132 itemClicked: function(event)
136 console.log('click:', event, event.ctrlKey, event.target);
137 var $e = $(event.target);
139 if($e.hasClass('annotation'))
141 if(this.currentOpen) return false;
143 var $p = $e.parent();
144 if(this.currentFocused)
146 console.log(this.currentFocused, $p);
147 if($p[0] == this.currentFocused[0]) {
148 console.log('unfocus of current');
149 this.unfocusAnnotation();
153 console.log('switch unfocus');
154 this.unfocusAnnotation();
157 this.focusAnnotation($p);
162 * Clicking outside of focused area doesn't unfocus by default
163 * - this greatly simplifies the whole click check
166 if( $e.hasClass('motyw'))
168 this.selectTheme($e.attr('theme-class'));
172 if( $e.hasClass('theme-text-list') )
174 this.selectTheme($e.parent().attr('theme-class'));
180 var editable = this.editableFor($e);
182 if($e.hasClass('delete-button'))
183 this.deleteElement(editable);
185 if($e.hasClass('edit-button'))
187 if( editable.hasClass('motyw') )
188 this.editTheme(editable);
190 this.openForEdit(editable);
193 if($e.hasClass('accept-button'))
194 this.closeWithSave(editable);
196 if($e.hasClass('reject-button'))
197 this.closeWithoutSave(editable);
200 messageCenter.addMessage('error', "wlsave", 'Błąd:' + e.toString());
206 unfocusAnnotation: function()
208 if(!this.currentFocused)
210 console.log('Redundant unfocus');
215 && this.currentOpen.is("*[x-annotation-box]")
216 && this.currentOpen.parent()[0] == this.currentFocused[0])
218 console.log("Can't unfocus open box");
222 var $box = $("*[x-annotation-box]", this.currentFocused);
226 // this.currentFocused.removeAttr('x-focused');
227 // this.currentFocused.hide();
228 this.currentFocused = null;
231 focusAnnotation: function($e) {
232 this.currentFocused = $e;
233 var $box = $("*[x-annotation-box]", $e);
238 // $e.attr('x-focused', 'focused');
241 closeWithSave: function($e) {
242 var $edit = $e.data('edit-overlay');
243 var newText = $('textarea', $edit).val();
246 errors = this.model.updateInnerWithWLML($e, newText);
249 messageCenter.addMessage('error', 'render', errors);
252 this.currentOpen = null;
256 closeWithoutSave: function($e) {
257 var $edit = $e.data('edit-overlay');
259 $e.removeAttr('x-open');
260 this.currentOpen = null;
263 editableFor: function($button)
268 while( ($e[0] != this.element[0]) && !($e.attr('x-editable')) && n < 50)
270 // console.log($e, $e.parent(), this.element);
275 if(!$e.attr('x-editable'))
276 throw Exception("Click outside of editable")
278 console.log("Trigger", $button, " yields editable: ", $e);
282 openForEdit: function($origin)
284 if(this.currentOpen && this.currentOpen != $origin) {
285 this.closeWithSave(this.currentOpen);
290 // annotations overlay their sub box - not their own box //
291 if($origin.is(".annotation-inline-box"))
292 $box = $("*[x-annotation-box]", $origin);
296 var x = $box[0].offsetLeft;
297 var y = $box[0].offsetTop;
298 var w = $box.outerWidth();
299 var h = $box.innerHeight();
301 console.log("Edit origin:", $origin, " box:", $box);
302 console.log("offsetParent:", $box[0].offsetParent);
303 console.log("Dimensions: ", x, y, w , h);
305 // start edition on this node
306 var $overlay = $('<div class="html-editarea"><textarea></textarea></div>');
308 h = Math.max(h, 2*parseInt($box.css('line-height')));
311 position: 'absolute',
319 $('textarea', $overlay).val( this.model.innerAsWLML($origin[0]) );
321 if($origin.is(".annotation-inline-box"))
323 if(this.currentFocused) {
324 // if some other is focused
325 if($origin[0] != this.currentFocused[0]) {
326 this.unfocusAnnotation();
327 this.focusAnnotation($origin);
331 else { // nothing was focused
332 this.focusAnnotation($origin);
335 else { // this item is not focusable
336 if(this.currentFocused) this.unfocusAnnotation();
339 $($box[0].offsetParent).append($overlay);
340 $origin.data('edit-overlay', $overlay);
342 this.currentOpen = $origin;
343 $origin.attr('x-open', 'open');
346 console.log("Can't open", e);
352 deleteElement: function($editable)
354 var relatedThemes = $("*[x-node='begin'], *[x-node='end']", $editable);
356 var themeMarks = relatedThemes.map(function() {
357 return $(".motyw[theme-class='"+$(this).attr('theme-class')+"']");
360 if($editable.is("*.motyw"))
362 console.log($editable);
363 var selector = "[theme-class='"+$editable.attr('theme-class')+"']";
364 relatedThemes = relatedThemes.add("*[x-node='begin']"+selector+", *[x-node='end']"+selector);
367 console.log(relatedThemes, themeMarks);
369 var del = confirm("Usunięcie elementu jest nieodwracalne.\n"
370 +" Czy na pewno chcesz usunąć ten element, wraz z zawartymi motywami ?\n");
373 relatedThemes.remove();
379 // Theme related stuff
380 verifyThemeInsertPoint: function(node) {
382 if(node.nodeType == 3) { // Text Node
383 node = node.parentNode;
386 if(node.nodeType != 1) return false;
388 console.log('Selection point:', node);
391 var xtype = node.attr('x-node');
393 if(!xtype || (xtype.search(':') >= 0) ||
394 xtype == 'motyw' || xtype == 'begin' || xtype == 'end')
397 // this is hopefully redundant
398 //if(! node.is('*.utwor *') )
401 // don't allow themes inside annotations
402 if( node.is('*[x-annotation-box] *') )
409 editTheme: function($element)
411 var themeTextSpan = $('.theme-text-list', $element);
412 this.themeEditor.setFromString( themeTextSpan.text() );
414 function _editThemeFinish(dialog) {
415 themeTextSpan.text( dialog.userData.themes.join(', ') );
418 this.themeEditor.show(_editThemeFinish);
422 // Special stuff for themes
426 var selection = window.getSelection();
427 var n = selection.rangeCount;
429 console.log("Range count:", n);
431 window.alert("Nie zaznaczono żadnego obszaru");
435 // for now allow only 1 range
437 window.alert("Zaznacz jeden obszar");
441 // remember the selected range
442 var range = selection.getRangeAt(0);
443 console.log(range.startContainer, range.endContainer);
445 // verify if the start/end points make even sense -
446 // they must be inside a x-node (otherwise they will be discarded)
447 // and the x-node must be a main text
448 if(! this.verifyThemeInsertPoint(range.startContainer) ) {
449 window.alert("Motyw nie może się zaczynać w tym miejscu.");
453 if(! this.verifyThemeInsertPoint(range.endContainer) ) {
454 window.alert("Motyw nie może się kończyć w tym miejscu.");
458 function _addThemeFinish(dialog)
460 var date = (new Date()).getTime();
461 var random = Math.floor(4000000000*Math.random());
462 var id = (''+date) + '-' + (''+random);
464 var spoint = document.createRange();
465 var epoint = document.createRange();
467 spoint.setStart(range.startContainer, range.startOffset);
468 epoint.setStart(range.endContainer, range.endOffset);
470 var mtag, btag, etag, errors;
471 var themesStr = dialog.userData.themes.join(', ');
474 mtag = $('<span></span>');
475 spoint.insertNode(mtag[0]);
476 errors = this.model.updateWithWLML(mtag, '<motyw id="m'+id+'">'+themesStr+'</motyw>');
479 messageCenter.addMessage('error', null, 'Błąd przy dodawaniu motywu :' + errors);
483 // insert theme-begin
484 btag = $('<span></span>');
485 spoint.insertNode(btag[0]);
486 errors = this.model.updateWithWLML(btag, '<begin id="b'+id+'" />');
489 messageCenter.addMessage('error', null, 'Błąd przy dodawaniu motywu :' + errors);
493 etag = $('<span></span>');
494 epoint.insertNode(etag[0]);
495 result = this.model.updateWithWLML(etag, '<end id="e'+id+'" />');
499 messageCenter.addMessage('error', null, 'Błąd przy dodawaniu motywu :' + errors);
503 selection.removeAllRanges();
508 this.themeEditor.setFromString('');
509 this.themeEditor.show(_addThemeFinish.bind(this));
512 selectTheme: function(themeId)
514 var selection = window.getSelection();
516 // remove current selection
517 selection.removeAllRanges();
519 var range = document.createRange();
520 var s = $(".motyw[theme-class='"+themeId+"']")[0];
521 var e = $(".end[theme-class='"+themeId+"']")[0];
522 console.log('Selecting range:', themeId, range, s, e);
525 range.setStartAfter(s);
526 range.setEndBefore(e);
527 selection.addRange(range);
532 var ThemeEditDialog = AbstractDialog.extend({
536 var active = $('input.theme-list-item:checked', this.$window);
538 if(active.length < 1) {
539 this.errors.push("You must select at least one theme.");
543 console.log("Active:", active);
544 this.userData.themes = $.makeArray(active.map(function() { return this.value; }) );
545 console.log('After validate:', this.userData);
546 return this._super();
549 setFromString: function(string)
551 var $unmatchedList = $('tbody.unknown-themes', this.$window);
553 $("tr:not(.header)", $unmatchedList).remove();
554 $unmatchedList.hide();
556 $('input.theme-list-item', this.$window).removeAttr('checked');
560 $.each(string.split(','), function() {
561 var name = $.trim(this);
564 console.log('Selecting:', name);
565 var checkbox = $("input.theme-list-item[value='"+name+"']", this.$window);
567 if(checkbox.length > 0)
568 checkbox.attr('checked', 'checked');
570 unmatched.push(name);
573 if(unmatched.length > 0)
575 $.each(unmatched, function() {
576 $('<tr><td colspan="5"><label><input type="checkbox"'+
577 ' checked="checked" class="theme-list-item" value="'
578 + this+ '" />"'+this+'"</label></td></tr>').
579 appendTo($unmatchedList);
582 $unmatchedList.show();
586 displayErrors: function() {
587 var errorP = $('.error-messages-inline-box', this.$window);
588 if(errorP.length > 0) {
590 $.each(this.errors, function() {
591 html += '<span>' + this + '</span>';
595 console.log('Validation errors:', html);
604 $('.error-messages-inline-box', this.$window).html('').hide();
610 panels['html'] = HTMLView;