Browse Source

script loading is done as fast as possible
unrelated to the monaco-loader

Raanan Weber 5 years ago
parent
commit
4e1c4827fc
2 changed files with 122 additions and 54 deletions
  1. 39 33
      Playground/js/main.js
  2. 83 21
      Playground/js/monacoCreator.js

+ 39 - 33
Playground/js/main.js

@@ -229,6 +229,17 @@ class Main {
         this.fpsLabel = document.getElementById("fpsLabel");
         this.scripts;
         this.previousHash = "";
+
+        // Restore BJS version if needed
+        var restoreVersionResult = true;
+        if (this.parent.settingsPG.restoreVersion() == false) {
+            // Check if there a hash in the URL
+            this.checkHash();
+            restoreVersionResult = false;
+        }
+
+        // Load scripts list
+        this.loadScriptsList(restoreVersionResult);
     }
 
     /**
@@ -266,17 +277,6 @@ class Main {
             }.bind(this)
         );
 
-        // Restore BJS version if needed
-        var restoreVersionResult = true;
-        if (this.parent.settingsPG.restoreVersion() == false) {
-            // Check if there a hash in the URL
-            this.checkHash();
-            restoreVersionResult = false;
-        }
-
-        // Load scripts list
-        this.loadScriptsList(restoreVersionResult);
-
         // -------------------- UI --------------------
         var handleRun = () => compileAndRun(this.parent, this.fpsLabel);
         var handleSave = () => this.askForSave();
@@ -497,14 +497,16 @@ class Main {
                     if (!this.checkTypescriptSupport(xhr)) return;
 
                     xhr.onreadystatechange = null;
-                    this.parent.monacoCreator.BlockEditorChange = true;
-                    this.parent.monacoCreator.JsEditor.setValue(xhr.responseText);
-                    this.parent.monacoCreator.JsEditor.setPosition({
-                        lineNumber: 0,
-                        column: 0
-                    });
-                    this.parent.monacoCreator.BlockEditorChange = false;
-                    compileAndRun(this.parent, this.fpsLabel);
+                    this.parent.monacoCreator.addOnMoncaoLoadedCallback(function () {
+                        this.parent.monacoCreator.BlockEditorChange = true;
+                        this.parent.monacoCreator.JsEditor.setValue(xhr.responseText);
+                        this.parent.monacoCreator.JsEditor.setPosition({
+                            lineNumber: 0,
+                            column: 0
+                        });
+                        this.parent.monacoCreator.BlockEditorChange = false;
+                        compileAndRun(this.parent, this.fpsLabel);
+                    }, this);
 
                     this.currentSnippetToken = null;
                 }
@@ -1074,8 +1076,8 @@ class Main {
         }
         if (pgHash) {
             var match = pgHash.match(/^(#[A-Za-z\d]*)(%23)([\d]+)$/);
-            if (match){
-                pgHash = match[1]+'#'+match[3];
+            if (match) {
+                pgHash = match[1] + '#' + match[3];
                 parent.location.hash = pgHash;
             }
             this.previousHash = pgHash;
@@ -1096,9 +1098,6 @@ class Main {
 
                         var snippet = JSON.parse(xmlHttp.responseText);
 
-                        this.parent.monacoCreator.BlockEditorChange = true;
-                        this.parent.monacoCreator.JsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
-
                         // Check if title / descr / tags are already set
                         if (snippet.name != null && snippet.name != "") {
                             this.currentSnippetTitle = snippet.name;
@@ -1127,12 +1126,18 @@ class Main {
 
                         this.updateMetadata();
 
-                        this.parent.monacoCreator.JsEditor.setPosition({
-                            lineNumber: 0,
-                            column: 0
-                        });
-                        this.parent.monacoCreator.BlockEditorChange = false;
-                        compileAndRun(this.parent, this.fpsLabel);
+                        this.parent.monacoCreator.addOnMoncaoLoadedCallback(function () {
+                            this.parent.monacoCreator.BlockEditorChange = true;
+                            this.parent.monacoCreator.JsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
+
+                            this.parent.monacoCreator.JsEditor.setPosition({
+                                lineNumber: 0,
+                                column: 0
+                            });
+                            this.parent.monacoCreator.BlockEditorChange = false;
+                            compileAndRun(this.parent, this.fpsLabel);
+                        }, this);
+
                     }
                 }
             }.bind(this);
@@ -1147,25 +1152,26 @@ class Main {
         }
     }
     updateMetadata() {
+        console.log('updating meta data');
         var selection;
 
         if (this.currentSnippetTitle) {
             selection = document.querySelector('title');
-            if(selection){
+            if (selection) {
                 selection.innerText = (this.currentSnippetTitle + " | Babylon.js Playground");
             }
         }
 
         if (this.currentSnippetDescription) {
             selection = document.querySelector('meta[name="description"]');
-            if(selection){
+            if (selection) {
                 selection.setAttribute("content", this.currentSnippetDescription + " - Babylon.js Playground");
             }
         }
 
         if (this.currentSnippetTags) {
             selection = document.querySelector('meta[name="keywords"]');
-            if(selection){
+            if (selection) {
                 selection.setAttribute("content", "babylon.js, game engine, webgl, 3d," + this.currentSnippetTags);
             }
         }

+ 83 - 21
Playground/js/monacoCreator.js

@@ -23,6 +23,13 @@ class MonacoCreator {
         this.deprecatedCandidates = [];
 
         this.compilerTriggerTimeoutID = null;
+
+        this.addOnMoncaoLoadedCallback(
+            function () {
+                this.parent.main.run();
+            },
+            this
+        );
     }
 
     // ACCESSORS
@@ -43,8 +50,8 @@ class MonacoCreator {
         return this.monacoMode;
     };
     set MonacoMode(mode) {
-        if (this.monacoMode != "javascript"
-            && this.monacoMode != "typescript")
+        if (this.monacoMode != "javascript" &&
+            this.monacoMode != "typescript")
             console.warn("Error while defining Monaco Mode");
         this.monacoMode = mode;
     };
@@ -81,12 +88,16 @@ class MonacoCreator {
         this.setupDefinitionWorker(libContent);
 
         // WARNING !!! We need the 'dev' version of Monaco, as we use monkey-patching to hook into the suggestion adapter
-        require.config({ paths: { 'vs': '/node_modules/monaco-editor/dev/vs' } });
+        require.config({
+            paths: {
+                'vs': '/node_modules/monaco-editor/dev/vs'
+            }
+        });
 
         require(['vs/editor/editor.main'], () => {
             // Setup the Monaco compilation pipeline, so we can reuse it directly for our scrpting needs
             this.setupMonacoCompilationPipeline(libContent);
-            
+
             // This is used for a vscode-like color preview for ColorX types
             this.setupMonacoColorProvider();
 
@@ -95,10 +106,38 @@ class MonacoCreator {
                 this.hookMonacoCompletionProvider(module.SuggestAdapter);
             });
 
-            this.parent.main.run();
+            this.onMonacoLoaded();
         });
     };
 
+    onMonacoLoaded() {
+        if (this.monacoLoaded) {
+            return;
+        }
+        this.onMonacoLoadedCallbacks.forEach((callbackDef) => {
+            callbackDef.func.call(callbackDef.context, this);
+        });
+        this.monacoLoaded = true;
+    }
+
+    /**
+     * This will register a new callback that will be triggered when the monaco loader is done.
+     * If the loader is already done, the function will be executed right away. 
+     * @param {Function} func the function to call when monaco is available
+     * @param {*} context The context of this function
+     */
+    addOnMoncaoLoadedCallback(func, context) {
+        this.onMonacoLoadedCallbacks = this.onMonacoLoadedCallbacks || [];
+        if (this.monacoLoaded) {
+            func.call(context, this);
+        } else {
+            this.onMonacoLoadedCallbacks.push({
+                func: func,
+                context: context
+            });
+        }
+    }
+
     // > This worker will analyze the syntaxtree and return an array of deprecated functions (but the goal is to do more in the future!)
     // We need to do this because:
     // - checking extended properties during completion is time consuming, so we need to prefilter potential candidates
@@ -109,22 +148,26 @@ class MonacoCreator {
     // We will also need this worker in the future to compute Intellicode scores for completion using dedicated attributes.
     setupDefinitionWorker(libContent) {
         this.definitionWorker = new Worker('/js/definitionWorker.js');
-        this.definitionWorker.addEventListener('message', ({ data }) => {
+        this.definitionWorker.addEventListener('message', ({
+            data
+        }) => {
             this.deprecatedCandidates = data.result;
             this.analyzeCode();
         });
-        this.definitionWorker.postMessage({ code: libContent });
+        this.definitionWorker.postMessage({
+            code: libContent
+        });
     }
 
     isDeprecatedEntry(details) {
-        return details
-            && details.tags
-            && details.tags.find(this.isDeprecatedTag);
+        return details &&
+            details.tags &&
+            details.tags.find(this.isDeprecatedTag);
     }
 
     isDeprecatedTag(tag) {
-        return tag
-            && tag.name == "deprecated";
+        return tag &&
+            tag.name == "deprecated";
     }
 
     // This will make sure that all members marked with a deprecated jsdoc attribute will be marked as such in Monaco UI
@@ -156,7 +199,10 @@ class MonacoCreator {
         for (const candidate of this.deprecatedCandidates) {
             const matches = model.findMatches(candidate, null, false, true, null, false);
             for (const match of matches) {
-                const position = { lineNumber: match.range.startLineNumber, column: match.range.startColumn };
+                const position = {
+                    lineNumber: match.range.startLineNumber,
+                    column: match.range.startColumn
+                };
                 const wordInfo = model.getWordAtPosition(position);
                 const offset = model.getOffsetAt(position);
 
@@ -184,7 +230,7 @@ class MonacoCreator {
 
         monaco.editor.setModelMarkers(model, source, markers);
     }
-    
+
     // This is our hook in the Monaco suggest adapter, we are called everytime a completion UI is displayed
     // So we need to be super fast.
     // We need the 'dev' version of Monaco, as we use monkey-patching to hook into this suggestion adapter
@@ -273,7 +319,9 @@ class MonacoCreator {
                     label = `(${converter(color.red)}, ${converter(color.green)}, ${converter(color.blue)}, ${converter(color.alpha)})`;
                 }
 
-                return [{ label: label }];
+                return [{
+                    label: label
+                }];
             },
 
             provideDocumentColors: (model) => {
@@ -378,10 +426,16 @@ class MonacoCreator {
         const main = this.parent.main;
         const monacoCreator = this;
 
-        this.diffEditor.addCommand(monaco.KeyCode.Escape, function () { main.toggleDiffEditor(monacoCreator, menuPG); });
+        this.diffEditor.addCommand(monaco.KeyCode.Escape, function () {
+            main.toggleDiffEditor(monacoCreator, menuPG);
+        });
         // Adding default VSCode bindinds for previous/next difference
-        this.diffEditor.addCommand(monaco.KeyMod.Alt | monaco.KeyCode.F5, function () { main.navigateToNext(); });
-        this.diffEditor.addCommand(monaco.KeyMod.Shift | monaco.KeyMod.Alt | monaco.KeyCode.F5, function () { main.navigateToPrevious(); });
+        this.diffEditor.addCommand(monaco.KeyMod.Alt | monaco.KeyCode.F5, function () {
+            main.navigateToNext();
+        });
+        this.diffEditor.addCommand(monaco.KeyMod.Shift | monaco.KeyMod.Alt | monaco.KeyCode.F5, function () {
+            main.navigateToPrevious();
+        });
 
         this.diffEditor.focus();
     }
@@ -418,10 +472,18 @@ class MonacoCreator {
     toggleMinimap() {
         var minimapToggle = document.getElementById("minimapToggle1280");
         if (minimapToggle.classList.contains('checked')) {
-            this.jsEditor.updateOptions({ minimap: { enabled: false } });
+            this.jsEditor.updateOptions({
+                minimap: {
+                    enabled: false
+                }
+            });
             this.parent.utils.setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-square" aria-hidden="true"></i>');
         } else {
-            this.jsEditor.updateOptions({ minimap: { enabled: true } });
+            this.jsEditor.updateOptions({
+                minimap: {
+                    enabled: true
+                }
+            });
             this.parent.utils.setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-check-square" aria-hidden="true"></i>');
         }
         minimapToggle.classList.toggle('checked');
@@ -465,4 +527,4 @@ class MonacoCreator {
             return output + stub;
         }
     };
-};
+};