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();
105 if(this.$addAnnotation)
106 this.$addAnnotation.unbind();
110 this.$printLink = $('.htmlview-toolbar .html-print-link', this.element);
111 this.$docbase = $('.htmlview', this.element);
112 this.$addThemeButton = $('.htmlview-toolbar .html-add-theme', this.element);
113 this.$addAnnotation = $('.htmlview-toolbar .html-add-annotation', this.element);
114 // this.$debugButton = $('.htmlview-toolbar .html-serialize', this.element);
116 this.updatePrintLink();
117 this.$docbase.bind('click', this.itemClicked.bind(this));
118 this.$addThemeButton.click( this.addTheme.bind(this) );
119 this.$addAnnotation.click( this.addAnnotation.bind(this) );
120 // this.$debugButton.click( this.serialized.bind(this) );
123 /* serialized: function() {
124 this.model.set('state', 'dirty');
125 console.log( this.model.serializer.serializeToString(this.model.get('data')) );
129 this.model.load(true);
132 dispose: function() {
133 this.model.removeObserver(this);
137 itemClicked: function(event)
141 console.log('click:', event, event.ctrlKey, event.target);
142 var $e = $(event.target);
144 if($e.hasClass('annotation'))
146 if(this.currentOpen) return false;
148 var $p = $e.parent();
149 if(this.currentFocused)
151 console.log(this.currentFocused, $p);
152 if($p[0] == this.currentFocused[0]) {
153 console.log('unfocus of current');
154 this.unfocusAnnotation();
158 console.log('switch unfocus');
159 this.unfocusAnnotation();
162 this.focusAnnotation($p);
167 * Clicking outside of focused area doesn't unfocus by default
168 * - this greatly simplifies the whole click check
171 if( $e.hasClass('motyw'))
173 this.selectTheme($e.attr('theme-class'));
177 if( $e.hasClass('theme-text-list') )
179 this.selectTheme($e.parent().attr('theme-class'));
185 var editable = this.editableFor($e);
190 if($e.hasClass('delete-button'))
191 this.deleteElement(editable);
193 if($e.hasClass('edit-button'))
195 if( editable.hasClass('motyw') )
196 this.editTheme(editable);
198 this.openForEdit(editable);
201 if($e.hasClass('accept-button'))
202 this.closeWithSave(editable);
204 if($e.hasClass('reject-button'))
205 this.closeWithoutSave(editable);
208 messageCenter.addMessage('error', "wlsave", 'Błąd:' + e.toString());
214 unfocusAnnotation: function()
216 if(!this.currentFocused)
218 console.log('Redundant unfocus');
223 && this.currentOpen.is("*[x-annotation-box]")
224 && this.currentOpen.parent()[0] == this.currentFocused[0])
226 console.log("Can't unfocus open box");
230 var $box = $("*[x-annotation-box]", this.currentFocused);
234 // this.currentFocused.removeAttr('x-focused');
235 // this.currentFocused.hide();
236 this.currentFocused = null;
239 focusAnnotation: function($e) {
240 this.currentFocused = $e;
241 var $box = $("*[x-annotation-box]", $e);
246 // $e.attr('x-focused', 'focused');
249 closeWithSave: function($e) {
250 var $edit = $e.data('edit-overlay');
251 var newText = $('textarea', $edit).val();
254 errors = this.model.updateInnerWithWLML($e, newText);
257 messageCenter.addMessage('error', 'render', errors);
260 this.currentOpen = null;
264 closeWithoutSave: function($e) {
265 var $edit = $e.data('edit-overlay');
267 $e.removeAttr('x-open');
268 this.currentOpen = null;
271 editableFor: function($button)
276 while( ($e[0] != this.element[0]) && !($e.attr('x-editable')) && n < 50)
278 // console.log($e, $e.parent(), this.element);
283 if(!$e.attr('x-editable'))
286 console.log("Trigger", $button, " yields editable: ", $e);
290 openForEdit: function($origin)
292 if(this.currentOpen && this.currentOpen != $origin) {
293 this.closeWithSave(this.currentOpen);
298 // annotations overlay their sub box - not their own box //
299 if($origin.is(".annotation-inline-box"))
300 $box = $("*[x-annotation-box]", $origin);
304 var x = $box[0].offsetLeft;
305 var y = $box[0].offsetTop;
306 var w = $box.outerWidth();
307 var h = $box.innerHeight();
309 console.log("Edit origin:", $origin, " box:", $box);
310 console.log("offsetParent:", $box[0].offsetParent);
311 console.log("Dimensions: ", x, y, w , h);
313 // start edition on this node
314 var $overlay = $('<div class="html-editarea"><textarea></textarea></div>');
316 h = Math.max(h, 2*parseInt($box.css('line-height')));
319 position: 'absolute',
327 $('textarea', $overlay).val( this.model.innerAsWLML($origin[0]) );
329 if($origin.is(".annotation-inline-box"))
331 if(this.currentFocused) {
332 // if some other is focused
333 if($origin[0] != this.currentFocused[0]) {
334 this.unfocusAnnotation();
335 this.focusAnnotation($origin);
339 else { // nothing was focused
340 this.focusAnnotation($origin);
343 else { // this item is not focusable
344 if(this.currentFocused) this.unfocusAnnotation();
347 $($box[0].offsetParent).append($overlay);
348 $origin.data('edit-overlay', $overlay);
350 this.currentOpen = $origin;
351 $origin.attr('x-open', 'open');
354 console.log("Can't open", e);
360 deleteElement: function($editable)
362 var relatedThemes = $("*[x-node='begin'], *[x-node='end']", $editable);
364 var themeMarks = relatedThemes.map(function() {
365 return $(".motyw[theme-class='"+$(this).attr('theme-class')+"']");
368 if($editable.is("*.motyw"))
370 console.log($editable);
371 var selector = "[theme-class='"+$editable.attr('theme-class')+"']";
372 relatedThemes = relatedThemes.add("*[x-node='begin']"+selector+", *[x-node='end']"+selector);
375 console.log(relatedThemes, themeMarks);
377 var del = confirm("Usunięcie elementu jest nieodwracalne.\n"
378 +" Czy na pewno chcesz usunąć ten element, wraz z zawartymi motywami ?\n");
381 relatedThemes.remove();
388 // Special stuff for themes
391 // Theme related stuff
392 verifyThemeInsertPoint: function(node) {
394 if(node.nodeType == 3) { // Text Node
395 node = node.parentNode;
398 if(node.nodeType != 1) return false;
400 console.log('Selection point:', node);
403 var xtype = node.attr('x-node');
405 if(!xtype || (xtype.search(':') >= 0) ||
406 xtype == 'motyw' || xtype == 'begin' || xtype == 'end')
409 // this is hopefully redundant
410 //if(! node.is('*.utwor *') )
413 // don't allow themes inside annotations
414 if( node.is('*[x-annotation-box] *') )
421 editTheme: function($element)
423 var themeTextSpan = $('.theme-text-list', $element);
424 this.themeEditor.setFromString( themeTextSpan.text() );
426 function _editThemeFinish(dialog) {
427 themeTextSpan.text( dialog.userData.themes.join(', ') );
430 this.themeEditor.show(_editThemeFinish);
436 var selection = window.getSelection();
437 var n = selection.rangeCount;
439 console.log("Range count:", n);
441 window.alert("Nie zaznaczono żadnego obszaru");
445 // for now allow only 1 range
447 window.alert("Zaznacz jeden obszar");
451 // remember the selected range
452 var range = selection.getRangeAt(0);
453 console.log(range.startContainer, range.endContainer);
455 // verify if the start/end points make even sense -
456 // they must be inside a x-node (otherwise they will be discarded)
457 // and the x-node must be a main text
458 if(! this.verifyThemeInsertPoint(range.startContainer) ) {
459 window.alert("Motyw nie może się zaczynać w tym miejscu.");
463 if(! this.verifyThemeInsertPoint(range.endContainer) ) {
464 window.alert("Motyw nie może się kończyć w tym miejscu.");
468 function _addThemeFinish(dialog)
470 var date = (new Date()).getTime();
471 var random = Math.floor(4000000000*Math.random());
472 var id = (''+date) + '-' + (''+random);
474 var spoint = document.createRange();
475 var epoint = document.createRange();
477 spoint.setStart(range.startContainer, range.startOffset);
478 epoint.setStart(range.endContainer, range.endOffset);
480 var mtag, btag, etag, errors;
481 var themesStr = dialog.userData.themes.join(', ');
484 mtag = $('<span></span>');
485 spoint.insertNode(mtag[0]);
486 errors = this.model.updateWithWLML(mtag, '<motyw id="m'+id+'">'+themesStr+'</motyw>');
489 messageCenter.addMessage('error', null, 'Błąd przy dodawaniu motywu :' + errors);
493 // insert theme-begin
494 btag = $('<span></span>');
495 spoint.insertNode(btag[0]);
496 errors = this.model.updateWithWLML(btag, '<begin id="b'+id+'" />');
499 messageCenter.addMessage('error', null, 'Błąd przy dodawaniu motywu :' + errors);
503 etag = $('<span></span>');
504 epoint.insertNode(etag[0]);
505 result = this.model.updateWithWLML(etag, '<end id="e'+id+'" />');
509 messageCenter.addMessage('error', null, 'Błąd przy dodawaniu motywu :' + errors);
513 selection.removeAllRanges();
518 this.themeEditor.setFromString('');
519 this.themeEditor.show(_addThemeFinish.bind(this));
522 selectTheme: function(themeId)
524 var selection = window.getSelection();
526 // remove current selection
527 selection.removeAllRanges();
529 var range = document.createRange();
530 var s = $(".motyw[theme-class='"+themeId+"']")[0];
531 var e = $(".end[theme-class='"+themeId+"']")[0];
532 console.log('Selecting range:', themeId, range, s, e);
535 range.setStartAfter(s);
536 range.setEndBefore(e);
537 selection.addRange(range);
541 addAnnotation: function()
543 var selection = window.getSelection();
544 var n = selection.rangeCount;
546 console.log("Range count:", n);
548 window.alert("Nie zaznaczono żadnego obszaru");
552 // for now allow only 1 range
554 window.alert("Zaznacz jeden obszar");
558 // remember the selected range
559 var range = selection.getRangeAt(0);
561 if(! this.verifyThemeInsertPoint(range.endContainer) ) {
562 window.alert("Nie można wstawić w to miejsce przypisu.");
566 var text = range.toString();
567 var tag = $('<span></span>');
568 range.collapse(false);
569 range.insertNode(tag[0]);
570 var errors = this.model.updateWithWLML(tag, '<pr><slowo_obce>'+text+"</slowo_obce> </pr>");
574 messageCenter.addMessage('error', null, 'Błąd przy dodawaniu przypisu:' + errors);
582 var ThemeEditDialog = AbstractDialog.extend({
586 var active = $('input.theme-list-item:checked', this.$window);
588 if(active.length < 1) {
589 this.errors.push("You must select at least one theme.");
593 console.log("Active:", active);
594 this.userData.themes = $.makeArray(active.map(function() { return this.value; }) );
595 console.log('After validate:', this.userData);
596 return this._super();
599 setFromString: function(string)
601 var $unmatchedList = $('tbody.unknown-themes', this.$window);
603 $("tr:not(.header)", $unmatchedList).remove();
604 $unmatchedList.hide();
606 $('input.theme-list-item', this.$window).removeAttr('checked');
610 $.each(string.split(','), function() {
611 var name = $.trim(this);
614 console.log('Selecting:', name);
615 var checkbox = $("input.theme-list-item[value='"+name+"']", this.$window);
617 if(checkbox.length > 0)
618 checkbox.attr('checked', 'checked');
620 unmatched.push(name);
623 if(unmatched.length > 0)
625 $.each(unmatched, function() {
626 $('<tr><td colspan="5"><label><input type="checkbox"'+
627 ' checked="checked" class="theme-list-item" value="'
628 + this+ '" />"'+this+'"</label></td></tr>').
629 appendTo($unmatchedList);
632 $unmatchedList.show();
636 displayErrors: function() {
637 var errorP = $('.error-messages-inline-box', this.$window);
638 if(errorP.length > 0) {
640 $.each(this.errors, function() {
641 html += '<span>' + this + '</span>';
645 console.log('Validation errors:', html);
654 $('.error-messages-inline-box', this.$window).html('').hide();
660 panels['html'] = HTMLView;