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