prevent empty span in a new node
[fnpeditor.git] / src / editor / modules / documentCanvas / canvas / keyboard.js
index f06f1f1..577c2fe 100644 (file)
@@ -1,8 +1,7 @@
 define([
 'libs/jquery',
-'modules/documentCanvas/canvas/documentElement',
 'modules/documentCanvas/canvas/utils'
-], function($, documentElement, utils) {
+], function($, utils) {
     
 'use strict';
 /* globals gettext */
@@ -18,26 +17,6 @@ var KEYS = {
     X: 88
 };
 
-var handleKey = function(event, canvas) {
-    handlers.some(function(handler) {
-        if(handles(handler, event) && handler[event.type]) {
-            handler[event.type](event, canvas);
-            return true;
-        }
-    });
-};
-
-var handles = function(handler, event) {
-    if(handler.key === event.which) {
-        return true;
-    }
-    if(handler.keys && handler.keys.indexOf(event.which) !== -1) {
-        return true;
-    }
-    return false;
-};
-
-
 var scroll = function(place, textElement) {
     var rect = textElement.getBoundingClientRect(),
         scroll = $('#rng-module-documentCanvas-contentWrapper'),
@@ -86,191 +65,6 @@ var getFirstRectBelow = function(node, y) {
     return toret;
 };
 
-var handlers = [];
-
-
-handlers.push({key: KEYS.ENTER,
-    keydown: function(event, canvas) {
-        event.preventDefault();
-        var cursor = canvas.getCursor(),
-            position = cursor.getPosition(),
-            element = position.element;
-
-        if(Object.keys(cursor.getPosition()).length === 0) {
-            var currentElement = canvas.getCurrentNodeElement();
-            if(currentElement && !currentElement.wlxmlNode.isRoot()) {
-                canvas.wlxmlDocument.transaction(function() {
-                    var added = currentElement.wlxmlNode.after({
-                        tagName: currentElement.wlxmlNode.getTagName() || 'div',
-                        attrs: {'class': currentElement.wlxmlNode.getClass() || 'p'}
-                    });
-                    added.append({text:''});
-                    return added;
-                }, {
-                    metadata: {
-                        description: gettext('Splitting text')
-                    },
-                    success: function(ret) {
-                        canvas.setCurrentElement(utils.getElementForNode(ret), {caretTo: 'start'});
-                    }
-                });
-
-            }
-            return;
-        }
-
-        if(!cursor.isSelecting()) {
-            if(event.ctrlKey) {
-                if(element instanceof documentElement.DocumentTextElement) {
-                    element = element.parent();
-                }
-
-                canvas.wlxmlDocument.transaction(function() {
-                    var added = element.wlxmlNode.after(
-                        {tagName: element.wlxmlNode.getTagName() || 'div', attrs: {'class': element.wlxmlNode.getClass() || 'p'}}
-                    );
-                    added.append({text: ''});
-                    return added;
-                }, {
-                    metadata: {
-                        description: gettext('Splitting text')
-                    },
-                    success: function(ret) {
-                        canvas.setCurrentElement(utils.getElementForNode(ret), {caretTo: 'start'});
-                    }
-                });
-
-            } else {
-
-                if(!(element.parent().parent())) {
-                    return false; // top level element is unsplittable
-                }
-
-                var node = position.element.wlxmlNode,
-                    result, goto, gotoOptions;
-
-                node.document.transaction(function() {
-                    result = position.element.wlxmlNode.breakContent({offset: position.offset});
-                }, {
-                    metadata: {
-                        description: gettext('Splitting text')
-                    }
-                });
-
-                if(result.emptyText) {
-                    goto = result.emptyText;
-                    gotoOptions = {};
-                } else {
-                    goto = result.second;
-                    gotoOptions = {caretTo: 'start'};
-                }
-
-                canvas.setCurrentElement(utils.getElementForNode(goto), gotoOptions);
-            }
-        }
-    }
-});
-
-
-var selectsWholeTextElement = function(cursor) {
-    if(cursor.isSelecting() && cursor.getSelectionStart().offsetAtBeginning && cursor.getSelectionEnd().offsetAtEnd) {
-        return true;
-    }
-    return false;
-};
-
-handlers.push({keys: [KEYS.BACKSPACE, KEYS.DELETE],
-    keydown: function(event, canvas) {
-        var cursor = canvas.getCursor(),
-            position = canvas.getCursor().getPosition(),
-            element = position.element,
-            node = element ? element.wlxmlNode : null,
-            direction = 'above',
-            caretTo = 'end',
-            goto;
-
-        if(!element || !node) {
-            return;
-        }
-            
-        if(event.which === KEYS.DELETE) {
-            direction = 'below';
-            caretTo = 'start';
-        }
-
-        if(cursor.isSelecting()) {
-            event.preventDefault();
-            var start = cursor.getSelectionStart(),
-                end = cursor.getSelectionEnd();
-
-            if(direction === 'above') {
-                if(start.offsetAtBeginning) {
-                    goto = canvas.getNearestTextElement('above', start.element);
-                    caretTo = 'end';
-                } else {
-                    goto = start.element;
-                    caretTo = start.offset;
-                }
-            } else {
-                if(end.offsetAtEnd) {
-                    goto = canvas.getNearestTextElement('below', start.element);
-                    caretTo = 'start';
-                } else {
-                    goto = end.element;
-                    caretTo = 0;
-                }
-            }
-
-            canvas.wlxmlDocument.deleteText({
-                from: {
-                    node: start.element.wlxmlNode,
-                    offset: start.offset
-                },
-                to: {
-                    node: end.element.wlxmlNode,
-                    offset: end.offset
-                }
-            });
-            if(goto) {
-                canvas.setCurrentElement(goto, {caretTo: caretTo});
-            }
-            return;
-        }
-            
-        var cursorAtOperationEdge = position.offsetAtBeginning;
-        if(event.which === KEYS.DELETE) {
-            cursorAtOperationEdge = position.offsetAtEnd;
-        }
-
-        var willDeleteWholeText = function() {
-            return element.getText().length === 1 || selectsWholeTextElement(cursor);
-        };
-
-        canvas.wlxmlDocument.transaction(function() {
-            if(willDeleteWholeText()) {
-                event.preventDefault();
-                node.setText('');
-            }
-            else if(cursorAtOperationEdge) {
-                if(direction === 'below') {
-                    element = canvas.getNearestTextElement(direction, element);
-                }
-                if(element && element.wlxmlNode.getIndex() === 0) {
-                    goto = element.wlxmlNode.parent().moveUp();
-                    if(goto) {
-                        canvas.setCurrentElement(goto.node, {caretTo: goto.offset});
-                    }
-                }
-                event.preventDefault();
-            }
-        }, {
-            metadata: {
-                description: gettext('Remove text')
-            }
-        });
-    }
-});
-
 var handleKeyEvent = function(e, s) {
     keyEventHandlers.some(function(handler) {
         if(handler.applies(e, s)) {
@@ -281,7 +75,7 @@ var handleKeyEvent = function(e, s) {
 };
 // todo: whileRemoveWholetext
 var keyEventHandlers = [
-    {
+    { // ctrl+x - prevented (?)
         applies: function(e, s) {
             return e.ctrlKey &&
                 e.key === KEYS.X &&
@@ -418,7 +212,7 @@ var keyEventHandlers = [
             }
         }
     },
-    {
+    { // backspace removing the last character in a span
         applies: function(e, s) {
             return s.type === 'caret' &&
                 s.element.wlxmlNode.parent().is({tagName: 'span'}) &&
@@ -436,7 +230,7 @@ var keyEventHandlers = [
                 {caretTo: params.ret ? params.ret.previousLen : (prevTextNode ? prevTextNode.getText().length : 0)});
         }
     },
-    {
+    { // backspace/delete through an edge (behaves weirdly at spans)
         applies: function(e, s) {
             return s.type === 'caret' && (
                 (s.isAtBeginning() && e.key === KEYS.BACKSPACE) ||
@@ -449,13 +243,13 @@ var keyEventHandlers = [
             if(e.key === KEYS.BACKSPACE) {
                 direction = 'above';
                 caretTo = 'end';
-                cursorAtOperationEdge = s.isAtBeginning();
+                cursorAtOperationEdge = s.isAtBeginning(); // always true?
                 element = s.element;
             }
             else {
                 direction = 'below';
                 caretTo = 'start';
-                cursorAtOperationEdge = s.isAtEnd();
+                cursorAtOperationEdge = s.isAtEnd(); // always true?
                 element = cursorAtOperationEdge && s.canvas.getNearestTextElement(direction, s.element);
             }
 
@@ -463,6 +257,14 @@ var keyEventHandlers = [
                 return;
             }
 
+
+            var parent = element.wlxmlNode.parent();
+            if(element.wlxmlNode.getIndex() === 0 && parent.isContextRoot() && (!parent.is('item') || parent.getIndex() === 0)) {
+                // Don't even try to do anything at the edge of a context root, except for non-first items
+                // - this is a temporary solution until key events handling get refactored into something more sane.
+                return;
+            }
+
             e.preventDefault();
 
             s.canvas.wlxmlDocument.transaction(function() {
@@ -482,13 +284,13 @@ var keyEventHandlers = [
         }
     },
 
-    {
+    { // backspace/delete last character in a node - why is it needed?
         applies: function(e,s) {
             return s.type === 'caret' && s.element.getText().length === 1 && (e.key === KEYS.BACKSPACE || e.key === KEYS.DELETE);
         },
         run: function(e,s) {
             e.preventDefault();
-            e.element.wlxmlNode.setText('');
+            s.element.wlxmlNode.setText('');
             s.canvas.setCurrentElement(s.element, {caretTo: 0});
         }
     },
@@ -554,14 +356,47 @@ var keyEventHandlers = [
 
         }
     },
-    {
+    { // enter on an empty list item - creates paragraph after list
+        applies: function(e, s) {
+            var parent = s.element && s.element.wlxmlNode.parent(),
+                parentIsItem = parent && parent.is('item'),
+                itemIsOnList = parent && parent.parent() && parent.parent().is('list');
+            return s.type === 'caret' && e.key === KEYS.ENTER && s.element.isEmpty() && parentIsItem && itemIsOnList;
+        },
+        run: function(e, s) {
+            var item = s.element.wlxmlNode.parent(),
+                list = item.parent();
+            e.preventDefault();
+            s.canvas.wlxmlDocument.transaction(function() {
+                var p = list.after({tagName: 'div', attrs: {'class': 'p'}});
+                p.append({text: ''});
+                item.detach();
+                if(list.contents().length === 0) {
+                    list.detach();
+                }
+                return p;
+            }, {
+                success: function(p) {
+                    s.canvas.setCurrentElement(p);
+                }
+            });
+        }
+    },
+    { // enter - split node
         applies: function(e, s) {
             return s.type === 'caret' && e.key === KEYS.ENTER && !s.element.parent().isRootElement();
         },
         run: function(e, s) {
-            var result, goto, gotoOptions;
+            var parent = s.element.parent(),
+                children = parent.children(),
+                result, goto, gotoOptions;
             void(e);
             e.preventDefault();
+
+            if(children.length === 1 && s.element.isEmpty()) {
+                return;
+            }
+
             s.canvas.wlxmlDocument.transaction(function() {
                 result = s.element.wlxmlNode.breakContent({offset: s.offset});
             }, {
@@ -581,11 +416,32 @@ var keyEventHandlers = [
 
             s.canvas.setCurrentElement(utils.getElementForNode(goto), gotoOptions);
         }
+    },
+    { // enter - new paragraph after image/video
+        applies: function (e, s) {
+            return s.type === 'nodeSelection' && e.key === KEYS.ENTER && !s.element.isRootElement();
+        },
+        run: function (e, s) {
+            var parent = s.element.parent(),
+                children = parent.children(),
+                result, goto, gotoOptions;
+            e.preventDefault();
+
+            s.canvas.wlxmlDocument.transaction(function() {
+                result = s.element.wlxmlNode.insertNewNode();
+            }, {
+                metadata: {
+                    description: gettext('Inserting node'),
+                    fragment: s.toDocumentFragment()
+                }
+            });
+
+            s.canvas.setCurrentElement(utils.getElementForNode(result), {caretTo: 'start'});
+        }
     }
 ];
 
 return {
-    handleKey: handleKey,
     handleKeyEvent: handleKeyEvent,
     KEYS: KEYS
 };