smartxml: caching text nodes via expando
[fnpeditor.git] / src / editor / modules / rng / rng.js
index 59652a7..e4731cc 100644 (file)
@@ -1,93 +1,31 @@
 define([
+'./documentSummary',
+'libs/underscore',
 'fnpjs/layout',
-'fnpjs/vbox',
+'fnpjs/logging/logging',
 'views/tabs/tabs',
 'libs/text!./mainLayout.html',
 'libs/text!./editingLayout.html',
 'libs/text!./diffLayout.html',
-], function(layout, vbox, tabs, mainLayoutTemplate, visualEditingLayoutTemplate, diffLayoutTemplate) {
+], function(documentSummary, _, layout, logging, tabs, mainLayoutTemplate, visualEditingLayoutTemplate, diffLayoutTemplate) {
 
 'use strict';
 
 return function(sandbox) {
+
+    /* globals gettext */
+
+    var logger = logging.getLogger('editor.modules.rng');
     
     function addMainTab(title, slug, view) {
         views.mainTabs.addTab(title, slug, view);
     }
-    
-    var dirty = {
-        sourceEditor: false,
-        documentCanvas: false,
-        metadataEditor: false,
-    };
-    
-    var synchronizeTab = function(slug) {
-        function tabIsDirty(slug) {
-            if(slug === 'editor' && (dirty.documentCanvas || dirty.metadataEditor))
-                return true;
-            if(slug === 'sourceEditor' && dirty.sourceEditor)
-                return true;
-            return false;
-        }
-    
-        if(tabIsDirty(slug)) {
-            var reason, doc;
-            if(slug === 'sourceEditor') {
-                doc = sandbox.getModule('sourceEditor').getDocument();
-                reason = 'source_edit';
-                dirty.sourceEditor = false;
-            }
-            if(slug === 'editor') {
-                doc = dirty.documentCanvas ? sandbox.getModule('documentCanvas').getDocument() : sandbox.getModule('data').getDocument();
-                if(dirty.metadataEditor) {
-                    doc = sandbox.getModule('metadataEditor').attachMetadata(doc);
-                }
-                reason = 'edit';
-                dirty.documentCanvas = dirty.metadataEditor = false;
-            }
-            sandbox.getModule('data').commitDocument(doc, reason);
-        }
-    };
-    
+     
     var commands = {
-        highlightDocumentElement: function(element, origin) {
-            ///'nodeBreadCrumbs', 'nodeFamilyTree'
-            ['documentCanvas', ].forEach(function(moduleName) {
-                if(!origin || moduleName != origin)
-                    sandbox.getModule(moduleName).highlightElement(element);
-            });
-        },
-        dimDocumentElement: function(element, origin) {
-            //'nodeBreadCrumbs', 'nodeFamilyTree'
-            ['documentCanvas'].forEach(function(moduleName) {
-                if(!origin || moduleName != origin)
-                    sandbox.getModule(moduleName).dimElement(element);
-            });
-        },
-        jumpToDocumentElement: function(element) {
-            sandbox.getModule('documentCanvas').jumpToElement(element);
+        refreshCanvasSelection: function(selection) {
+            var fragment = selection.toDocumentFragment();
+            sandbox.getModule('documentToolbar').setDocumentFragment(fragment);
         },
-        updateCurrentNodeElement: function(nodeElement) {
-            sandbox.getModule('nodePane').setNodeElement(nodeElement);
-            sandbox.getModule('nodeFamilyTree').setElement(nodeElement);
-            sandbox.getModule('nodeBreadCrumbs').setNodeElement(nodeElement);
-        },
-        updateCurrentTextElement: function(textElement) {
-            sandbox.getModule('nodeFamilyTree').setElement(textElement);
-        },
-        resetDocument: function(document, reason) {
-            var modules = [];
-            if(reason === 'source_edit')
-                modules = ['documentCanvas', 'metadataEditor'];
-            else if (reason === 'edit')
-                modules = ['sourceEditor'];
-            else if (reason === 'revert')
-                modules = ['documentCanvas', 'metadataEditor', 'sourceEditor'];
-                
-            modules.forEach(function(moduleName) {
-                sandbox.getModule(moduleName).setDocument(document);
-            });
-        }
     };
     
 
@@ -95,25 +33,16 @@ return function(sandbox) {
         mainLayout: new layout.Layout(mainLayoutTemplate),
         mainTabs: (new tabs.View()).render(),
         visualEditing: new layout.Layout(visualEditingLayoutTemplate),
-        visualEditingSidebar: (new tabs.View({stacked: true})).render(),
-        currentNodePaneLayout: new vbox.VBox(),
         diffLayout: new layout.Layout(diffLayoutTemplate)
     };
     
-    views.visualEditing.setView('rightColumn', views.visualEditingSidebar.getAsView());
-    addMainTab('Edytor', 'editor', views.visualEditing.getAsView());
+    addMainTab(gettext('Editor'), 'editor', views.visualEditing.getAsView());
     addMainTab(gettext('Source'), 'sourceEditor',  '');
-    addMainTab('Historia', 'history', views.diffLayout.getAsView());
+    addMainTab(gettext('History'), 'history', views.diffLayout.getAsView());
     
     sandbox.getDOM().append(views.mainLayout.getAsView());
     
-    views.visualEditingSidebar.addTab({icon: 'pencil'}, 'edit', views.currentNodePaneLayout.getAsView());
-
-    views.mainTabs.on('tabSelected', function(event) {
-        if(event.prevSlug) {
-            synchronizeTab(event.prevSlug);
-        }
-    });
+    var wlxmlDocument, documentIsDirty;
     
     /* Events handling */
     
@@ -123,33 +52,73 @@ return function(sandbox) {
         ready: function() {
             addMainTab(gettext('Source'), 'sourceEditor',  sandbox.getModule('sourceEditor').getView());
             sandbox.getModule('sourceEditor').setDocument(sandbox.getModule('data').getDocument());
-        },
-        xmlChanged: function() {
-            dirty.sourceEditor = true;
-        },
-        documentSet: function() {
-            dirty.sourceEditor = false;
         }
     };
     
     eventHandlers.data = {
-        ready: function() {
+        ready: function(usingDraft, draftTimestamp, xmlValid) {
+            wlxmlDocument = sandbox.getModule('data').getDocument();
+
             views.mainLayout.setView('mainView', views.mainTabs.getAsView());
             
-            _.each(['sourceEditor', 'documentCanvas', 'documentToolbar', 'nodePane', 'metadataEditor', 'nodeFamilyTree', 'nodeBreadCrumbs', 'mainBar', 'indicator', 'documentHistory', 'diffViewer'], function(moduleName) {
+            documentSummary.init(sandbox.getConfig().documentSummaryView, wlxmlDocument);
+            documentSummary.render();
+            documentSummary.setDraftField(usingDraft ? (draftTimestamp || '???') : '-');
+            sandbox.getModule('mainBar').setSummaryView(documentSummary.dom);
+
+            sandbox.getModule('mainBar').setCommandEnabled('drop-draft', usingDraft);
+            sandbox.getModule('mainBar').setCommandEnabled('save', usingDraft);
+
+            
+            var toStart = ['sourceEditor', 'documentToolbar', 'mainBar', 'indicator', 'documentHistory', 'diffViewer', 'statusBar'];
+            if(xmlValid) {
+                toStart.push('documentCanvas');
+            }
+            _.each(toStart, function(moduleName) {
                 sandbox.getModule(moduleName).start();
             });
+            
+            documentIsDirty = false;
+            wlxmlDocument.on('change', function() {
+                documentIsDirty = true;
+                sandbox.getModule('mainBar').setCommandEnabled('save', true);
+            });
+            wlxmlDocument.on('contentSet', function() {
+                documentIsDirty = true;
+            });
         },
-        documentChanged: function(document, reason) {
-            commands.resetDocument(document, reason);
-        },
-        savingStarted: function() {
+        draftDropped: function() {
+            documentSummary.setDraftField('-');
+            sandbox.getModule('mainBar').setCommandEnabled('drop-draft', false);
             sandbox.getModule('mainBar').setCommandEnabled('save', false);
-            sandbox.getModule('indicator').showMessage(gettext('Saving...'));
         },
-        savingEnded: function(status) {
-            sandbox.getModule('mainBar').setCommandEnabled('save', true);
-            sandbox.getModule('indicator').clearMessage({message:'Dokument zapisany'});
+        savingStarted: function(what) {
+            var msg = {
+                remote: gettext('Saving document'),
+                local: gettext('Saving local copy')
+            };
+            sandbox.getModule('mainBar').setCommandEnabled('save', false);
+            sandbox.getModule('indicator').showMessage(msg[what] + '...');
+        },
+        savingEnded: function(status, what, data) {
+            void(status);
+            var msg = {
+                remote: gettext('Document saved'),
+                local: gettext('Local copy saved')
+            };
+            documentIsDirty = false;
+            
+            sandbox.getModule('indicator').clearMessage({message: msg[what]});
+            if(status === 'success' && what === 'remote') {
+                documentSummary.setDraftField('-');
+                sandbox.getModule('mainBar').setCommandEnabled('drop-draft', false);
+                sandbox.getModule('mainBar').setCommandEnabled('save', false);
+            }
+            if(what === 'local') {
+                documentSummary.setDraftField(data.timestamp);
+                sandbox.getModule('mainBar').setCommandEnabled('drop-draft', true);
+                sandbox.getModule('mainBar').setCommandEnabled('save', true);
+            }
         },
         restoringStarted: function(event) {
             sandbox.getModule('mainBar').setCommandEnabled('save', false);
@@ -161,22 +130,26 @@ return function(sandbox) {
         diffFetched: function(diff) {
             sandbox.getModule('diffViewer').setDiff(diff);
         },
-        documentReverted: function(event) {
-            commands.resetDocument(event.document, 'revert');
-            sandbox.getModule('mainBar').setCommandEnabled('save', true);
-            sandbox.getModule('indicator').clearMessage({message:'Wersja ' + event.reverted_version + ' przywrócona'});
-            sandbox.getModule('mainBar').setVersion(event.current_version);
+        documentReverted: function(version) {
+            documentIsDirty = false;
+            sandbox.getModule('indicator').clearMessage({message:'Wersja ' + version + ' przywrócona'});
         }
     };
     
     eventHandlers.mainBar = {
         ready: function() {
-            sandbox.getModule('mainBar').setVersion(sandbox.getModule('data').getDocumentVersion());
             views.mainLayout.setView('topPanel', sandbox.getModule('mainBar').getView());
         },
         'cmd.save': function() {
-            synchronizeTab(views.mainTabs.getCurrentSlug());
+            var sourceEditor = sandbox.getModule('sourceEditor');
+            if(!sourceEditor.changesCommited()) {
+                logger.debug('Source editor has uncommited changes, commiting...');
+                sourceEditor.commitChanges();
+            }
             sandbox.getModule('data').saveDocument();
+        },
+        'cmd.drop-draft': function() {
+            sandbox.getModule('data').dropDraft();
         }
     };
     
@@ -193,98 +166,30 @@ return function(sandbox) {
             sandbox.getModule('documentCanvas').setDocument(sandbox.getModule('data').getDocument());
             views.visualEditing.setView('leftColumn', sandbox.getModule('documentCanvas').getView());
         },
-        documentSet: function() {
-            dirty.documentCanvas = false;
-        },
         
-        currentTextElementSet: function(textElement) {
-            commands.updateCurrentTextElement(textElement);
-        },
-
-        currentNodeElementSet: function(nodeElement) {
-            commands.updateCurrentNodeElement(nodeElement);
-        },
-        
-        currentNodeElementChanged: function(nodeElement) {
-            commands.updateCurrentNodeElement(nodeElement);
-            dirty.documentCanvas = true;
-        },
-
-        contentChanged: function() {
-            dirty.documentCanvas = true;
-        },
-
         nodeHovered: function(canvasNode) {
             commands.highlightDocumentNode(canvasNode);
         },
         
         nodeBlured: function(canvasNode) {
             commands.dimDocumentNode(canvasNode);
-        }
-    };
-
-    eventHandlers.nodePane = {
-        ready: function() {
-            views.currentNodePaneLayout.appendView(sandbox.getModule('nodePane').getView());
-        },
-        
-        nodeElementChange: function(attr, value) {
-            sandbox.getModule('documentCanvas').modifyCurrentNodeElement(attr, value);
-        }
-    };
-    
-    eventHandlers.metadataEditor = {
-        ready: function() {
-            sandbox.getModule('metadataEditor').setDocument(sandbox.getModule('data').getDocument());
-            views.visualEditingSidebar.addTab({icon: 'info-sign'}, 'metadataEditor', sandbox.getModule('metadataEditor').getView());
-        },
-        metadataChanged: function(metadata) {
-            dirty.metadataEditor = true;
-        },
-        metadataSet: function() {
-            dirty.metadataEditor = false;
-        },
-    };
-    
-    eventHandlers.nodeFamilyTree = {
-        ready: function() {
-            views.currentNodePaneLayout.appendView(sandbox.getModule('nodeFamilyTree').getView());
-        },
-        elementEntered: function(element) {
-            commands.highlightDocumentElement(element, 'nodeFamilyTree');
-        },
-        elementLeft: function(element) {
-            commands.dimDocumentElement(element, 'nodeFamilyTree');
         },
-        elementClicked: function(element) {
-            commands.jumpToDocumentElement(element);
+
+        selectionChanged: function(selection) {
+            commands.refreshCanvasSelection(selection);
         }
     };
     
     eventHandlers.documentToolbar = {
         ready: function() {
             views.visualEditing.setView('toolbar', sandbox.getModule('documentToolbar').getView());
+            sandbox.getModule('documentToolbar').setCanvas(sandbox.getModule('documentCanvas').getCanvas());
         },
-        command: function(cmd, params) {
-            sandbox.getModule('documentCanvas').command(cmd, params);
+        actionExecuted: function(action, ret) {
+            sandbox.getModule('documentCanvas').onAfterActionExecuted(action, ret);
         }
     };
     
-    eventHandlers.nodeBreadCrumbs = {
-        ready: function() {
-            views.visualEditing.setView('statusBar', sandbox.getModule('nodeBreadCrumbs').getView());
-        },
-        elementEntered: function(element) {
-            commands.highlightDocumentElement(element, 'nodeBreadCrumbs');
-        },
-        elementLeft: function(element) {
-            commands.dimDocumentElement(element, 'nodeBreadCrumbs');
-        },
-        elementClicked: function(element) {
-            commands.jumpToDocumentElement(element);
-        }        
-    };
-    
     eventHandlers.documentHistory = {
         ready: function() {
             sandbox.getModule('documentHistory').addHistory(sandbox.getModule('data').getHistory());
@@ -293,10 +198,11 @@ return function(sandbox) {
         compare: function(ver1, ver2) {
             sandbox.getModule('data').fetchDiff(ver1, ver2);
         },
-        restoreVersion: function(event) {
-            sandbox.getModule('data').restoreVersion(event);
+        restoreVersion: function(version) {
+            sandbox.getModule('data').restoreVersion(version);
         },
         displayVersion: function(event) {
+            /* globals window */
             window.open('/' + gettext('editor') + '/' + sandbox.getModule('data').getDocumentId() + '?version=' + event.version, _.uniqueId());
         }
     };
@@ -306,19 +212,57 @@ return function(sandbox) {
             views.diffLayout.setView('right', sandbox.getModule('diffViewer').getView());
         }
     };
+
+    eventHandlers.statusBar = {
+        ready: function() {
+            views.mainLayout.setView('bottomPanel', sandbox.getModule('statusBar').getView());
+        }
+    };
+
+    eventHandlers.__all__ = {
+        actionHovered: function(action) {
+            sandbox.getModule('statusBar').showAction(action);
+        },
+        actionOff: function() {
+            sandbox.getModule('statusBar').clearAction();
+        }
+    };
+
+    window.addEventListener('beforeunload', function(event) {
+        var txt = gettext('Do you really want to exit?');
+        if(documentIsDirty) {
+            txt += ' ' + gettext('Document contains unsaved changes!');
+        }
+        event.returnValue = txt; // FF
+        return txt; // Chrome
+    });
     
     /* api */
     
     return {
         start: function() {
+            sandbox.registerActionsAppObject({
+                getUser: function() {
+                    return sandbox.getConfig().user;
+                }
+            });
             sandbox.getModule('data').start();
         },
         handleEvent: function(moduleName, eventName, args) {
-            if('')
-                wysiwigHandler.handleEvent(moduleName, eventName, args);
-            else if(eventHandlers[moduleName] && eventHandlers[moduleName][eventName]) {
+            var eventRepr = moduleName + '.' + eventName;
+            if(eventHandlers[moduleName] && eventHandlers[moduleName][eventName]) {
+                logger.debug('Handling event ' + eventRepr);
                 eventHandlers[moduleName][eventName].apply(eventHandlers, args);
+                return;
             }
+
+            if(eventHandlers.__all__[eventName]) {
+                logger.debug('Handling event ' + eventRepr);
+                eventHandlers.__all__[eventName].apply(eventHandlers.__all__, args);
+                return;
+            }
+
+            logger.warning('No event handler for ' + eventRepr);
         }
     };
 };