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