editor: make comment not visible on canvas
[fnpeditor.git] / src / editor / modules / documentCanvas / canvas / canvas.js
1 define([
2 'libs/jquery',
3 'libs/underscore',
4 'libs/backbone',
5 'fnpjs/logging/logging',
6 'modules/documentCanvas/canvas/documentElement',
7 'modules/documentCanvas/canvas/keyboard',
8 'modules/documentCanvas/canvas/utils',
9 'modules/documentCanvas/canvas/wlxmlListener',
10 'modules/documentCanvas/canvas/elementsRegister',
11 'modules/documentCanvas/canvas/genericElement',
12 'modules/documentCanvas/canvas/nullElement',
13 ], function($, _, Backbone, logging, documentElement, keyboard, utils, wlxmlListener, ElementsRegister, genericElement, nullElement) {
14     
15 'use strict';
16 /* global document:false, window:false, Node:false, gettext */
17
18 var logger = logging.getLogger('canvas');
19
20 var TextHandler = function(canvas) {this.canvas = canvas; this.buffer = null;};
21 $.extend(TextHandler.prototype, {
22     handle: function(node, text) {
23         this.setText(text, node);
24         // return;
25         // if(!this.node) {
26         //     this.node = node;
27         // }
28         // if(this.node.sameNode(node)) {
29         //     this._ping(text);
30         // } else {
31         //     this.flush();
32         //     this.node = node;
33         //     this._ping(text);
34         // }
35     },
36     _ping: _.throttle(function(text) {
37         this.buffer = text;
38         this.flush();
39     }, 1000),
40     flush: function() {
41         if(this.buffer !== null) {
42             this.setText(this.buffer, this.node);
43             this.buffer = null;
44         }
45     },
46     setText: function(text, node) {
47         //this.canvas.wlxmlDocument.transform('setText', {node:node, text: text});
48         node.document.transaction(function() {
49             node.setText(text);
50         }, {
51             metadata:{
52                 description: gettext('Changing text')
53             }
54         });
55
56     }
57
58 });
59
60
61 var Canvas = function(wlxmlDocument, elements) {
62     this.elementsRegister = new ElementsRegister(documentElement.DocumentNodeElement, nullElement);
63
64     elements = [
65         {tag: 'section', klass: null, prototype: genericElement},
66         {tag: 'div', klass: null, prototype: genericElement},
67         {tag: 'header', klass: null, prototype: genericElement},
68         {tag: 'span', klass: null, prototype: genericElement},
69         {tag: 'aside', klass: null, prototype: genericElement}
70     ].concat(elements || []);
71
72     (elements).forEach(function(elementDesc) {
73         this.elementsRegister.register(elementDesc);
74     }.bind(this));
75     this.eventBus = _.extend({}, Backbone.Events);
76     this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
77     this.wlxmlListener = wlxmlListener.create(this);
78     this.loadWlxmlDocument(wlxmlDocument);
79     this.setupEventHandling();
80     this.textHandler = new TextHandler(this);
81 };
82
83 $.extend(Canvas.prototype, Backbone.Events, {
84
85     loadWlxmlDocument: function(wlxmlDocument) {
86         if(!wlxmlDocument) {
87             return false;
88         }
89
90         this.wlxmlListener.listenTo(wlxmlDocument);
91         this.wlxmlDocument = wlxmlDocument;
92         this.reloadRoot();
93     },
94
95     createElement: function(wlxmlNode) {
96         var Factory;
97         if(wlxmlNode.nodeType === Node.TEXT_NODE) {
98             Factory = documentElement.DocumentTextElement;
99         } else {
100             Factory = this.elementsRegister.getElement({tag: wlxmlNode.getTagName(), klass: wlxmlNode.getClass()});
101         }
102         return new Factory(wlxmlNode, this);
103     },
104
105     getDocumentElement: function(htmlElement) {
106         /* globals HTMLElement, Text */
107         if(!htmlElement || !(htmlElement instanceof HTMLElement || htmlElement instanceof Text)) {
108             return null;
109         }
110         var $element = $(htmlElement);
111         if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined) {
112             return $element.data('canvas-element');
113         }
114
115         if(htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined) {
116             $element = $element.parent();
117         }
118
119         if($element.attr('document-text-element') !== undefined || (htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined)) {
120             //return DocumentTextElement.fromHTMLElement(htmlElement, canvas);
121             return $element.data('canvas-element');
122         }
123     },
124
125     reloadRoot: function() {
126         this.rootElement = this.createElement(this.wlxmlDocument.root);
127         this.wrapper.empty();
128         this.wrapper.append(this.rootElement.dom);
129     },
130
131     setupEventHandling: function() {
132         var canvas = this;
133
134         this.wrapper.on('keyup keydown keypress', function(e) {
135             keyboard.handleKey(e, canvas);
136         });
137
138         this.wrapper.on('mouseup', function() {
139             canvas.triggerSelectionChanged();
140         });
141
142         var mouseDown;
143         this.wrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
144             mouseDown = e.target;
145         });
146
147         this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
148             e.stopPropagation();
149             if(e.originalEvent.detail === 3) {
150                 e.preventDefault();
151                 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
152             } else {
153                 if(mouseDown === e.target) {
154                     canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
155                 }
156             }
157         });
158
159         this.wrapper.on('paste', function(e) {
160             e.preventDefault();
161
162             var clipboardData = e.originalEvent.clipboardData;
163             if(!clipboardData || !clipboardData.getData) {
164                 return; // TODO: alert
165             }
166
167             var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
168                 cursor = canvas.getCursor(),
169                 element = cursor.getPosition().element,
170                 lhs, rhs;
171             
172             if(element && cursor.isWithinElement()) {
173                 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
174                 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
175                 element.setText(lhs+text+rhs);
176                 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
177             } else {
178                 /* jshint noempty:false */
179                 // TODO: alert
180             }
181         });
182
183         /* globals MutationObserver */
184         var observer = new MutationObserver(function(mutations) {
185             mutations.forEach(function(mutation) {
186                 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
187                     observer.disconnect();
188                     if(mutation.target.data === '') {
189                         mutation.target.data = utils.unicode.ZWS;
190                     }
191                     else if(mutation.oldValue === utils.unicode.ZWS) {
192                         mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
193                         canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
194                     }
195                     observer.observe(canvas.wrapper[0], config);
196
197                     var textElement = canvas.getDocumentElement(mutation.target),
198                         toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
199
200                     //textElement.data('wlxmlNode').setText(toSet);
201                     //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
202                     if(textElement.wlxmlNode.getText() !== toSet) {
203                         canvas.textHandler.handle(textElement.wlxmlNode, toSet);
204                     }
205                 }
206             });
207         });
208         var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
209         observer.observe(this.wrapper[0], config);
210
211
212         var hoverHandler = function(e) {
213             var el = canvas.getDocumentElement(e.currentTarget),
214                 expose = {
215                     mouseover: true,
216                     mouseout: false
217                 };
218             if(!el) {
219                 return;
220             }
221             e.stopPropagation();
222             if(el instanceof documentElement.DocumentTextElement) {
223                 el = el.parent();
224             }
225             el.updateState({exposed:expose[e.type]});
226         };
227
228         this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
229         this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
230
231         this.eventBus.on('elementToggled', function(toggle, element) {
232             if(!toggle) {
233                 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
234             }
235         });
236     },
237
238     view: function() {
239         return this.wrapper;
240     },
241
242     doc: function() {
243         return this.rootElement;
244     },
245
246     toggleElementHighlight: function(node, toggle) {
247         var element = utils.getElementForNode(node);
248         element.updateState({exposed: toggle});
249     },
250
251     getCursor: function() {
252         return new Cursor(this);
253     },
254
255     
256     getCurrentNodeElement: function() {
257         return this.currentNodeElement;
258     },
259
260     getCurrentTextElement: function() {
261         var htmlElement = this.wrapper.find('.current-text-element')[0];
262         if(htmlElement) {
263             return this.getDocumentElement(htmlElement);
264         }
265     },
266
267     getPreviousTextElement: function(relativeToElement, includeInvisible) {
268         return this.getNearestTextElement('above', relativeToElement, includeInvisible);
269     },
270
271     getNextTextElement: function(relativeToElement, includeInvisible) {
272         return this.getNearestTextElement('below', relativeToElement, includeInvisible);
273     },
274
275     getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
276         includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
277         var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
278         return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
279     },
280
281     contains: function(element) {
282         return element && element.dom && element.dom.parents().index(this.wrapper) !== -1;
283     },
284
285     triggerSelectionChanged: function() {
286         this.trigger('selectionChanged', this.getSelection());
287         var s = this.getSelection(),
288             f = s.toDocumentFragment();
289         if(f && f instanceof f.RangeFragment) {
290             if(this.currentNodeElement) {
291                 this.currentNodeElement.updateState({active: false});
292                 this.currentNodeElement = null;
293             }
294         }
295     },
296
297     getSelection: function() {
298         return new Selection(this);
299     },
300
301     select: function(fragment) {
302         if(fragment instanceof this.wlxmlDocument.RangeFragment) {
303             this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
304         } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
305             var params = {
306                 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
307             };
308             this.setCurrentElement(fragment.node, params);
309         } else {
310             logger.debug('Fragment not supported');
311         }
312     },
313
314     setCurrentElement: function(element, params) {
315         if(!element) {
316             logger.debug('Invalid element passed to setCurrentElement: ' + element);
317             return;
318         }
319
320         if(!(element instanceof documentElement.DocumentElement)) {
321             element = utils.getElementForNode(element);
322         }
323
324         if(!element || !this.contains(element)) {
325             logger.warning('Cannot set current element: element doesn\'t exist on canvas');
326             return;
327         }
328
329         params = _.extend({caretTo: 'end'}, params);
330         var findFirstDirectTextChild = function(e, nodeToLand) {
331             var byBrowser = this.getCursor().getPosition().element;
332             if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
333                 return byBrowser;
334             }
335             return e.getVerticallyFirstTextElement();
336         }.bind(this);
337         var _markAsCurrent = function(element) {
338             if(element instanceof documentElement.DocumentTextElement) {
339                 this.wrapper.find('.current-text-element').removeClass('current-text-element');
340                 element.dom.addClass('current-text-element');
341             } else {
342                 if(this.currentNodeElement) {
343                     this.currentNodeElement.updateState({active: false});
344                 }
345                 element.updateState({active: true});
346                 this.currentNodeElement = element;
347             }
348         }.bind(this);
349
350
351         var isTextElement = element instanceof documentElement.DocumentTextElement,
352             nodeElementToLand = isTextElement ? element.parent() : element,
353             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
354             currentTextElement = this.getCurrentTextElement(),
355             currentNodeElement = this.getCurrentNodeElement();
356
357         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
358             this.wrapper.find('.current-text-element').removeClass('current-text-element');
359         }
360
361         if(textElementToLand) {
362             _markAsCurrent(textElementToLand);
363             if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
364                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
365             }
366         } else {
367             document.getSelection().removeAllRanges();
368         }
369
370         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
371             _markAsCurrent(nodeElementToLand);
372         }
373         this.triggerSelectionChanged();
374     },
375
376     _moveCaretToTextElement: function(element, where) {
377         var range = document.createRange(),
378             node = element.dom.contents()[0];
379
380         if(typeof where !== 'number') {
381             range.selectNodeContents(node);
382         } else {
383             range.setStart(node, Math.min(node.data.length, where));
384         }
385         
386         if(where !== 'whole') {
387             var collapseArg = true;
388             if(where === 'end') {
389                 collapseArg = false;
390             }
391             range.collapse(collapseArg);
392         }
393         var selection = document.getSelection();
394
395         selection.removeAllRanges();
396         selection.addRange(range);
397         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
398     },
399
400     setCursorPosition: function(position) {
401         if(position.element) {
402             this._moveCaretToTextElement(position.element, position.offset);
403         }
404     },
405
406     toggleGrid: function() {
407         this.wrapper.toggleClass('grid-on');
408         this.trigger('changed');
409     },
410     isGridToggled: function() {
411         return this.wrapper.hasClass('grid-on');
412     }
413 });
414
415
416 var isText = function(node) {
417     return node && node.nodeType === Node.TEXT_NODE && $(node.parentNode).is('[document-text-element]');
418 };
419
420 var Selection = function(canvas) {
421     this.canvas = canvas;
422     var nativeSelection = this.nativeSelection = window.getSelection();
423     Object.defineProperty(this, 'type', {
424         get: function() {
425             if(nativeSelection.focusNode) {
426                 if(nativeSelection.isCollapsed && isText(nativeSelection.focusNode)) {
427                     return 'caret';
428                 }
429                 if(isText(nativeSelection.focusNode) && isText(nativeSelection.anchorNode)) {
430                     return 'textSelection';
431                 }
432             }
433             if(canvas.getCurrentNodeElement()) {
434                 return 'node';
435             }
436         }
437     });
438 };
439
440 $.extend(Selection.prototype, {
441     toDocumentFragment: function() {
442         var doc = this.canvas.wlxmlDocument,
443             anchorElement = this.canvas.getDocumentElement(this.nativeSelection.anchorNode),
444             focusElement = this.canvas.getDocumentElement(this.nativeSelection.focusNode),
445             anchorNode = anchorElement ? anchorElement.wlxmlNode : null,
446             focusNode = focusElement ? focusElement.wlxmlNode : null;
447         if(this.type === 'caret') {
448             return doc.createFragment(doc.CaretFragment, {node: anchorNode, offset: this.nativeSelection.anchorOffset});
449         }
450         if(this.type === 'textSelection') {
451             if(anchorNode.isSiblingOf(focusNode)) {
452                 return doc.createFragment(doc.TextRangeFragment, {
453                     node1: anchorNode,
454                     offset1: this.nativeSelection.anchorOffset,
455                     node2: focusNode,
456                     offset2: this.nativeSelection.focusOffset,
457                 });
458             }
459             else {
460                 var siblingParents = doc.getSiblingParents({node1: anchorNode, node2: focusNode});
461                 return doc.createFragment(doc.RangeFragment, {
462                     node1: siblingParents.node1,
463                     node2: siblingParents.node2
464                 });
465             }
466         }
467         if(this.type === 'node') {
468             return doc.createFragment(doc.NodeFragment, {node: this.canvas.getCurrentNodeElement().wlxmlNode});
469         }
470     },
471     sameAs: function(other) {
472         void(other);
473     }
474 });
475
476 var Cursor = function(canvas) {
477     this.canvas = canvas;
478     this.selection = window.getSelection();
479 };
480
481 $.extend(Cursor.prototype, {
482     sameAs: function(other) {
483         var same = true;
484         if(!other) {
485             return false;
486         }
487
488         ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
489             same = same && this.selection[prop] === other.selection[prop];
490             if(!same) {
491                 return true; // break
492             }
493         }.bind(this));
494
495         return same;
496     },
497     isSelecting: function() {
498         var selection = window.getSelection();
499         return !selection.isCollapsed;
500     },
501     isSelectingWithinElement: function() {
502         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
503     },
504     isWithinElement: function() {
505         return !this.isSelecting() || this.isSelectingWithinElement();
506     },
507     isSelectingSiblings: function() {
508         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
509     },
510     getPosition: function() {
511         return this.getSelectionAnchor();
512     },
513     getSelectionStart: function() {
514         return this.getSelectionBoundry('start');
515     },
516     getSelectionEnd: function() {
517         return this.getSelectionBoundry('end');
518     },
519     getSelectionAnchor: function() {
520         return this.getSelectionBoundry('anchor');
521     },
522     getSelectionFocus: function() {
523         return this.getSelectionBoundry('focus');
524     },
525     getSelectionBoundry: function(which) {
526         /* globals window */
527         var selection = window.getSelection(),
528             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
529             focusElement = this.canvas.getDocumentElement(selection.focusNode);
530         
531         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
532             return {};
533         }
534
535         if(which === 'anchor') {
536             return {
537                 element: anchorElement,
538                 offset: selection.anchorOffset,
539                 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
540                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
541             };
542         }
543         if(which === 'focus') {
544             return {
545                 element: focusElement,
546                 offset: selection.focusOffset,
547                 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
548                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
549             };
550         }
551         
552         var getPlaceData = function(anchorFirst) {
553             var element, offset;
554             if(anchorFirst) {
555                 if(which === 'start') {
556                     element = anchorElement;
557                     offset = selection.anchorOffset;
558                 }
559                 else if(which === 'end') {
560                     element = focusElement;
561                     offset = selection.focusOffset;
562                 }
563             } else {
564                 if(which === 'start') {
565                     element = focusElement;
566                     offset = selection.focusOffset;
567                 }
568                 else if(which === 'end') {
569                     element = anchorElement;
570                     offset = selection.anchorOffset;
571                 }
572             }
573             return {element: element, offset: offset};
574         };
575
576         var anchorFirst, placeData, parent;
577
578         if(anchorElement.parent().sameNode(focusElement.parent())) {
579             parent = anchorElement.parent();
580             if(selection.anchorNode === selection.focusNode) {
581                 anchorFirst = selection.anchorOffset <= selection.focusOffset;
582             } else {
583                 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
584             }
585             placeData = getPlaceData(anchorFirst);
586         } else {
587             /*jshint bitwise: false*/
588             anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
589             placeData = getPlaceData(anchorFirst);
590         }
591
592         var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
593         return {
594             element: placeData.element,
595             offset: placeData.offset,
596             offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
597             offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
598         };
599     }
600 });
601
602 return {
603     fromXMLDocument: function(wlxmlDocument, elements) {
604         return new Canvas(wlxmlDocument, elements);
605     }
606 };
607
608 });