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