smartxml: Automatically rollback transaction on error thrown
[fnpeditor.git] / src / editor / modules / documentCanvas / commands.js
index 043d6b7..55de02c 100644 (file)
@@ -1,8 +1,11 @@
 define([
 define([
-'modules/documentCanvas/canvas/documentElement'
-], function(documentElement) {
+'./canvas/utils',
+'views/dialog/dialog',
+'fnpjs/datetime'
+], function(utils, Dialog, datetime) {
     
 'use strict';
     
 'use strict';
+/* globals gettext */
 
 
 var gridToggled = false;
 
 
 var gridToggled = false;
@@ -13,11 +16,27 @@ var commands = {
         this._cmds[name] = command;
     },
 
         this._cmds[name] = command;
     },
 
-    run: function(name, params, canvas) {
-        return this._cmds[name](canvas, params);
+    run: function(name, params, canvas, user) {
+        return this._cmds[name](canvas, params, user);
     }
 };
 
     }
 };
 
+commands.register('undo', function(canvas) {
+    var doc = canvas.wlxmlDocument;
+
+    doc.undo();
+});
+
+commands.register('redo', function(canvas) {
+    var doc = canvas.wlxmlDocument;
+
+    doc.redo();
+});
+
+commands.register('remove-node', function(canvas) {
+    canvas.getCurrentNodeElement().data('wlxmlNode').detach();
+});
+
 commands.register('unwrap-node', function(canvas) {
     var cursor = canvas.getCursor(),
         selectionStart = cursor.getSelectionStart(),
 commands.register('unwrap-node', function(canvas) {
     var cursor = canvas.getCursor(),
         selectionStart = cursor.getSelectionStart(),
@@ -25,14 +44,19 @@ commands.register('unwrap-node', function(canvas) {
         parent1 = selectionStart.element.parent() || undefined,
         parent2 = selectionEnd.element.parent() || undefined;
 
         parent1 = selectionStart.element.parent() || undefined,
         parent2 = selectionEnd.element.parent() || undefined;
 
-    if(canvas.list.areItemsOfTheSameList({element1: parent1, element2: parent2})) {
-        var selectionAnchor = cursor.getSelectionAnchor();
-        canvas.list.extractItems({element1: parent1, element2: parent2});
+    var selectionAnchor = cursor.getSelectionAnchor(),
+        node1 = parent1.data('wlxmlNode'),
+        node2 = parent2.data('wlxmlNode'),
+        doc = node1.document;
+    if(doc.areItemsOfSameList({node1: node1, node2: node2})) {
+        doc.extractItems({item1: node1, item2: node2});
         canvas.setCurrentElement(selectionAnchor.element, {caretTo: selectionAnchor.offset});
     } else if(!cursor.isSelecting()) {
         canvas.setCurrentElement(selectionAnchor.element, {caretTo: selectionAnchor.offset});
     } else if(!cursor.isSelecting()) {
-        var toUnwrap = cursor.getPosition().element,
-            parent = toUnwrap.unwrap();
-        canvas.setCurrentElement(parent);
+        var nodeToUnwrap = cursor.getPosition().element.data('wlxmlNode'),
+            parentNode = nodeToUnwrap.unwrap();
+        if(parentNode) {
+            canvas.setCurrentElement(utils.findCanvasElement(parentNode));
+        }
     }
 });
 
     }
 });
 
@@ -43,12 +67,17 @@ commands.register('wrap-node', function(canvas) {
         parent1 = selectionStart.element.parent() || undefined,
         parent2 = selectionEnd.element.parent() || undefined;
 
         parent1 = selectionStart.element.parent() || undefined,
         parent2 = selectionEnd.element.parent() || undefined;
 
-    if(canvas.list.areItemsOfTheSameList({element1: parent1, element2: parent2})) {
-        canvas.list.create({element1: parent1, element2: parent2});
+    var node1 = parent1.data('wlxmlNode'),
+        node2 = parent2.data('wlxmlNode'),
+        doc = node1.document;
+
+    if(doc.areItemsOfSameList({node1: node1, node2: node2})) {
+        doc.createList({node1: node1, node2: node2});
     }
 });
 
 commands.register('list', function(canvas, params) {
     }
 });
 
 commands.register('list', function(canvas, params) {
+    void(params);
     var cursor = canvas.getCursor(),
         selectionStart = cursor.getSelectionStart(),
         selectionEnd = cursor.getSelectionEnd(),
     var cursor = canvas.getCursor(),
         selectionStart = cursor.getSelectionStart(),
         selectionEnd = cursor.getSelectionEnd(),
@@ -61,73 +90,198 @@ commands.register('list', function(canvas, params) {
         return;
     }
 
         return;
     }
 
-    canvas.list.create({element1: parent1, element2: parent2});
-
+    var node1 = parent1.data('wlxmlNode'),
+        node2 = parent2.data('wlxmlNode'),
+        doc = node1.document;
+    
+    doc.createList({node1: node1, node2: node2});
     canvas.setCurrentElement(selectionFocus.element, {caretTo: selectionFocus.offset});
 });
 
 commands.register('toggle-grid', function(canvas, params) {
     canvas.setCurrentElement(selectionFocus.element, {caretTo: selectionFocus.offset});
 });
 
 commands.register('toggle-grid', function(canvas, params) {
-    canvas.doc().dom().find('[wlxml-tag]').toggleClass('rng-common-hoveredNode', params.toggle);
+    canvas.doc().dom().parent().toggleClass('grid-on', params.toggle);
     gridToggled = params.toggle;
 });
 
     gridToggled = params.toggle;
 });
 
-commands.register('newNodeRequested', function(canvas, params) {
+commands.register('newNodeRequested', function(canvas, params, user) {
     var cursor = canvas.getCursor(),
         selectionStart = cursor.getSelectionStart(),
     var cursor = canvas.getCursor(),
         selectionStart = cursor.getSelectionStart(),
-        selectionEnd = cursor.getSelectionEnd();
+        selectionEnd = cursor.getSelectionEnd(),
+        wlxmlNode, caretTo, wrapperCanvasElement;
+
+    var insertNode = function(insertion, callback) {
+        var doc = canvas.wlxmlDocument,
+            node, metadata, creator, dialog;
+
+        var execCallback = function(node) {
+            if(callback) {
+                callback(node);
+            }
+        };
+
+        if(params.wlxmlTag === 'aside' && params.wlxmlClass === 'comment') {
+            doc.startTransaction();
+            node = insertion();
+            if(user) {
+                creator = user.name;
+                if(user.email) {
+                    creator += ' (' + user.email + ')';
+                }
+            } else {
+                creator = 'anonymous';
+            }
+
+            metadata = node.getMetadata();
+            metadata.add({key: 'creator', value: creator});
+            metadata.add({key: 'date', value: datetime.currentStrfmt()});
+            doc.endTransaction();
+            execCallback(node);
+        } else if(params.wlxmlClass === 'link') {
+            dialog = Dialog.create({
+                title: gettext('Create link'),
+                executeButtonText: gettext('Apply'),
+                cancelButtonText: gettext('Cancel'),
+                fields: [
+                    {label: gettext('Link'), name: 'href', type: 'input'}
+                ]
+            });
+            dialog.on('execute', function(event) {
+                doc.startTransaction();
+                node = insertion();
+                node.setAttr('href', event.formData.href);
+                doc.endTransaction();
+                event.success();
+                execCallback(node);
+            });
+            dialog.show();
+        } else {
+            doc.startTransaction();
+            node = insertion();
+            doc.endTransaction();
+            execCallback(node);
+        }
+    };
 
     if(cursor.isSelecting()) {
         if(cursor.isSelectingSiblings()) {
             if(cursor.isSelectingWithinElement()) {
 
     if(cursor.isSelecting()) {
         if(cursor.isSelectingSiblings()) {
             if(cursor.isSelectingWithinElement()) {
-                var newElement = selectionStart.element.wrapWithNodeElement({tag: params.wlxmlTag, klass: params.wlxmlClass, start: selectionStart.offset, end: selectionEnd.offset}),
-                    caretTo = selectionStart.offset < selectionEnd.offset ? 'start' : 'end';
-                canvas.setCurrentElement(newElement.children()[0], {caretTo: caretTo});
+                wlxmlNode = selectionStart.element.data('wlxmlNode');
+                caretTo = selectionStart.offset < selectionEnd.offset ? 'start' : 'end';
+
+                insertNode(
+                    function() {
+                        return wlxmlNode.wrapWith({tagName: params.wlxmlTag, attrs: {'class': params.wlxmlClass}, start: selectionStart.offset, end: selectionEnd.offset});
+                    },
+                    function(wrapper) {
+                        wrapperCanvasElement = utils.findCanvasElement(wrapper);
+                        canvas.setCurrentElement(wrapperCanvasElement.children()[0], {caretTo: caretTo});
+                    }
+                );
             }
             else {
             }
             else {
-                var parent = selectionStart.element.parent(),
-                    caretTo = selectionStart.element.sameNode(cursor.getSelectionAnchor().element) ? 'end' : 'start';
-
-                var wrapper = canvas.wrapText({
-                    inside: parent,
-                    _with: {tag: params.wlxmlTag, klass: params.wlxmlClass},
-                    offsetStart: selectionStart.offset,
-                    offsetEnd: selectionEnd.offset,
-                    textNodeIdx: [parent.childIndex(selectionStart.element), parent.childIndex(selectionEnd.element)]
-                });
-
-                canvas.setCurrentElement(wrapper.children()[caretTo === 0 ? 0 : wrapper.children().length - 1], {caretTo: caretTo});
+                wlxmlNode = selectionStart.element.data('wlxmlNode').parent();
+                caretTo = selectionStart.element.sameNode(cursor.getSelectionAnchor().element) ? 'end' : 'start';
+
+                insertNode(
+                    function() {
+                        return wlxmlNode.wrapText({
+                            _with: {tagName: params.wlxmlTag, attrs: {'class': params.wlxmlClass}},
+                            offsetStart: selectionStart.offset,
+                            offsetEnd: selectionEnd.offset,
+                            textNodeIdx: [wlxmlNode.indexOf(selectionStart.element.data('wlxmlNode')), wlxmlNode.indexOf(selectionEnd.element.data('wlxmlNode'))] //parent.childIndex(selectionEnd.element)]
+                        });
+                    },
+                    function(wrapper) {
+                        wrapperCanvasElement = utils.findCanvasElement(wrapper);
+                        canvas.setCurrentElement(wrapperCanvasElement.children()[caretTo === 0 ? 0 : wrapperCanvasElement.children().length - 1], {caretTo: caretTo});
+                    }
+                );
             }
         } else {
             }
         } else {
-            var siblingParents = canvas.getSiblingParents({element1: selectionStart.element, element2: selectionEnd.element})
+            var node1 = selectionStart.element.data('wlxmlNode'),
+                node2 = selectionEnd.element.data('wlxmlNode'),
+                siblingParents = canvas.wlxmlDocument.getSiblingParents({node1: node1, node2: node2});
+
             if(siblingParents) {
             if(siblingParents) {
-                canvas.wrapElements({
-                    element1: siblingParents.element1,
-                    element2: siblingParents.element2,
-                    _with: {tag: params.wlxmlTag, klass: params.wlxmlClass}
-                });
+                insertNode(
+                    function() {
+                        return canvas.wlxmlDocument.wrapNodes({
+                            node1: siblingParents.node1,
+                            node2: siblingParents.node2,
+                            _with: {tagName: params.wlxmlTag, attrs: {'class': params.wlxmlClass}}
+                        });
+                    }
+                );
             }
         }
     } else if(canvas.getCurrentNodeElement()) {
             }
         }
     } else if(canvas.getCurrentNodeElement()) {
-        var el = canvas.getCurrentNodeElement().wrapWithNodeElement({tag: params.wlxmlTag, klass: params.wlxmlClass});
-        canvas.setCurrentElement(el);
-    }
-
+        wlxmlNode = canvas.getCurrentNodeElement().data('wlxmlNode');
+
+        var linkFound = [wlxmlNode].concat(wlxmlNode.parents()).some(function(node) {
+            if(node.getClass() === 'link') {
+                var dialog = Dialog.create({
+                    title: gettext('Edit link'),
+                    executeButtonText: gettext('Apply'),
+                    cancelButtonText: gettext('Cancel'),
+                    fields: [
+                        {label: gettext('Link'), name: 'href', type: 'input', initialValue: node.getAttr('href')},
+                    ]
+                });
+                dialog.on('execute', function(event) {
+                    canvas.wlxmlDocument.startTransaction();
+                    node.setAttr('href', event.formData.href);
+                    event.success();
+                    canvas.wlxmlDocument.endTransaction();
+                });
+                dialog.show();
+                return true;
+            }
+        });
+        if(linkFound) {
+            return;
+        }
 
 
+        if(params.ctrlKey) {
+            insertNode(
+                function() {
+                    return wlxmlNode.wrapWith({tagName: params.wlxmlTag, attrs: {'class': params.wlxmlClass}});
+                },
+                function(wrapper) {
+                    canvas.setCurrentElement(utils.findCanvasElement(wrapper));
+                }
+            );
+        } else {
+            insertNode(
+                function() {
+                    var node = wlxmlNode.after({tagName: params.wlxmlTag, attrs: {'class': params.wlxmlClass}});
+                    node.append({text:''});
+                    return node;
+                }, function(wrapper) {
+                    canvas.setCurrentElement(utils.findCanvasElement(wrapper));
+                }
+            );
+        }
+    }
 });
 
 commands.register('footnote', function(canvas, params) {
 });
 
 commands.register('footnote', function(canvas, params) {
+    void(params);
     var cursor = canvas.getCursor(),
         position = cursor.getPosition(),
     var cursor = canvas.getCursor(),
         position = cursor.getPosition(),
-        asideElement;
+        asideNode, asideElement, node;
         
 
     if(cursor.isSelectingWithinElement()) {
         
 
     if(cursor.isSelectingWithinElement()) {
-        asideElement = position.element.wrapWithNodeElement({tag: 'aside', klass: 'footnote', start: cursor.getSelectionStart().offset, end: cursor.getSelectionEnd().offset});
+        asideNode = position.element.data('wlxmlNode').wrapWith({tagName: 'aside', attrs:{'class': 'footnote'}, start: cursor.getSelectionStart().offset, end: cursor.getSelectionEnd().offset});
     } else {
     } else {
-        asideElement = position.element.divide({tag: 'aside', klass: 'footnote', offset: position.offset});
-        asideElement.append({text: ''});
+        node = position.element.data('wlxmlNode');
+        node.document.transaction(function() {
+            asideNode = node.divideWithElementNode({tagName: 'aside', attrs:{'class': 'footnote'}}, {offset: position.offset});
+            asideNode.append({text: ''});
+        });
     }
 
     }
 
+    asideElement = utils.findCanvasElement(asideNode);
     asideElement.toggle(true);
     canvas.setCurrentElement(asideElement);
 });
     asideElement.toggle(true);
     canvas.setCurrentElement(asideElement);
 });
@@ -137,11 +291,11 @@ commands.register('take-away-node', function(canvas) {
         element = position.element,
         nodeElement = element ? element.parent() : canvas.getCurrentNodeElement();
 
         element = position.element,
         nodeElement = element ? element.parent() : canvas.getCurrentNodeElement();
 
-    if(!nodeElement || !(nodeElement.parent()))
+    if(!nodeElement || !(nodeElement.parent())) {
         return;
         return;
+    }
 
 
-
-    var range = nodeElement.unwrapContents();
+    var range = nodeElement.data('wlxmlNode').unwrapContent();
 
     if(element) {
         var elementIsFirstChild = nodeElement.childIndex(element);
 
     if(element) {
         var elementIsFirstChild = nodeElement.childIndex(element);
@@ -149,21 +303,21 @@ commands.register('take-away-node', function(canvas) {
             canvas.setCurrentElement(element, {caretTo: position.offset});
         } else {
             if(elementIsFirstChild) {
             canvas.setCurrentElement(element, {caretTo: position.offset});
         } else {
             if(elementIsFirstChild) {
-                canvas.setCurrentElement(range.element1, {caretTo: 'end'});
+                canvas.setCurrentElement(utils.findCanvasElement(range.element1), {caretTo: 'end'});
             } else {
             } else {
-                canvas.setCurrentElement(range.element2, {caretTo: 'end'});
+                canvas.setCurrentElement(utils.findCanvasElement(range.element2), {caretTo: 'end'});
             }
         }
     } else {
             }
         }
     } else {
-        canvas.setCurrentElement(range.element1, {caretTo: 'start'});
+        canvas.setCurrentElement(utils.findCanvasElement(range.element1), {caretTo: 'start'});
     }
 
 });
 
 
 return {
     }
 
 });
 
 
 return {
-    run: function(name, params, canvas) {
-        return commands.run(name, params, canvas);
+    run: function(name, params, canvas, user) {
+        return commands.run(name, params, canvas, user);
     }
 };
 
     }
 };