Browse Source

Merge pull request #2687 from blink1073/strict-null-rendermime

Strict null checks for Rendermime and Running
Ian Rose 7 years ago
parent
commit
bee6ed9e70

+ 1 - 1
packages/apputils-extension/src/palette.ts

@@ -77,7 +77,7 @@ class Palette implements ICommandPalette {
     return new DisposableDelegate(() => this._palette.removeItem(item));
   }
 
-  private _palette: CommandPalette = null;
+  private _palette: CommandPalette;
 }
 
 

+ 2 - 2
packages/apputils-extension/src/settingclientdataconnector.ts

@@ -31,10 +31,10 @@ class SettingClientDataConnector extends StateDB implements IDataConnector<ISett
   /**
    * Retrieve a saved bundle from the data connector.
    */
-  fetch(id: string): Promise<ISettingRegistry.IPlugin | null> {
+  fetch(id: string): Promise<ISettingRegistry.IPlugin | undefined> {
     return super.fetch(id).then(user => {
       if (!user && !Private.schemas[id]) {
-        return null;
+        return undefined;
       }
 
       user = user || { };

+ 7 - 5
packages/codemirror-extension/src/index.ts

@@ -192,7 +192,7 @@ function activateEditorCommands(app: JupyterLab, tracker: IEditorTracker, mainMe
             cm.setOption('theme', theme);
           }
         });
-        return settingRegistry.set(id, 'theme', theme);
+        return settingRegistry.set(id, 'theme', theme as string);
       },
       isEnabled: hasWidget,
       isToggled: args => args['theme'] === theme
@@ -211,7 +211,7 @@ function activateEditorCommands(app: JupyterLab, tracker: IEditorTracker, mainMe
             cm.setOption('keyMap', keyMap);
           }
         });
-        return settingRegistry.set(id, 'keyMap', keyMap);
+        return settingRegistry.set(id, 'keyMap', keyMap as string);
       },
       isEnabled: hasWidget,
       isToggled: args => args['keyMap'] === keyMap
@@ -221,8 +221,8 @@ function activateEditorCommands(app: JupyterLab, tracker: IEditorTracker, mainMe
       label: args => args['name'] as string,
       execute: args => {
         let mode = args['mode'] as string;
-        if (mode) {
-          let widget = tracker.currentWidget;
+        let widget = tracker.currentWidget;
+        if (mode && widget) {
           let spec = Mode.findByName(mode);
           if (spec) {
             widget.model.mimeType = spec.mime;
@@ -243,7 +243,9 @@ function activateEditorCommands(app: JupyterLab, tracker: IEditorTracker, mainMe
     });
 
     Mode.getModeInfo().sort((a, b) => {
-      return a.name.localeCompare(b.name);
+      let aName = a.name || '';
+      let bName = b.name || '';
+      return aName.localeCompare(bName);
     }).forEach(spec => {
       modeMenu.addItem({
         command: CommandIDs.changeMode,

+ 1 - 1
packages/completer/src/index.ts

@@ -61,7 +61,7 @@ namespace ICompletionManager {
     /**
      * The host editor for the completer.
      */
-    editor: CodeEditor.IEditor;
+    editor: CodeEditor.IEditor | null;
 
     /**
      * The session used by the completer to make API requests.

+ 1 - 1
packages/completer/src/widget.ts

@@ -494,7 +494,7 @@ namespace Completer {
     /**
      * The semantic parent of the completer widget, its referent editor.
      */
-    editor?: CodeEditor.IEditor;
+    editor?: CodeEditor.IEditor | null;
 
     /**
      * The model for the completer widget.

+ 7 - 7
packages/rendermime/src/latex.ts

@@ -32,10 +32,10 @@ declare var MathJax: any;
 export
 function removeMath(text: string): { text: string, math: string[] } {
   let math: string[] = []; // stores math strings for later
-  let start: number;
-  let end: string;
-  let last: number;
-  let braces: number;
+  let start: number | null = null;
+  let end: string | null = null;
+  let last: number | null = null;
+  let braces: number = 0;
   let deTilde: (text: string) => string;
 
   if (!initialized) {
@@ -70,7 +70,7 @@ function removeMath(text: string): { text: string, math: string[] } {
       //
       blocks[i] = '@@' + math.length + '@@';
       math.push(block);
-    } else if (start) {
+    } else if (start !== null) {
       //
       //  If we are in math, look for the end delimiter,
       //    but don't go past double line breaks, and
@@ -86,7 +86,7 @@ function removeMath(text: string): { text: string, math: string[] } {
           last   = null;
         }
       } else if (block.match(/\n.*\n/)) {
-        if (last) {
+        if (last !== null) {
           i = last;
           blocks = processMath(start, i, deTilde, math, blocks);
         }
@@ -119,7 +119,7 @@ function removeMath(text: string): { text: string, math: string[] } {
       }
     }
   }
-  if (last) {
+  if (start !== null && last !== null) {
     blocks = processMath(start, last, deTilde, math, blocks);
     start = null;
     end = null;

+ 14 - 13
packages/rendermime/src/renderers.ts

@@ -782,34 +782,35 @@ namespace Private {
       // breaks: true; We can't use GFM breaks as it causes problems with tables
       langPrefix: `cm-s-${CodeMirrorEditor.defaultConfig.theme} language-`,
       highlight: (code, lang, callback) => {
+        let cb = (err: Error | null, code: string) => {
+          if (callback) {
+            callback(err, code);
+          }
+          return code;
+        };
         if (!lang) {
-            // no language, no highlight
-            if (callback) {
-                callback(null, code);
-                return;
-            } else {
-                return code;
-            }
+          // no language, no highlight
+          return cb(null, code);
         }
         Mode.ensure(lang).then(spec => {
           let el = document.createElement('div');
           if (!spec) {
-              console.log(`No CodeMirror mode: ${lang}`);
-              callback(null, code);
-              return;
+            console.log(`No CodeMirror mode: ${lang}`);
+            return cb(null, code);
           }
           try {
             Mode.run(code, spec.mime, el);
-            callback(null, el.innerHTML);
+            return cb(null, el.innerHTML);
           } catch (err) {
             console.log(`Failed to highlight ${lang} code`, err);
-            callback(err, code);
+            return cb(err, code);
           }
         }).catch(err => {
           console.log(`No CodeMirror mode: ${lang}`);
           console.log(`Require CodeMirror mode error: ${err}`);
-          callback(null, code);
+          return cb(null, code);
         });
+        return code;
       }
     });
   }

+ 3 - 3
packages/rendermime/src/rendermime.ts

@@ -141,9 +141,9 @@ class RenderMime {
   clone(options: RenderMime.ICloneOptions = {}): RenderMime {
     // Create the clone.
     let clone = new RenderMime({
-      resolver: options.resolver || this.resolver,
-      sanitizer: options.sanitizer || this.sanitizer,
-      linkHandler: options.linkHandler || this.linkHandler
+      resolver: options.resolver || this.resolver || undefined,
+      sanitizer: options.sanitizer || this.sanitizer || undefined,
+      linkHandler: options.linkHandler || this.linkHandler || undefined
     });
 
     // Clone the internal state.

+ 1 - 0
packages/running/package.json

@@ -14,6 +14,7 @@
   },
   "dependencies": {
     "@jupyterlab/apputils": "^0.8.2",
+    "@jupyterlab/coreutils": "^0.8.1",
     "@jupyterlab/services": "^0.47.1",
     "@phosphor/domutils": "^1.1.1",
     "@phosphor/messaging": "^1.2.1",

+ 16 - 23
packages/running/src/index.ts

@@ -1,10 +1,6 @@
 // Copyright (c) Jupyter Development Team.
 // Distributed under the terms of the Modified BSD License.
 
-import {
-  ServiceManager, Session, TerminalSession
-} from '@jupyterlab/services';
-
 import {
   Message
 } from '@phosphor/messaging';
@@ -25,6 +21,14 @@ import {
   DOMUtils
 } from '@jupyterlab/apputils';
 
+import {
+  PathExt
+} from '@jupyterlab/coreutils';
+
+import {
+  ServiceManager, Session, TerminalSession
+} from '@jupyterlab/services';
+
 import '../style/index.css';
 
 /**
@@ -181,17 +185,6 @@ class RunningSessions extends Widget {
     return this._renderer;
   }
 
-  /**
-   * Dispose of the resources used by the widget.
-   */
-  dispose(): void {
-    this._manager = null;
-    this._runningSessions = null;
-    this._runningTerminals = null;
-    this._renderer = null;
-    super.dispose();
-  }
-
   /**
    * Refresh the widget.
    */
@@ -243,9 +236,9 @@ class RunningSessions extends Widget {
   protected onUpdateRequest(msg: Message): void {
     // Fetch common variables.
     let termSection = DOMUtils.findElement(this.node, TERMINALS_CLASS);
-    let termList = DOMUtils.findElement(termSection, LIST_CLASS);
+    let termList = DOMUtils.findElement(termSection, LIST_CLASS) as HTMLElement;
     let sessionSection = DOMUtils.findElement(this.node, SESSIONS_CLASS);
-    let sessionList = DOMUtils.findElement(sessionSection, LIST_CLASS);
+    let sessionList = DOMUtils.findElement(sessionSection, LIST_CLASS) as HTMLLIElement;
     let renderer = this._renderer;
     let specs = this._manager.specs;
 
@@ -254,10 +247,10 @@ class RunningSessions extends Widget {
 
     // Remove any excess item nodes.
     while (termList.children.length > this._runningTerminals.length) {
-      termList.removeChild(termList.firstChild);
+      termList.removeChild(termList.firstChild!);
     }
     while (sessionList.children.length > this._runningSessions.length) {
-      sessionList.removeChild(sessionList.firstChild);
+      sessionList.removeChild(sessionList.firstChild!);
     }
 
     // Add any missing item nodes.
@@ -347,7 +340,7 @@ class RunningSessions extends Widget {
     // Strip out non-file backed sessions.
     this._runningSessions = [];
     for (let session of models) {
-      let name = session.name || session.path.split('/').pop();
+      let name = session.name || PathExt.basename(session.path);
       if (name.indexOf('.') !== -1 || session.name) {
         this._runningSessions.push(session);
       }
@@ -363,8 +356,8 @@ class RunningSessions extends Widget {
     this.update();
   }
 
-  private _manager: ServiceManager.IManager = null;
-  private _renderer: RunningSessions.IRenderer = null;
+  private _manager: ServiceManager.IManager;
+  private _renderer: RunningSessions.IRenderer;
   private _runningSessions: Session.IModel[] = [];
   private _runningTerminals: TerminalSession.IModel[] = [];
   private _refreshId = -1;
@@ -662,7 +655,7 @@ namespace RunningSessions {
      */
     updateSessionNode(node: HTMLLIElement, model: Session.IModel, kernelName: string): void {
       let icon = DOMUtils.findElement(node, ITEM_ICON_CLASS);
-      let name = model.name || model.path.split('/').pop();
+      let name = model.name || PathExt.basename(model.path);
 
       if (name.indexOf('.ipynb') !== -1) {
         icon.className = `${ITEM_ICON_CLASS} ${NOTEBOOK_ICON_CLASS}`;