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