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