refactoring
[fnpeditor.git] / src / editor / modules / documentCanvas / canvas / canvas.js
index 6a60f80..937d580 100644 (file)
@@ -2,15 +2,17 @@ define([
 'libs/jquery',
 'libs/underscore',
 'libs/backbone',
+'fnpjs/logging/logging',
 'modules/documentCanvas/canvas/documentElement',
 'modules/documentCanvas/canvas/keyboard',
 'modules/documentCanvas/canvas/utils',
 'modules/documentCanvas/canvas/wlxmlListener'
-], function($, _, Backbone, documentElement, keyboard, utils, wlxmlListener) {
+], function($, _, Backbone, logging, documentElement, keyboard, utils, wlxmlListener) {
     
 'use strict';
-/* global document:false, window:false */
+/* global document:false, window:false, Node:false */
 
+var logger = logging.getLogger('canvas');
 
 var TextHandler = function(canvas) {this.canvas = canvas; this.buffer = null;};
 $.extend(TextHandler.prototype, {
@@ -52,6 +54,7 @@ var Canvas = function(wlxmlDocument, publisher) {
     this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
     this.wlxmlListener = wlxmlListener.create(this);
     this.loadWlxmlDocument(wlxmlDocument);
+    this.setupEventHandling();
     this.publisher = publisher ? publisher : function() {};
     this.textHandler = new TextHandler(this);
 };
@@ -66,7 +69,11 @@ $.extend(Canvas.prototype, {
         this.wlxmlListener.listenTo(wlxmlDocument);
         this.wlxmlDocument = wlxmlDocument;
         this.reloadRoot();
-        this.setupEventHandling();
+    },
+
+    createElement: function(wlxmlNode) {
+        var Factory = wlxmlNode.nodeType === Node.TEXT_NODE ? documentElement.DocumentTextElement : documentElement.DocumentNodeElement;
+        return Factory.create(wlxmlNode, this);
     },
 
     reloadRoot: function() {
@@ -89,11 +96,46 @@ $.extend(Canvas.prototype, {
             keyboard.handleKey(e, this);
         }.bind(this));
 
+        var mouseDown;
+        this.wrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
+            mouseDown = e.target;
+        });
+
         this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
             e.stopPropagation();
-            canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
+            if(e.originalEvent.detail === 3) {
+                e.preventDefault();
+                canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
+            } else {
+                if(mouseDown === e.target) {
+                    canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
+                }
+            }
         });
 
+        this.wrapper.on('paste', function(e) {
+            e.preventDefault();
+
+            var clipboardData = e.originalEvent.clipboardData;
+            if(!clipboardData || !clipboardData.getData) {
+                return; // TODO: alert
+            }
+
+            var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
+                cursor = canvas.getCursor(),
+                element = cursor.getPosition().element,
+                lhs, rhs;
+            
+            if(element && cursor.isWithinElement()) {
+                lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
+                rhs = element.getText().substr(cursor.getSelectionEnd().offset);
+                element.setText(lhs+text+rhs);
+                canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
+            } else {
+                /* jshint noempty:false */
+                // TODO: alert
+            }
+        });
 
         /* globals MutationObserver */
         var observer = new MutationObserver(function(mutations) {
@@ -108,7 +150,6 @@ $.extend(Canvas.prototype, {
                         canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
                     }
                     observer.observe(canvas.wrapper[0], config);
-                    canvas.publisher('contentChanged');
 
                     var textElement = canvas.getDocumentElement(mutation.target),
                         toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
@@ -171,10 +212,6 @@ $.extend(Canvas.prototype, {
         element.toggleHighlight(toggle);
     },
 
-    createNodeElement: function(params) {
-        return documentElement.DocumentNodeElement.create(params, this);
-    },
-
     getDocumentElement: function(from) {
         /* globals HTMLElement, Text */
         if(from instanceof HTMLElement || from instanceof Text) {
@@ -194,13 +231,20 @@ $.extend(Canvas.prototype, {
         return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
     },
 
-
+    contains: function(element) {
+        return element.dom().parents().index(this.wrapper) !== -1;
+    },
 
     setCurrentElement: function(element, params) {
         if(!(element instanceof documentElement.DocumentElement)) {
             element = utils.findCanvasElement(element);
         }
 
+        if(!element || !this.contains(element)) {
+            logger.warning('Cannot set current element: element doesn\'t exist on canvas');
+            return;
+        }
+
         params = _.extend({caretTo: 'end'}, params);
         var findFirstDirectTextChild = function(e, nodeToLand) {
             var byBrowser = this.getCursor().getPosition().element;
@@ -222,7 +266,6 @@ $.extend(Canvas.prototype, {
             } else {
                 this.wrapper.find('.current-node-element').removeClass('current-node-element');
                 element._container().addClass('current-node-element');
-                this.publisher('currentElementChanged', element);
             }
         }.bind(this);
 
@@ -266,12 +309,13 @@ $.extend(Canvas.prototype, {
             range.setStart(node, where);
         }
         
-        var collapseArg = true;
-        if(where === 'end') {
-            collapseArg = false;
+        if(where !== 'whole') {
+            var collapseArg = true;
+            if(where === 'end') {
+                collapseArg = false;
+            }
+            range.collapse(collapseArg);
         }
-        range.collapse(collapseArg);
-        
         var selection = document.getSelection();
 
         selection.removeAllRanges();
@@ -299,6 +343,9 @@ $.extend(Cursor.prototype, {
     isSelectingWithinElement: function() {
         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
     },
+    isWithinElement: function() {
+        return !this.isSelecting() || this.isSelectingWithinElement();
+    },
     isSelectingSiblings: function() {
         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
     },
@@ -331,25 +378,21 @@ $.extend(Cursor.prototype, {
             return {
                 element: anchorElement,
                 offset: selection.anchorOffset,
-                offsetAtBeginning: selection.anchorOffset === 0,
-                offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
+                offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
+                offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
             };
         }
         if(which === 'focus') {
             return {
                 element: focusElement,
                 offset: selection.focusOffset,
-                offsetAtBeginning: selection.focusOffset === 0,
-                offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
+                offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
+                offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
             };
         }
         
-        var element,
-            offset;
-
-        if(anchorElement.parent().sameNode(focusElement.parent())) {
-            var parent = anchorElement.parent(),
-                anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
+        var getPlaceData = function(anchorFirst) {
+            var element, offset;
             if(anchorFirst) {
                 if(which === 'start') {
                     element = anchorElement;
@@ -369,23 +412,31 @@ $.extend(Cursor.prototype, {
                     offset = selection.anchorOffset;
                 }
             }
-        } else {
-            // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
-            if(which === 'start') {
-                element = anchorElement;
-                offset = selection.anchorOffset;
+            return {element: element, offset: offset};
+        };
+
+        var anchorFirst, placeData, parent;
+
+        if(anchorElement.parent().sameNode(focusElement.parent())) {
+            parent = anchorElement.parent();
+            if(selection.anchorNode === selection.focusNode) {
+                anchorFirst = selection.anchorOffset <= selection.focusOffset;
             } else {
-                element = focusElement;
-                offset = selection.focusOffset;
+                anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
             }
+            placeData = getPlaceData(anchorFirst);
+        } else {
+            /*jshint bitwise: false*/
+            anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
+            placeData = getPlaceData(anchorFirst);
         }
 
-        var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
+        var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
         return {
-            element: element,
-            offset: offset,
-            offsetAtBeginning: offset === 0,
-            offsetAtEnd: nodeLen === offset
+            element: placeData.element,
+            offset: placeData.offset,
+            offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
+            offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
         };
     }
 });