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