2f25cb3d09d1b047cbc66ac6a9432ebb2e406fbd
[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, element;
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                     element = canvas.getDocumentElement(e.target);
174                     if(element && element.wlxmlNode.nodeType === Node.ELEMENT_NODE) {
175                         if(element.getVerticallyFirstTextElement && !element.getVerticallyFirstTextElement({considerChildren: false})) {
176                             canvas.setCurrentElement(element);
177                             return;
178                         }
179                     }
180                     if(window.getSelection().isCollapsed) {
181                         position = utils.caretPositionFromPoint(e.clientX, e.clientY);
182                         canvas.setCurrentElement(canvas.getDocumentElement(position.textNode), {caretTo: position.offset});
183                     }
184                 }
185             }
186         });
187
188         this.rootWrapper.on('paste', function(e) {
189             e.preventDefault();
190
191             var clipboardData = e.originalEvent.clipboardData;
192             if(!clipboardData || !clipboardData.getData) {
193                 return; // TODO: alert
194             }
195
196             var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
197                 cursor = canvas.getCursor(),
198                 element = cursor.getPosition().element,
199                 lhs, rhs;
200             
201             if(element && cursor.isWithinElement()) {
202                 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
203                 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
204                 element.setText(lhs+text+rhs);
205                 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
206             } else {
207                 /* jshint noempty:false */
208                 // TODO: alert
209             }
210         });
211
212         /* globals MutationObserver */
213         var observer = new MutationObserver(function(mutations) {
214             mutations.forEach(function(mutation) {
215                 if(canvas.dom[0].contains(mutation.target) && documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
216                     observer.disconnect();
217                     if(mutation.target.data === '') {
218                         mutation.target.data = utils.unicode.ZWS;
219                     }
220                     else if(mutation.oldValue === utils.unicode.ZWS) {
221                         mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
222                         canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
223                     }
224                     observer.observe(canvas.dom[0], config);
225
226                     var textElement = canvas.getDocumentElement(mutation.target),
227                         toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
228
229                     //textElement.data('wlxmlNode').setText(toSet);
230                     //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
231                     if(textElement.wlxmlNode.getText() !== toSet) {
232                         canvas.textHandler.handle(textElement.wlxmlNode, toSet);
233                     }
234                 }
235             });
236         });
237         var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
238         observer.observe(this.rootWrapper[0], config);
239
240
241         var hoverHandler = function(e) {
242             var el = canvas.getDocumentElement(e.currentTarget),
243                 expose = {
244                     mouseover: true,
245                     mouseout: false
246                 };
247             if(!el) {
248                 return;
249             }
250             e.stopPropagation();
251             if(el instanceof documentElement.DocumentTextElement) {
252                 el = el.parent();
253             }
254             el.updateState({exposed:expose[e.type]});
255         };
256
257         this.rootWrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
258         this.rootWrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
259
260         this.eventBus.on('elementToggled', function(toggle, element) {
261             if(!toggle) {
262                 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
263             }
264         });
265     },
266
267     view: function() {
268         return this.dom;
269     },
270
271     doc: function() {
272         return this.rootElement;
273     },
274
275     toggleElementHighlight: function(node, toggle) {
276         var element = utils.getElementForNode(node);
277         element.updateState({exposed: toggle});
278     },
279
280     getCursor: function() {
281         return new Cursor(this);
282     },
283
284     
285     getCurrentNodeElement: function() {
286         return this.currentNodeElement;
287     },
288
289     getCurrentTextElement: function() {
290         var htmlElement = this.rootWrapper.find('.current-text-element')[0];
291         if(htmlElement) {
292             return this.getDocumentElement(htmlElement);
293         }
294     },
295
296     getPreviousTextElement: function(relativeToElement, includeInvisible) {
297         return this.getNearestTextElement('above', relativeToElement, includeInvisible);
298     },
299
300     getNextTextElement: function(relativeToElement, includeInvisible) {
301         return this.getNearestTextElement('below', relativeToElement, includeInvisible);
302     },
303
304     getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
305         includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
306         var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
307         return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
308     },
309
310     contains: function(element) {
311         return element && element.dom && element.dom.parents().index(this.rootWrapper) !== -1;
312     },
313
314     triggerSelectionChanged: function() {
315         this.trigger('selectionChanged', this.getSelection());
316         var s = this.getSelection(),
317             f = s.toDocumentFragment();
318         if(f && f instanceof f.RangeFragment) {
319             if(this.currentNodeElement) {
320                 this.currentNodeElement.updateState({active: false});
321                 this.currentNodeElement = null;
322             }
323         }
324     },
325
326     getSelection: function() {
327         return new Selection(this);
328     },
329
330     select: function(fragment) {
331         if(fragment instanceof this.wlxmlDocument.RangeFragment) {
332             this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
333         } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
334             var params = {
335                 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
336             };
337             this.setCurrentElement(fragment.node, params);
338         } else {
339             logger.debug('Fragment not supported');
340         }
341     },
342
343     setCurrentElement: function(element, params) {
344         if(!element) {
345             logger.debug('Invalid element passed to setCurrentElement: ' + element);
346             return;
347         }
348
349         if(!(element instanceof documentElement.DocumentElement)) {
350             element = utils.getElementForNode(element);
351         }
352
353         if(!element || !this.contains(element)) {
354             logger.warning('Cannot set current element: element doesn\'t exist on canvas');
355             return;
356         }
357
358         params = _.extend({caretTo: 'end'}, params);
359         var findFirstDirectTextChild = function(e, nodeToLand) {
360             var byBrowser = this.getCursor().getPosition().element;
361             if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
362                 return byBrowser;
363             }
364             return _.isFunction(e.getVerticallyFirstTextElement) ? e.getVerticallyFirstTextElement({considerChildren: false}) : null;
365         }.bind(this);
366         var _markAsCurrent = function(element) {
367             if(element instanceof documentElement.DocumentTextElement) {
368                 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
369                 element.dom.addClass('current-text-element');
370             } else {
371                 if(this.currentNodeElement) {
372                     this.currentNodeElement.updateState({active: false});
373                 }
374                 element.updateState({active: true});
375                 this.currentNodeElement = element;
376             }
377         }.bind(this);
378
379
380         var isTextElement = element instanceof documentElement.DocumentTextElement,
381             nodeElementToLand = isTextElement ? element.parent() : element,
382             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
383             currentTextElement = this.getCurrentTextElement(),
384             currentNodeElement = this.getCurrentNodeElement();
385
386         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
387             this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
388         }
389
390         if(textElementToLand) {
391             _markAsCurrent(textElementToLand);
392             if((params.caretTo || params.caretTo === 0) || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
393                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
394             }
395         } else {
396             document.getSelection().removeAllRanges();
397         }
398
399         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
400             _markAsCurrent(nodeElementToLand);
401         }
402         this.triggerSelectionChanged();
403     },
404
405     _moveCaretToTextElement: function(element, where) {
406         var range = document.createRange(),
407             node = element.dom.contents()[0];
408
409         if(typeof where !== 'number') {
410             range.selectNodeContents(node);
411         } else {
412             range.setStart(node, Math.min(node.data.length, where));
413         }
414         
415         if(where !== 'whole') {
416             var collapseArg = true;
417             if(where === 'end') {
418                 collapseArg = false;
419             }
420             range.collapse(collapseArg);
421         }
422         var selection = document.getSelection();
423
424         $(node).parent().attr('contenteditable', true);
425         selection.removeAllRanges();
426         selection.addRange(range);
427         $(node).parent().focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
428     },
429
430     setCursorPosition: function(position) {
431         if(position.element) {
432             this._moveCaretToTextElement(position.element, position.offset);
433         }
434     }
435 });
436
437
438 var isText = function(node) {
439     return node && node.nodeType === Node.TEXT_NODE && $(node.parentNode).is('[document-text-element]');
440 };
441
442 var Selection = function(canvas) {
443     this.canvas = canvas;
444     var nativeSelection = this.nativeSelection = window.getSelection();
445     Object.defineProperty(this, 'type', {
446         get: function() {
447             if(nativeSelection.focusNode) {
448                 if(nativeSelection.isCollapsed && isText(nativeSelection.focusNode)) {
449                     return 'caret';
450                 }
451                 if(isText(nativeSelection.focusNode) && isText(nativeSelection.anchorNode)) {
452                     return 'textSelection';
453                 }
454             }
455             if(canvas.getCurrentNodeElement()) {
456                 return 'node';
457             }
458         }
459     });
460 };
461
462 $.extend(Selection.prototype, {
463     toDocumentFragment: function() {
464         var doc = this.canvas.wlxmlDocument,
465             anchorElement = this.canvas.getDocumentElement(this.nativeSelection.anchorNode),
466             focusElement = this.canvas.getDocumentElement(this.nativeSelection.focusNode),
467             anchorNode = anchorElement ? anchorElement.wlxmlNode : null,
468             focusNode = focusElement ? focusElement.wlxmlNode : null;
469         if(this.type === 'caret') {
470             return doc.createFragment(doc.CaretFragment, {node: anchorNode, offset: this.nativeSelection.anchorOffset});
471         }
472         if(this.type === 'textSelection') {
473             if(!anchorNode || !focusNode) {
474                 return;
475             }
476             if(anchorNode.isSiblingOf(focusNode)) {
477                 return doc.createFragment(doc.TextRangeFragment, {
478                     node1: anchorNode,
479                     offset1: this.nativeSelection.anchorOffset,
480                     node2: focusNode,
481                     offset2: this.nativeSelection.focusOffset,
482                 });
483             }
484             else {
485                 var siblingParents = doc.getSiblingParents({node1: anchorNode, node2: focusNode});
486                 return doc.createFragment(doc.RangeFragment, {
487                     node1: siblingParents.node1,
488                     node2: siblingParents.node2
489                 });
490             }
491         }
492         if(this.type === 'node') {
493             return doc.createFragment(doc.NodeFragment, {node: this.canvas.getCurrentNodeElement().wlxmlNode});
494         }
495     },
496     sameAs: function(other) {
497         void(other);
498     }
499 });
500
501 var Cursor = function(canvas) {
502     this.canvas = canvas;
503     this.selection = window.getSelection();
504 };
505
506 $.extend(Cursor.prototype, {
507     sameAs: function(other) {
508         var same = true;
509         if(!other) {
510             return false;
511         }
512
513         ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
514             same = same && this.selection[prop] === other.selection[prop];
515             if(!same) {
516                 return true; // break
517             }
518         }.bind(this));
519
520         return same;
521     },
522     isSelecting: function() {
523         var selection = window.getSelection();
524         return !selection.isCollapsed;
525     },
526     isSelectingWithinElement: function() {
527         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
528     },
529     isWithinElement: function() {
530         return !this.isSelecting() || this.isSelectingWithinElement();
531     },
532     isSelectingSiblings: function() {
533         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
534     },
535     getPosition: function() {
536         return this.getSelectionAnchor();
537     },
538     getSelectionStart: function() {
539         return this.getSelectionBoundry('start');
540     },
541     getSelectionEnd: function() {
542         return this.getSelectionBoundry('end');
543     },
544     getSelectionAnchor: function() {
545         return this.getSelectionBoundry('anchor');
546     },
547     getSelectionFocus: function() {
548         return this.getSelectionBoundry('focus');
549     },
550     getSelectionBoundry: function(which) {
551         /* globals window */
552         var selection = window.getSelection(),
553             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
554             focusElement = this.canvas.getDocumentElement(selection.focusNode);
555         
556         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
557             return {};
558         }
559
560         if(which === 'anchor') {
561             return {
562                 element: anchorElement,
563                 offset: selection.anchorOffset,
564                 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
565                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
566             };
567         }
568         if(which === 'focus') {
569             return {
570                 element: focusElement,
571                 offset: selection.focusOffset,
572                 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
573                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
574             };
575         }
576         
577         var getPlaceData = function(anchorFirst) {
578             var element, offset;
579             if(anchorFirst) {
580                 if(which === 'start') {
581                     element = anchorElement;
582                     offset = selection.anchorOffset;
583                 }
584                 else if(which === 'end') {
585                     element = focusElement;
586                     offset = selection.focusOffset;
587                 }
588             } else {
589                 if(which === 'start') {
590                     element = focusElement;
591                     offset = selection.focusOffset;
592                 }
593                 else if(which === 'end') {
594                     element = anchorElement;
595                     offset = selection.anchorOffset;
596                 }
597             }
598             return {element: element, offset: offset};
599         };
600
601         var anchorFirst, placeData, parent;
602
603         if(anchorElement.parent().sameNode(focusElement.parent())) {
604             parent = anchorElement.parent();
605             if(selection.anchorNode === selection.focusNode) {
606                 anchorFirst = selection.anchorOffset <= selection.focusOffset;
607             } else {
608                 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
609             }
610             placeData = getPlaceData(anchorFirst);
611         } else {
612             /*jshint bitwise: false*/
613             anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
614             placeData = getPlaceData(anchorFirst);
615         }
616
617         var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
618         return {
619             element: placeData.element,
620             offset: placeData.offset,
621             offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
622             offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
623         };
624     }
625 });
626
627 return {
628     fromXMLDocument: function(wlxmlDocument, elements, metadata) {
629         return new Canvas(wlxmlDocument, elements, metadata);
630     }
631 };
632
633 });