Visual editor - grid toggle
[fnpeditor.git] / modules / visualEditor.js
index 38f3302..39859a8 100644 (file)
@@ -3,6 +3,7 @@ rng.modules.visualEditor = function(sandbox) {
 \r
     var view = {\r
         node: $(sandbox.getTemplate('main')()),\r
+        currentNode: null,\r
         setup: function() {\r
             var view = this;\r
 
@@ -14,37 +15,103 @@ rng.modules.visualEditor = function(sandbox) {
                 isDirty = true;\r
             });\r
 
-            this.node.on('mouseover', '.rng', function(e) { $(e.target).addClass('rng-hover')});\r
-            this.node.on('mouseout', '.rng', function(e) { $(e.target).removeClass('rng-hover')});\r
-            this.node.on('click', '.rng', function(e) {\r
+            this.node.on('mouseover', '[wlxml-tag]', function(e) { mediator.nodeHovered($(e.target));});\r
+            this.node.on('mouseout', '[wlxml-tag]', function(e) { mediator.nodeBlured($(e.target));});\r
+            this.node.on('click', '[wlxml-tag]', function(e) {\r
+                console.log('clicked node type: '+e.target.nodeType);\r
                 view._markSelected($(e.target));\r
             });\r
 \r
-            this.node.on('keyup', function(e) {\r
+            this.node.on('keyup', '#rng-visualEditor-contentWrapper', function(e) {\r
                 var anchor = $(window.getSelection().anchorNode);\r
                 if(anchor[0].nodeType === Node.TEXT_NODE)\r
                     anchor = anchor.parent();\r
-                if(!anchor.hasClass('rng'))\r
+                if(!anchor.is('[wlxml-tag]'))\r
                     return;\r
                 view._markSelected(anchor);\r
-            });
+            });\r
+            \r
+            this.node.on('keydown', '#rng-visualEditor-contentWrapper', function(e) {\r
+                if(e.which === 13) { \r
+                    e.preventDefault();\r
+                    var anchor = $(window.getSelection().anchorNode);\r
+                    if(anchor[0].nodeType === Node.TEXT_NODE)\r
+                        anchor = anchor.parent();\r
+                    var newNode = anchor.clone().empty();\r
+                    newNode.attr('id', '');\r
+                    anchor.after(newNode);\r
+                    view.selectNode(newNode);\r
+                }\r
+            });\r
+            \r
+            \r
+            var metaTable = this.metaTable = this.node.find('#rng-visualEditor-meta table');\r
+            \r
+            this.node.find('.rng-visualEditor-metaAddBtn').click(function() {\r
+                var newRow = view._addMetaRow('', '');\r
+                $(newRow.find('td div')[0]).focus();\r
+                isDirty = true;\r
+            });\r
+            \r
+            this.metaTable.on('click', '.rng-visualEditor-metaRemoveBtn', function(e) {\r
+                $(e.target).closest('tr').remove();\r
+                isDirty = true;\r
+            });\r
+            \r
+            this.metaTable.on('keydown', '[contenteditable]', function(e) {\r
+                console.log(e.which);\r
+                if(e.which === 13) { \r
+                    if($(document.activeElement).hasClass('rng-visualEditor-metaItemKey')) {\r
+                        metaTable.find('.rng-visualEditor-metaItemValue').focus();\r
+                    } else {\r
+                        var input = $('<input>');\r
+                        input.appendTo('body').focus()\r
+                        view.node.find('.rng-visualEditor-metaAddBtn').focus();\r
+                        input.remove();\r
+                    }\r
+                    e.preventDefault();\r
+                }\r
+                \r
+            });\r
+            \r
+            \r
+            var observer = new MutationObserver(function(mutations) {\r
+              mutations.forEach(function(mutation) {\r
+                if(mutation.addedNodes.length > 0) {\r
+                    console.log(mutation.addedNodes);\r
+                }\r
+                _.each(mutation.addedNodes, function(node) {\r
+                    node = $(node);\r
+                    node.parent().find('[wlxml-tag]').each(function() {\r
+                        tag = $(this);\r
+                        if(!tag.attr('id'))\r
+                            tag.attr('id', 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {var r = Math.random()*16|0,v=c=='x'?r:r&0x3|0x8;return v.toString(16);}));\r
+                    });\r
+                });\r
+              });    \r
+            });\r
+            var config = { attributes: true, childList: true, characterData: true, subtree: true };\r
+            observer.observe(this.node.find('#rng-visualEditor-contentWrapper')[0], config);\r
+            \r
+            this.gridToggled = false;
         },\r
         getMetaData: function() {\r
             var toret = {};\r
-            this.node.find('#rng-visualEditor-meta table tr').each(function() {\r
+            this.metaTable.find('tr').each(function() {\r
                 var tr = $(this);\r
-                var key = $(tr.find('td')[0]).html();\r
-                var value = $(tr.find('td input')[0]).val();\r
+                var inputs = $(this).find('td [contenteditable]');\r
+                var key = $(inputs[0]).text();\r
+                var value = $(inputs[1]).text();\r
                 toret[key] = value;\r
             });\r
             console.log(toret);\r
             return toret;\r
         },\r
         setMetaData: function(metadata) {\r
-            var table = this.node.find('#rng-visualEditor-meta table');\r
-            table.empty();\r
+            var view = this;\r
+            this.metaTable.find('tr').remove();\r
             _.each(_.keys(metadata), function(key) {    \r
-                $(sandbox.getTemplate('metaItem')({key: key, value: metadata[key]})).appendTo(table);\r
+                view._addMetaRow(key, metadata[key]);\r
             });\r
         },\r
         setBody: function(HTMLTree) {\r
@@ -54,13 +121,216 @@ rng.modules.visualEditor = function(sandbox) {
             return this.node.find('#rng-visualEditor-content').html();\r
         }, \r
         _markSelected: function(node) {\r
-            this.node.find('.rng').removeClass('rng-current');\r
+            this.node.find('.rng-current').removeClass('rng-current');\r
             node.addClass('rng-current');\r
+            this.currentNode = node;\r
+            mediator.nodeSelected(node);\r
+        },\r
+        selectNode: function(node) {\r
+            view._markSelected(node);\r
+            var range = document.createRange();\r
+            range.selectNodeContents(node[0]);\r
+            range.collapse(false);\r
+\r
+            var selection = document.getSelection();\r
+            selection.removeAllRanges()\r
+            selection.addRange(range);\r
+        },\r
+        selectNodeById: function(id) {\r
+            var node = this.node.find('#'+id);\r
+            if(node)\r
+                this.selectNode(node);\r
+        },\r
+        highlightNode: function(node) {\r
+            if(!this.gridToggled)\r
+                node.addClass('rng-hover');\r
+        },\r
+        dimNode: function(node) {\r
+            if(!this.gridToggled)\r
+                node.removeClass('rng-hover');\r
+        },\r
+        highlightNodeById: function(id) {\r
+            var node = this.node.find('#'+id);\r
+            if(node)\r
+                this.highlightNode(node);\r
+        },\r
+        dimNodeById: function(id) {\r
+            var node = this.node.find('#'+id);\r
+            if(node)\r
+                this.dimNode(node);\r
+        },\r
+        selectFirstNode: function() {\r
+            var firstNodeWithText = this.node.find('[wlxml-tag]').filter(function() {\r
+                return $(this).clone().children().remove().end().text().trim() !== '';\r
+            }).first();\r
+            var node;\r
+            if(firstNodeWithText.length)\r
+                node = $(firstNodeWithText[0])\r
+            else {\r
+                node = this.node.find('[wlxml-class|="p"]')\r
+            }\r
+            this.selectNode(node);\r
+        },\r
+        _addMetaRow: function(key, value) {\r
+            var newRow = $(sandbox.getTemplate('metaItem')({key: key || '', value: value || ''}));\r
+            newRow.appendTo(this.metaTable);\r
+            return newRow;\r
+        },\r
+        toggleGrid: function(toggle) {\r
+            this.node.find('[wlxml-tag]').toggleClass('rng-hover', toggle);\r
+            this.gridToggled = toggle;\r
         }\r
     };\r
+    \r
+    \r
+    var sideBarView = {\r
+        node: view.node.find('#rng-visualEditor-sidebar'),\r
+        setup: function() {\r
+            var view = this;\r
+            this.node.find('#rng-visualEditor-sidebarButtons a').click(function(e) {\r
+                e.preventDefault();\r
+                var target = $(e.currentTarget);\r
+                if(!target.attr('data-content-id'))\r
+                    return;\r
+                view.selectTab(target.attr('data-content-id'));\r
+            });\r
+            view.selectTab('rng-visualEditor-edit');\r
+            \r
+            view.node.on('change', '.rng-visualEditor-editPaneNodeForm select', function(e) {\r
+                var target = $(e.target);\r
+                var attr = target.attr('id').split('-')[2].split('editPane')[1].substr(0,3) === 'Tag' ? 'tag' : 'class';\r
+                mediator.getCurrentNode().attr('wlxml-'+attr, target.val());\r
+                isDirty = true;\r
+            });\r
+            \r
+            view.node.on('change', '.rng-visualEditor-editPaneSelectionForm select', function(e) {\r
+                var target = $(e.target);\r
+                var selection = window.getSelection();\r
+                if(selection.anchorNode === selection.focusNode && selection.anchorNode.nodeType === Node.TEXT_NODE) {\r
+                    var startOffset = selection.anchorOffset;\r
+                    var endOffset = selection.focusOffset;\r
+                    if(startOffset > endOffset) {\r
+                        var tmp = startOffset;\r
+                        startOffset = endOffset;\r
+                        endOffset = tmp;\r
+                    }\r
+                    var node = selection.anchorNode;\r
+                    var prefix = node.data.substr(0, startOffset);\r
+                    var suffix = node.data.substr(endOffset);\r
+                    var core = node.data.substr(startOffset, endOffset - startOffset);\r
+                    var newNode = $('<span wlxml-tag="' + target.val() + '">' + core + '</span>');\r
+                    $(node).replaceWith(newNode);\r
+                    newNode.before(prefix);\r
+                    newNode.after(suffix);\r
+                    mediator.nodeCreated(newNode);\r
+                    isDirty = true;\r
+                }\r
+            });\r
+            \r
+            view.node.on('click', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
+                var target = $(e.target);\r
+                mediator.nodeDimmedById(target.attr('data-id'));\r
+                mediator.nodeSelectedById(target.attr('data-id'));\r
+            });\r
+            \r
+            view.node.on('mouseenter', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
+                var target = $(e.target);\r
+                mediator.nodeHighlightedById(target.attr('data-id')); \r
+            });\r
+            view.node.on('mouseleave', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
+                var target = $(e.target);\r
+                mediator.nodeDimmedById(target.attr('data-id')); \r
+            });\r
+        },\r
+        selectTab: function(id) {\r
+           this.node.find('.rng-visualEditor-sidebarContentItem').hide();\r
+           this.node.find('#'+id).show();\r
+           this.node.find('#rng-visualEditor-sidebarButtons li').removeClass('active');\r
+           this.node.find('#rng-visualEditor-sidebarButtons li a[data-content-id=' + id + ']').parent().addClass('active');\r
+        \r
+        },\r
+        updateEditPane: function(node) {\r
+            var pane = this.node.find('#rng-visualEditor-edit');\r
+            pane.html( $(sandbox.getTemplate('editPane')({tag: node.attr('wlxml-tag'), klass: node.attr('wlxml-class')})));\r
+            \r
+            var parent = {\r
+                repr: node.parent().attr('wlxml-tag') + ' / ' + (node.parent().attr('wlxml-class') || '[[no class]]'),\r
+                id: node.parent().attr('id')\r
+            }\r
+            var children = [];\r
+            node.children().each(function() {\r
+                var child = $(this);\r
+                children.push({repr: child.attr('wlxml-tag') + ' / ' + (child.attr('wlxml-class') || '[[no class]]'), id: child.attr('id')});\r
+            });\r
+            var naviTemplate = sandbox.getTemplate('editPaneNavigation')({parent: parent, children: children});\r
+            pane.find('.rng-visualEditor-editPaneSurrouding > div').html($(naviTemplate));\r
+        },\r
+        highlightNode: function(id) {\r
+            var pane = this.node.find('#rng-visualEditor-edit');\r
+            pane.find('a[data-id="'+id+'"]').addClass('rng-hover');\r
+        },\r
+        dimNode: function(id) {\r
+            var pane = this.node.find('#rng-visualEditor-edit');\r
+            pane.find('a[data-id="' +id+'"]').removeClass('rng-hover');\r
+        }\r
+    }\r
+    \r
+    var toolbarView = {\r
+        node: view.node.find('#rng-visualEditor-toolbar'),\r
+        setup: function() {\r
+            var view = this;\r
+            \r
+            view.node.find('button').click(function(e) {\r
+                var btn = $(e.currentTarget);\r
+                if(btn.attr('data-btn-type') === 'toggle') {\r
+                    btn.toggleClass('active')\r
+                    mediator.toolbarButtonToggled(btn.attr('data-btn'), btn.hasClass('active'));\r
+                }\r
+            });\r
+        }\r
+    }\r
+    \r
     view.setup();\r
+    sideBarView.setup();\r
+    toolbarView.setup();\r
+    \r
+    var mediator = {\r
+        getCurrentNode: function() {\r
+            return view.currentNode;\r
+        },\r
+        nodeCreated: function(node) {\r
+            view.selectNode(node);\r
+            \r
+        },\r
+        nodeSelected: function(node) {\r
+            sideBarView.updateEditPane(node);\r
+        },\r
+        nodeSelectedById: function(id) {\r
+            view.selectNodeById(id);\r
+        },\r
+        nodeHighlightedById: function(id) {\r
+            view.highlightNodeById(id);\r
+        },\r
+        nodeDimmedById: function(id) {\r
+            view.dimNodeById(id);\r
+        },\r
+        toolbarButtonToggled: function(btn, toggle) {\r
+            if(btn === 'grid')\r
+                view.toggleGrid(toggle);\r
+        },\r
+        nodeHovered: function(node) {\r
+            view.highlightNode(node);\r
+            sideBarView.highlightNode(node.attr('id'));\r
+        },\r
+        nodeBlured: function(node) {\r
+            view.dimNode(node);\r
+            sideBarView.dimNode(node.attr('id'));\r
+        }\r
+        \r
+    }\r
     \r
     var isDirty = false;\r
+    var wasShownAlready = false;\r
     \r
     \r
     return {\r
@@ -84,6 +354,12 @@ rng.modules.visualEditor = function(sandbox) {
         },\r
         setDirty: function(dirty) {\r
             isDirty = dirty;\r
+        },\r
+        onShowed: function() {\r
+            if(!wasShownAlready) {\r
+                wasShownAlready = true;\r
+                view.selectFirstNode();\r
+            }\r
         }\r
     \r
     }\r