diff --git a/.eslintignore b/.eslintignore
index 9b4de212b811..572134dd536b 100644
--- a/.eslintignore
+++ b/.eslintignore
@@ -1,29 +1,29 @@
+node_modules
**/build
**/lib
**/node_modules
+**/mock_packages
**/static
+**/typings
+**/schemas
+**/themes
tests/**/coverage
+*.map.js
+*.bundle.js
dev_mode/index.js
-dev_mode/schemas
!dev_mode/static/index.out.js
-dev_mode/static
-dev_mode/themes
dev_mode/workspaces
docs/_build
docs/api
-examples/app/build
-examples/app/schemas
-examples/app/themes
+docs/build
examples/chrome-example-test.js
jupyterlab/chrome-test.js
jupyterlab/geckodriver
-jupyterlab/schemas
packages/extensionmanager-extension/examples/listings
-jupyterlab/staging/index.js
-jupyterlab/staging/yarn.js
-jupyterlab/themes
packages/ui-components/src/icon/iconimports.ts
+jupyterlab/staging/yarn.js
+jupyterlab/staging/index.js
# jetbrains IDE stuff
.idea/
diff --git a/.eslintrc b/.eslintrc
deleted file mode 100644
index 210d8b9cef83..000000000000
--- a/.eslintrc
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "env": {
- "browser": true,
- "node": true,
- "commonjs": true
- },
- "extends": ["eslint:recommended", "prettier"],
- "plugins": ["prettier"],
- "parserOptions": {
- "ecmaVersion": 2017,
- "sourceType": "module",
- "ecmaFeatures": {
- "modules": true,
- "jsx": true
- }
- },
- "rules": {
- "prettier/prettier": ["error", { "singleQuote": true }],
- "indent": ["error", 2],
- "linebreak-style": ["error", "unix"],
- "no-console": ["error", { "allow": ["warn", "error"] }]
- }
-}
diff --git a/.eslintrc.js b/.eslintrc.js
new file mode 100644
index 000000000000..5a7f06a28a25
--- /dev/null
+++ b/.eslintrc.js
@@ -0,0 +1,51 @@
+module.exports = {
+ env: {
+ browser: true,
+ es6: true,
+ commonjs: true
+ },
+ root: true,
+ extends: [
+ 'eslint:recommended',
+ 'plugin:@typescript-eslint/eslint-recommended',
+ 'plugin:@typescript-eslint/recommended',
+ 'prettier/@typescript-eslint',
+ 'plugin:react/recommended'
+ ],
+ parser: '@typescript-eslint/parser',
+ parserOptions: {
+ project: 'tsconfig.eslint.json'
+ },
+ plugins: ['@typescript-eslint'],
+ rules: {
+ '@typescript-eslint/no-floating-promises': ['error', { ignoreVoid: true }],
+ '@typescript-eslint/interface-name-prefix': [
+ 'error',
+ { prefixWithI: 'always' }
+ ],
+ '@typescript-eslint/no-unused-vars': ['warn', { args: 'none' }],
+ '@typescript-eslint/no-use-before-define': 'off',
+ '@typescript-eslint/camelcase': 'off',
+ '@typescript-eslint/no-explicit-any': 'off',
+ '@typescript-eslint/no-non-null-assertion': 'off',
+ '@typescript-eslint/no-namespace': 'off',
+ '@typescript-eslint/explicit-function-return-type': 'off',
+ '@typescript-eslint/ban-ts-ignore': 'warn',
+ '@typescript-eslint/no-var-requires': 'off',
+ '@typescript-eslint/no-empty-interface': 'off',
+ '@typescript-eslint/triple-slash-reference': 'warn',
+ '@typescript-eslint/no-inferrable-types': 'off',
+ 'no-inner-declarations': 'off',
+ 'no-prototype-builtins': 'off',
+ 'no-control-regex': 'warn',
+ 'no-undef': 'warn',
+ 'no-case-declarations': 'warn',
+ 'no-useless-escape': 'off',
+ 'prefer-const': 'off'
+ },
+ settings: {
+ react: {
+ version: 'detect'
+ }
+ }
+};
diff --git a/buildutils/src/add-sibling.ts b/buildutils/src/add-sibling.ts
index 4bb333ff715e..a731d40831b8 100755
--- a/buildutils/src/add-sibling.ts
+++ b/buildutils/src/add-sibling.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -20,20 +20,20 @@ import * as utils from './utils';
// Make sure we have required command line arguments.
if (process.argv.length < 3) {
- let msg = '** Must supply a target extension';
+ const msg = '** Must supply a target extension';
process.stderr.write(msg);
process.exit(1);
}
// Extract the desired git repository and repository name.
-let target = process.argv[2];
-let basePath = path.resolve('.');
+const target = process.argv[2];
+const basePath = path.resolve('.');
let packageDirName = path.basename(target);
let packagePath = path.resolve(target);
if (fs.existsSync(packagePath)) {
// Copy the package directory contents to the sibling package.
- let newPackagePath = path.join(basePath, 'packages', packageDirName);
+ const newPackagePath = path.join(basePath, 'packages', packageDirName);
fs.copySync(packagePath, newPackagePath);
packagePath = newPackagePath;
} else {
@@ -52,16 +52,16 @@ if (fs.existsSync(path.join(packagePath, 'node_modules'))) {
}
// Make sure composite is set to true in the new package.
-let packageTsconfigPath = path.join(packagePath, 'tsconfig.json');
+const packageTsconfigPath = path.join(packagePath, 'tsconfig.json');
if (fs.existsSync(packageTsconfigPath)) {
- let packageTsconfig = utils.readJSONFile(packageTsconfigPath);
+ const packageTsconfig = utils.readJSONFile(packageTsconfigPath);
packageTsconfig.compilerOptions.composite = true;
utils.writeJSONFile(packageTsconfigPath, packageTsconfig);
}
// Get the package.json of the extension.
-let pkgJSONPath = path.join(packagePath, 'package.json');
-let data = utils.readJSONFile(pkgJSONPath);
+const pkgJSONPath = path.join(packagePath, 'package.json');
+const data = utils.readJSONFile(pkgJSONPath);
if (data.private !== true) {
data.publishConfig = {};
data.publishConfig.access = 'public';
@@ -69,13 +69,13 @@ if (data.private !== true) {
}
// Add the extension path to packages/metapackage/tsconfig.json
-let tsconfigPath = path.join(
+const tsconfigPath = path.join(
basePath,
'packages',
'metapackage',
'tsconfig.json'
);
-let tsconfig = utils.readJSONFile(tsconfigPath);
+const tsconfig = utils.readJSONFile(tsconfigPath);
tsconfig.references.push({
path: path.join('..', '..', packageDirName)
});
diff --git a/buildutils/src/build.ts b/buildutils/src/build.ts
index de622b45a756..c77a1c7f49ee 100644
--- a/buildutils/src/build.ts
+++ b/buildutils/src/build.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -98,7 +98,7 @@ export namespace Build {
export function ensureAssets(
options: IEnsureOptions
): webpack.Configuration[] {
- let { output, packageNames } = options;
+ const { output, packageNames } = options;
const themeConfig: webpack.Configuration[] = [];
diff --git a/buildutils/src/bump-js-major.ts b/buildutils/src/bump-js-major.ts
index 246c20a6d07a..c41de510dd62 100644
--- a/buildutils/src/bump-js-major.ts
+++ b/buildutils/src/bump-js-major.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -16,7 +16,7 @@ export function getDeps(
lut: { [key: string]: { [key: string]: string } }
): Set {
const deps: Set = new Set();
- for (let name in lut) {
+ for (const name in lut) {
if ('@jupyterlab/' + pkgName in lut[name]) {
const otherName = name.replace('@jupyterlab/', '');
deps.add(otherName);
@@ -94,8 +94,8 @@ commander
}
if (options.dryRun) {
- console.log('Would run:');
- console.log(cmd);
+ console.debug('Would run:');
+ console.debug(cmd);
return;
}
utils.run(cmd);
diff --git a/buildutils/src/bumpversion.ts b/buildutils/src/bumpversion.ts
index 397f513e6699..d5df65ace4f6 100644
--- a/buildutils/src/bumpversion.ts
+++ b/buildutils/src/bumpversion.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -81,7 +81,7 @@ commander
if (opts.force) {
cmd += ' --yes';
}
- let oldVersion = utils.run(
+ const oldVersion = utils.run(
'git rev-parse HEAD',
{
stdio: 'pipe',
@@ -100,7 +100,7 @@ commander
utils.run(cmd);
}
- let newVersion = utils.run(
+ const newVersion = utils.run(
'git rev-parse HEAD',
{
stdio: 'pipe',
diff --git a/buildutils/src/clean-packages.ts b/buildutils/src/clean-packages.ts
index 4b7e2decaaec..02c4b7e81a3a 100644
--- a/buildutils/src/clean-packages.ts
+++ b/buildutils/src/clean-packages.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -9,11 +9,11 @@ import * as glob from 'glob';
import { readJSONFile } from './utils';
// Get all of the packages.
-let basePath = path.resolve('.');
-let baseConfig = readJSONFile(path.join(basePath, 'package.json'));
-let packageConfig = baseConfig.workspaces;
-let skipSource = process.argv.indexOf('packages') === -1;
-let skipExamples = process.argv.indexOf('examples') === -1;
+const basePath = path.resolve('.');
+const baseConfig = readJSONFile(path.join(basePath, 'package.json'));
+const packageConfig = baseConfig.workspaces;
+const skipSource = process.argv.indexOf('packages') === -1;
+const skipExamples = process.argv.indexOf('examples') === -1;
// Handle the packages
for (let i = 0; i < packageConfig.length; i++) {
@@ -23,7 +23,7 @@ for (let i = 0; i < packageConfig.length; i++) {
if (skipExamples && packageConfig[i] === 'examples/*') {
continue;
}
- let files = glob.sync(path.join(basePath, packageConfig[i]));
+ const files = glob.sync(path.join(basePath, packageConfig[i]));
for (let j = 0; j < files.length; j++) {
try {
handlePackage(files[j]);
@@ -38,18 +38,18 @@ for (let i = 0; i < packageConfig.length; i++) {
*/
function handlePackage(packagePath: string): void {
// Read in the package.json.
- let packageJSONPath = path.join(packagePath, 'package.json');
+ const packageJSONPath = path.join(packagePath, 'package.json');
let data: any;
try {
data = require(packageJSONPath);
} catch (e) {
- console.log('skipping', packagePath);
+ console.debug('skipping', packagePath);
return;
}
if (!data.scripts || !data.scripts.clean) {
return;
}
- let targets = data.scripts.clean.split('&&');
+ const targets = data.scripts.clean.split('&&');
for (let i = 0; i < targets.length; i++) {
let target = targets[i].replace('rimraf', '').trim();
target = path.join(packagePath, target);
diff --git a/buildutils/src/create-package.ts b/buildutils/src/create-package.ts
index 6749e4eb2f72..af69b871f5e5 100644
--- a/buildutils/src/create-package.ts
+++ b/buildutils/src/create-package.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -8,7 +8,7 @@ import * as inquirer from 'inquirer';
import * as path from 'path';
import * as utils from './utils';
-let questions: inquirer.Question[] = [
+const questions: inquirer.Question[] = [
{
type: 'input',
name: 'name',
@@ -23,14 +23,14 @@ let questions: inquirer.Question[] = [
void inquirer.prompt(questions).then(answers => {
let { name, description } = answers;
- let dest = path.resolve(path.join('.', 'packages', name));
+ const dest = path.resolve(path.join('.', 'packages', name));
if (fs.existsSync(dest)) {
console.error('Package already exists: ', name);
process.exit(1);
}
fs.copySync(path.resolve(path.join(__dirname, '..', 'template')), dest);
- let jsonPath = path.join(dest, 'package.json');
- let data = utils.readJSONFile(jsonPath);
+ const jsonPath = path.join(dest, 'package.json');
+ const data = utils.readJSONFile(jsonPath);
if (name.indexOf('@jupyterlab/') === -1) {
name = '@jupyterlab/' + name;
}
diff --git a/buildutils/src/create-test-package.ts b/buildutils/src/create-test-package.ts
index 4cd355985011..c5e2ea478775 100644
--- a/buildutils/src/create-test-package.ts
+++ b/buildutils/src/create-test-package.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -10,24 +10,24 @@ import * as utils from './utils';
if (require.main === module) {
// Make sure we have required command line arguments.
if (process.argv.length !== 3) {
- let msg = '** Must supply a source package name\n';
+ const msg = '** Must supply a source package name\n';
process.stderr.write(msg);
process.exit(1);
}
let name = process.argv[2];
- let pkgPath = path.resolve(path.join('.', 'packages', name));
+ const pkgPath = path.resolve(path.join('.', 'packages', name));
if (!fs.existsSync(pkgPath)) {
console.error('Package does not exist: ', name);
process.exit(1);
}
- let dest = path.resolve(`./tests/test-${name}`);
+ const dest = path.resolve(`./tests/test-${name}`);
if (fs.existsSync(dest)) {
console.error('Test package already exists:', dest);
process.exit(1);
}
fs.copySync(path.resolve(path.join(__dirname, '..', 'test-template')), dest);
- let jsonPath = path.join(dest, 'package.json');
- let data = utils.readJSONFile(jsonPath);
+ const jsonPath = path.join(dest, 'package.json');
+ const data = utils.readJSONFile(jsonPath);
if (name.indexOf('@jupyterlab/') === -1) {
name = '@jupyterlab/test-' + name;
}
diff --git a/buildutils/src/create-theme.ts b/buildutils/src/create-theme.ts
index 5fdc2fe3ea1f..c27829c32eff 100644
--- a/buildutils/src/create-theme.ts
+++ b/buildutils/src/create-theme.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -8,7 +8,7 @@ import * as inquirer from 'inquirer';
import * as path from 'path';
import * as utils from './utils';
-let questions: inquirer.Question[] = [
+const questions: inquirer.Question[] = [
{
type: 'input',
name: 'name',
@@ -58,34 +58,34 @@ export default plugin;
`;
void inquirer.prompt(questions).then(answers => {
- let { name, title, description } = answers;
- let dest = path.resolve(path.join('.', name));
+ const { name, title, description } = answers;
+ const dest = path.resolve(path.join('.', name));
if (fs.existsSync(dest)) {
console.error('Package already exists: ', name);
process.exit(1);
}
fs.copySync(path.resolve('.', 'packages', 'theme-light-extension'), dest);
- let jsonPath = path.join(dest, 'package.json');
- let data = utils.readJSONFile(jsonPath);
+ const jsonPath = path.join(dest, 'package.json');
+ const data = utils.readJSONFile(jsonPath);
data.name = name;
data.description = description;
utils.writePackageData(jsonPath, data);
// update the urls in urls.css
- let filePath = path.resolve('.', name, 'style', 'urls.css');
+ const filePath = path.resolve('.', name, 'style', 'urls.css');
let text = fs.readFileSync(filePath, 'utf8');
text = text.split('@jupyterlab/theme-light-extension').join(name);
fs.writeFileSync(filePath, text, 'utf8');
// remove lib, node_modules and static.
['lib', 'node_modules', 'static'].forEach(folder => {
- let folderPath = path.join('.', name, folder);
+ const folderPath = path.join('.', name, folder);
if (fs.existsSync(folderPath)) {
fs.removeSync(folderPath);
}
});
- let readme = `${name}\n${description}\n`;
+ const readme = `${name}\n${description}\n`;
fs.writeFileSync(path.join('.', name, 'README.md'), readme, 'utf8');
let src = template.split('{{name}}').join(name);
@@ -93,5 +93,5 @@ void inquirer.prompt(questions).then(answers => {
fs.writeFileSync(path.join('.', name, 'src', 'index.ts'), src, 'utf8');
// Signify successful complation.
- console.log(`Created new theme ${name}`);
+ console.debug(`Created new theme ${name}`);
});
diff --git a/buildutils/src/dependency-graph.ts b/buildutils/src/dependency-graph.ts
index 9a04c5eaff0d..97c222042da1 100644
--- a/buildutils/src/dependency-graph.ts
+++ b/buildutils/src/dependency-graph.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -20,8 +20,8 @@ function flat(arr: any[]) {
* Parse the yarn file at the given path.
*/
function readYarn(basePath: string = '.') {
- let file = fs.readFileSync(path.join(basePath, 'yarn.lock'), 'utf8');
- let json = lockfile.parse(file);
+ const file = fs.readFileSync(path.join(basePath, 'yarn.lock'), 'utf8');
+ const json = lockfile.parse(file);
if (json.type !== 'success') {
throw new Error('Error reading file');
@@ -44,9 +44,9 @@ function getNode(yarnData: any, pkgName: string) {
);
return undefined;
}
- let name = pkgName[0] + pkgName.slice(1).split('@')[0];
- let version = yarnData[pkgName].version;
- let pkgNode = `${name}@${version}`;
+ const name = pkgName[0] + pkgName.slice(1).split('@')[0];
+ const version = yarnData[pkgName].version;
+ const pkgNode = `${name}@${version}`;
return pkgNode;
}
@@ -65,8 +65,8 @@ function buildYarnGraph(yarnData: any): Graph {
const dependsOn: Graph = Object.create(null);
Object.keys(yarnData).forEach(pkgName => {
- let pkg = yarnData[pkgName];
- let pkgNode = getNode(yarnData, pkgName)!;
+ const pkg = yarnData[pkgName];
+ const pkgNode = getNode(yarnData, pkgName)!;
// If multiple version specs resolve to the same actual package version, we
// only want to record the dependency once.
@@ -75,10 +75,10 @@ function buildYarnGraph(yarnData: any): Graph {
}
dependsOn[pkgNode] = [];
- let deps = pkg.dependencies;
+ const deps = pkg.dependencies;
if (deps) {
Object.keys(deps).forEach(depName => {
- let depNode = getNode(yarnData, `${depName}@${deps[depName]}`)!;
+ const depNode = getNode(yarnData, `${depName}@${deps[depName]}`)!;
dependsOn[pkgNode].push(depNode);
});
}
@@ -90,11 +90,11 @@ function buildYarnGraph(yarnData: any): Graph {
* Construct a subgraph of all nodes reachable from the given nodes.
*/
function subgraph(graph: Graph, nodes: string[]): Graph {
- let sub = Object.create(null);
+ const sub = Object.create(null);
// Seed the graph
let newNodes = nodes;
while (newNodes.length > 0) {
- let old = newNodes;
+ const old = newNodes;
newNodes = [];
old.forEach(i => {
if (!(i in sub)) {
@@ -127,13 +127,13 @@ function convertDot(
distinguishRoots = false,
distinguishLeaves = false
) {
- let edges: string[][] = flat(
+ const edges: string[][] = flat(
Object.keys(g).map(a => g[a].map(b => [a, b]))
).sort();
- let nodes = Object.keys(g).sort();
+ const nodes = Object.keys(g).sort();
// let leaves = Object.keys(g).filter(i => g[i].length === 0);
// let roots = Object.keys(g).filter(i => g[i].length === 0);
- let dot = `
+ const dot = `
digraph DEPS {
${graphOptions || ''}
${nodes.map(node => `"${node}";`).join(' ')}
@@ -166,10 +166,10 @@ function main({
lumino,
topLevel
}: IMainOptions) {
- let yarnData = readYarn(path);
- let graph = buildYarnGraph(yarnData);
+ const yarnData = readYarn(path);
+ const graph = buildYarnGraph(yarnData);
- let paths: string[] = [path];
+ const paths: string[] = [path];
if (lerna !== false) {
paths.push(...utils.getLernaPaths(path).sort());
}
@@ -182,11 +182,11 @@ function main({
// Filter lerna packages if a regex was supplied
if (lernaInclude) {
- let re = new RegExp(lernaInclude);
+ const re = new RegExp(lernaInclude);
data = data.filter(d => d.name && d.name.match(re));
}
if (lernaExclude) {
- let re = new RegExp(lernaExclude);
+ const re = new RegExp(lernaExclude);
data = data.filter(d => d.name && !d.name.match(re));
}
@@ -201,13 +201,13 @@ function main({
* All dependency roots *except* other packages in this repo.
*/
const dependencyRoots: string[][] = data.map(d => {
- let roots: string[] = [];
- for (let depKind of depKinds) {
- let deps = d[depKind];
+ const roots: string[] = [];
+ for (const depKind of depKinds) {
+ const deps = d[depKind];
if (deps === undefined) {
continue;
}
- let nodes = Object.keys(deps)
+ const nodes = Object.keys(deps)
.map(i => {
// Do not get a package if it is a top-level package (and this is
// not in yarn).
@@ -222,7 +222,7 @@ function main({
});
// Find the subgraph
- let sub = subgraph(graph, flat(dependencyRoots));
+ const sub = subgraph(graph, flat(dependencyRoots));
// Add in top-level lerna packages if desired
if (topLevel) {
@@ -286,8 +286,8 @@ commander
'dot graph options (such as "ratio=0.25; concentrate=true;")'
)
.action(args => {
- let graph = main(args);
- console.log(convertDot(graph, args.graphOptions));
+ const graph = main(args);
+ console.debug(convertDot(graph, args.graphOptions));
console.error(`Nodes: ${Object.keys(graph).length}`);
});
diff --git a/buildutils/src/ensure-max-old-space.ts b/buildutils/src/ensure-max-old-space.ts
index d8c1429f1335..ead911868774 100644
--- a/buildutils/src/ensure-max-old-space.ts
+++ b/buildutils/src/ensure-max-old-space.ts
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
diff --git a/buildutils/src/ensure-package.ts b/buildutils/src/ensure-package.ts
index ae60ec6ada63..335911acc33d 100644
--- a/buildutils/src/ensure-package.ts
+++ b/buildutils/src/ensure-package.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -56,16 +56,16 @@ const ICON_CSS_CLASSES_TEMPLATE = `
export async function ensurePackage(
options: IEnsurePackageOptions
): Promise {
- let { data, pkgPath } = options;
- let deps: { [key: string]: string } = data.dependencies || {};
- let devDeps: { [key: string]: string } = data.devDependencies || {};
- let seenDeps = options.depCache || {};
- let missing = options.missing || [];
- let unused = options.unused || [];
- let messages: string[] = [];
- let locals = options.locals || {};
- let cssImports = options.cssImports || [];
- let differentVersions = options.differentVersions || [];
+ const { data, pkgPath } = options;
+ const deps: { [key: string]: string } = data.dependencies || {};
+ const devDeps: { [key: string]: string } = data.devDependencies || {};
+ const seenDeps = options.depCache || {};
+ const missing = options.missing || [];
+ const unused = options.unused || [];
+ const messages: string[] = [];
+ const locals = options.locals || {};
+ const cssImports = options.cssImports || [];
+ const differentVersions = options.differentVersions || [];
// Verify dependencies are consistent.
let promises = Object.keys(deps).map(async name => {
@@ -106,7 +106,9 @@ export async function ensurePackage(
filenames = glob.sync(path.join(pkgPath, 'src/*.ts*'));
filenames = filenames.concat(glob.sync(path.join(pkgPath, 'src/**/*.ts*')));
- if (!fs.existsSync(path.join(pkgPath, 'tsconfig.json'))) {
+ const tsConfigPath = path.join(pkgPath, 'tsconfig.json');
+
+ if (!fs.existsSync(tsConfigPath)) {
if (utils.writePackageData(path.join(pkgPath, 'package.json'), data)) {
messages.push('Updated package.json');
}
@@ -115,7 +117,7 @@ export async function ensurePackage(
// Make sure typedoc config files are consistent
if (fs.existsSync(path.join(pkgPath, 'typedoc.json'))) {
- let name = data.name.split('/');
+ const name = data.name.split('/');
utils.writeJSONFile(path.join(pkgPath, 'typedoc.json'), {
excludeNotExported: true,
mode: 'file',
@@ -128,11 +130,11 @@ export async function ensurePackage(
// Extract all of the imports from the TypeScript files.
filenames.forEach(fileName => {
- let sourceFile = ts.createSourceFile(
+ const sourceFile = ts.createSourceFile(
fileName,
fs.readFileSync(fileName).toString(),
(ts.ScriptTarget as any).ES6,
- /*setParentNodes */ true
+ /* setParentNodes */ true
);
imports = imports.concat(getImports(sourceFile));
});
@@ -148,7 +150,7 @@ export async function ensurePackage(
let names: string[] = Array.from(new Set(imports)).sort();
names = names.map(function(name) {
- let parts = name.split('/');
+ const parts = name.split('/');
if (name.indexOf('@') === 0) {
return parts[0] + '/' + parts[1];
}
@@ -211,7 +213,7 @@ export async function ensurePackage(
}
}
if (names.indexOf(name) === -1) {
- let version = data.dependencies[name];
+ const version = data.dependencies[name];
messages.push(
`Unused dependency: ${name}@${version}: remove or add to list of known unused dependencies for this package`
);
@@ -228,7 +230,7 @@ export async function ensurePackage(
}
// Handle references.
- let references: { [key: string]: string } = Object.create(null);
+ const references: { [key: string]: string } = Object.create(null);
Object.keys(deps).forEach(name => {
if (!(name in locals)) {
return;
@@ -237,14 +239,13 @@ export async function ensurePackage(
if (!fs.existsSync(path.join(target, 'tsconfig.json'))) {
return;
}
- let ref = path.relative(pkgPath, locals[name]);
+ const ref = path.relative(pkgPath, locals[name]);
references[name] = ref.split(path.sep).join('/');
});
if (
data.name.indexOf('example-') === -1 &&
Object.keys(references).length > 0
) {
- const tsConfigPath = path.join(pkgPath, 'tsconfig.json');
const tsConfigData = utils.readJSONFile(tsConfigPath);
tsConfigData.references = [];
Object.keys(references).forEach(name => {
@@ -253,6 +254,19 @@ export async function ensurePackage(
utils.writeJSONFile(tsConfigPath, tsConfigData);
}
+ // Inherit from the base tsconfig.
+ if (fs.existsSync(tsConfigPath)) {
+ const tsConfigData = utils.readJSONFile(tsConfigPath);
+ let prefix = '';
+ let dirName = pkgPath;
+ while (!fs.existsSync(path.join(dirName, 'tsconfigbase.json'))) {
+ dirName = path.dirname(dirName);
+ prefix += '../';
+ }
+ tsConfigData.extends = path.join(prefix, 'tsconfigbase');
+ utils.writeJSONFile(tsConfigPath, tsConfigData);
+ }
+
// Get a list of all the published files.
// This will not catch .js or .d.ts files if they have not been built,
// but we primarily use this to check for files that are published as-is,
@@ -275,7 +289,7 @@ export async function ensurePackage(
} else if (!schemaDir && schemas.length) {
messages.push(`Schemas found, but no schema indicated in ${pkgPath}`);
}
- for (let schema of schemas) {
+ for (const schema of schemas) {
if (!published.has(schema)) {
messages.push(`Schema ${schema} not published in ${pkgPath}`);
}
@@ -283,7 +297,7 @@ export async function ensurePackage(
// Ensure that the `style` directories match what is in the `package.json`
const styles = glob.sync(path.join(pkgPath, 'style', '**/*.*'));
- for (let style of styles) {
+ for (const style of styles) {
if (!published.has(style)) {
messages.push(`Style file ${style} not published in ${pkgPath}`);
}
@@ -356,7 +370,7 @@ export async function ensureUiComponents(
): Promise {
const funcName = 'ensureUiComponents';
const pkgName = utils.stem(pkgPath);
- let messages: string[] = [];
+ const messages: string[] = [];
const svgPaths = glob.sync(path.join(pkgPath, 'style/icons', '**/*.svg'));
@@ -364,8 +378,8 @@ export async function ensureUiComponents(
const iconSrcDir = path.join(pkgPath, 'src/icon');
// build the per-icon import code
- let _svgImportStatements: string[] = [];
- let _labiconConstructions: string[] = [];
+ const _svgImportStatements: string[] = [];
+ const _labiconConstructions: string[] = [];
svgPaths.forEach(svgPath => {
const svgName = utils.stem(svgPath);
const svgImportPath = path
@@ -408,8 +422,8 @@ export async function ensureUiComponents(
const iconCSSDir = path.join(pkgPath, 'style');
// build the per-icon import code
- let _iconCSSUrls: string[] = [];
- let _iconCSSDeclarations: string[] = [];
+ const _iconCSSUrls: string[] = [];
+ const _iconCSSDeclarations: string[] = [];
svgPaths.forEach(svgPath => {
const svgName = utils.stem(svgPath);
const urlName = 'jp-icon-' + svgName;
@@ -512,7 +526,7 @@ function ensureFile(
contents: string,
prettify: boolean = true
): string[] {
- let messages: string[] = [];
+ const messages: string[] = [];
if (!fs.existsSync(fpath)) {
// bail
@@ -551,7 +565,7 @@ function ensureFile(
* @returns An array of package names.
*/
function getImports(sourceFile: ts.SourceFile): string[] {
- let imports: string[] = [];
+ const imports: string[] = [];
handleNode(sourceFile);
function handleNode(node: any): void {
diff --git a/buildutils/src/ensure-repo.ts b/buildutils/src/ensure-repo.ts
index aa9bc56a20b3..146bdb645bfd 100644
--- a/buildutils/src/ensure-repo.ts
+++ b/buildutils/src/ensure-repo.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -22,13 +22,13 @@ import {
type Dict = { [key: string]: T };
// Data to ignore.
-let MISSING: Dict = {
+const MISSING: Dict = {
'@jupyterlab/buildutils': ['path'],
'@jupyterlab/testutils': ['fs'],
'@jupyterlab/vega5-extension': ['vega-embed']
};
-let UNUSED: Dict = {
+const UNUSED: Dict = {
'@jupyterlab/apputils': ['@types/react'],
'@jupyterlab/application': ['@fortawesome/fontawesome-free'],
'@jupyterlab/apputils-extension': ['es6-promise'],
@@ -44,9 +44,9 @@ let UNUSED: Dict = {
};
// Packages that are allowed to have differing versions
-let DIFFERENT_VERSIONS: Array = ['vega-lite', 'vega', 'vega-embed'];
+const DIFFERENT_VERSIONS: Array = ['vega-lite', 'vega', 'vega-embed'];
-let SKIP_CSS: Dict = {
+const SKIP_CSS: Dict = {
'@jupyterlab/application': ['@jupyterlab/rendermime'],
'@jupyterlab/application-extension': ['@jupyterlab/apputils'],
'@jupyterlab/completer': ['@jupyterlab/codeeditor'],
@@ -79,11 +79,11 @@ let SKIP_CSS: Dict = {
'@jupyterlab/ui-extension': ['@blueprintjs/icons']
};
-let pkgData: Dict = {};
-let pkgPaths: Dict = {};
-let pkgNames: Dict = {};
-let depCache: Dict = {};
-let locals: Dict = {};
+const pkgData: Dict = {};
+const pkgPaths: Dict = {};
+const pkgNames: Dict = {};
+const depCache: Dict = {};
+const locals: Dict = {};
/**
* Ensure the metapackage package.
@@ -91,23 +91,23 @@ let locals: Dict = {};
* @returns An array of messages for changes.
*/
function ensureMetaPackage(): string[] {
- let basePath = path.resolve('.');
- let mpPath = path.join(basePath, 'packages', 'metapackage');
- let mpJson = path.join(mpPath, 'package.json');
- let mpData = utils.readJSONFile(mpJson);
- let messages: string[] = [];
- let seen: Dict = {};
+ const basePath = path.resolve('.');
+ const mpPath = path.join(basePath, 'packages', 'metapackage');
+ const mpJson = path.join(mpPath, 'package.json');
+ const mpData = utils.readJSONFile(mpJson);
+ const messages: string[] = [];
+ const seen: Dict = {};
utils.getCorePaths().forEach(pkgPath => {
if (path.resolve(pkgPath) === path.resolve(mpPath)) {
return;
}
- let name = pkgNames[pkgPath];
+ const name = pkgNames[pkgPath];
if (!name) {
return;
}
seen[name] = true;
- let data = pkgData[name];
+ const data = pkgData[name];
let valid = true;
// Ensure it is a dependency.
@@ -144,9 +144,9 @@ function ensureMetaPackage(): string[] {
* Ensure the jupyterlab application package.
*/
function ensureJupyterlab(): string[] {
- let basePath = path.resolve('.');
- let corePath = path.join(basePath, 'dev_mode', 'package.json');
- let corePackage = utils.readJSONFile(corePath);
+ const basePath = path.resolve('.');
+ const corePath = path.join(basePath, 'dev_mode', 'package.json');
+ const corePackage = utils.readJSONFile(corePath);
corePackage.jupyterlab.extensions = {};
corePackage.jupyterlab.mimeExtensions = {};
@@ -154,11 +154,11 @@ function ensureJupyterlab(): string[] {
corePackage.dependencies = {};
corePackage.resolutions = {};
- let singletonPackages: string[] = corePackage.jupyterlab.singletonPackages;
+ const singletonPackages: string[] = corePackage.jupyterlab.singletonPackages;
const coreData = new Map();
utils.getCorePaths().forEach(pkgPath => {
- let dataPath = path.join(pkgPath, 'package.json');
+ const dataPath = path.join(pkgPath, 'package.json');
let data: any;
try {
data = utils.readJSONFile(dataPath);
@@ -191,7 +191,7 @@ function ensureJupyterlab(): string[] {
});
// At this point, each singleton should have a resolution. Check this.
- let unresolvedSingletons = singletonPackages.filter(
+ const unresolvedSingletons = singletonPackages.filter(
pkg => !(pkg in corePackage.resolutions)
);
if (unresolvedSingletons.length > 0) {
@@ -231,7 +231,7 @@ function ensureJupyterlab(): string[] {
});
utils.getLernaPaths().forEach(pkgPath => {
- let dataPath = path.join(pkgPath, 'package.json');
+ const dataPath = path.join(pkgPath, 'package.json');
let data: any;
try {
data = utils.readJSONFile(dataPath);
@@ -240,7 +240,7 @@ function ensureJupyterlab(): string[] {
}
// watch all src, build, and test files in the Jupyterlab project
- let relativePath = utils.ensureUnixPathSep(
+ const relativePath = utils.ensureUnixPathSep(
path.join('..', path.relative(basePath, pkgPath))
);
corePackage.jupyterlab.linkedPackages[data.name] = relativePath;
@@ -257,10 +257,10 @@ function ensureJupyterlab(): string[] {
* Ensure the repo integrity.
*/
export async function ensureIntegrity(): Promise {
- let messages: Dict = {};
+ const messages: Dict = {};
// Pick up all the package versions.
- let paths = utils.getLernaPaths();
+ const paths = utils.getLernaPaths();
// These two are not part of the workspaces but should be kept
// in sync.
@@ -328,7 +328,7 @@ export async function ensureIntegrity(): Promise {
// Update the metapackage.
let pkgMessages = ensureMetaPackage();
if (pkgMessages.length > 0) {
- let pkgName = '@jupyterlab/metapackage';
+ const pkgName = '@jupyterlab/metapackage';
if (!messages[pkgName]) {
messages[pkgName] = [];
}
@@ -336,18 +336,18 @@ export async function ensureIntegrity(): Promise {
}
// Validate each package.
- for (let name in locals) {
+ for (const name in locals) {
// application-top is handled elsewhere
if (name === '@jupyterlab/application-top') {
continue;
}
- let unused = UNUSED[name] || [];
+ const unused = UNUSED[name] || [];
// Allow jest-junit to be unused in the test suite.
if (name.indexOf('@jupyterlab/test-') === 0) {
unused.push('jest-junit');
}
- let options: IEnsurePackageOptions = {
+ const options: IEnsurePackageOptions = {
pkgPath: pkgPaths[name],
data: pkgData[name],
depCache,
@@ -362,7 +362,7 @@ export async function ensureIntegrity(): Promise {
options.noUnused = false;
}
- let pkgMessages = await ensurePackage(options);
+ const pkgMessages = await ensurePackage(options);
if (pkgMessages.length > 0) {
messages[name] = pkgMessages;
}
@@ -371,7 +371,7 @@ export async function ensureIntegrity(): Promise {
// ensure the icon svg imports
pkgMessages = await ensureUiComponents(pkgPaths['@jupyterlab/ui-components']);
if (pkgMessages.length > 0) {
- let pkgName = '@jupyterlab/ui-components';
+ const pkgName = '@jupyterlab/ui-components';
if (!messages[pkgName]) {
messages[pkgName] = [];
}
@@ -379,8 +379,8 @@ export async function ensureIntegrity(): Promise {
}
// Handle the top level package.
- let corePath = path.resolve('.', 'package.json');
- let coreData: any = utils.readJSONFile(corePath);
+ const corePath = path.resolve('.', 'package.json');
+ const coreData: any = utils.readJSONFile(corePath);
if (utils.writePackageData(corePath, coreData)) {
messages['top'] = ['Update package.json'];
}
@@ -393,21 +393,21 @@ export async function ensureIntegrity(): Promise {
// Handle any messages.
if (Object.keys(messages).length > 0) {
- console.log(JSON.stringify(messages, null, 2));
+ console.debug(JSON.stringify(messages, null, 2));
if (process.argv.indexOf('--force') !== -1) {
- console.log(
+ console.debug(
'\n\nPlease run `jlpm run integrity` locally and commit the changes'
);
process.exit(1);
}
utils.run('jlpm install');
- console.log('\n\nMade integrity changes!');
- console.log('Please commit the changes by running:');
- console.log('git commit -a -m "Package integrity updates"');
+ console.debug('\n\nMade integrity changes!');
+ console.debug('Please commit the changes by running:');
+ console.debug('git commit -a -m "Package integrity updates"');
return false;
}
- console.log('Repo integrity verified!');
+ console.debug('Repo integrity verified!');
return true;
}
diff --git a/buildutils/src/get-dependency.ts b/buildutils/src/get-dependency.ts
index 9f8c0000b59c..53c77b8d901f 100644
--- a/buildutils/src/get-dependency.ts
+++ b/buildutils/src/get-dependency.ts
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -20,13 +20,13 @@ let allDevDeps: string[] = [];
*/
export async function getDependency(name: string): Promise {
let version = '';
- let versions: { [key: string]: number } = {};
+ const versions: { [key: string]: number } = {};
allDeps = [];
allDevDeps = [];
utils.getLernaPaths().forEach(pkgRoot => {
// Read in the package.json.
- let packagePath = path.join(pkgRoot, 'package.json');
+ const packagePath = path.join(pkgRoot, 'package.json');
let data: any;
try {
data = utils.readJSONFile(packagePath);
@@ -39,8 +39,8 @@ export async function getDependency(name: string): Promise {
return;
}
- let deps = data.dependencies || {};
- let devDeps = data.devDependencies || {};
+ const deps = data.dependencies || {};
+ const devDeps = data.devDependencies || {};
if (deps[name]) {
allDeps.push(data.name);
if (deps[name] in versions) {
@@ -79,14 +79,14 @@ export async function getDependency(name: string): Promise {
if (require.main === module) {
// Make sure we have required command line arguments.
if (process.argv.length < 3) {
- let msg = '** Must supply a target library name\n';
+ const msg = '** Must supply a target library name\n';
process.stderr.write(msg);
process.exit(1);
}
- let name = process.argv[2];
+ const name = process.argv[2];
void getDependency(name).then(version => {
- console.log('dependency of: ', allDeps);
- console.log('devDependency of:', allDevDeps);
- console.log(`\n "${name}": "${version}"`);
+ console.debug('dependency of: ', allDeps);
+ console.debug('devDependency of:', allDevDeps);
+ console.debug(`\n "${name}": "${version}"`);
});
}
diff --git a/buildutils/src/index.ts b/buildutils/src/index.ts
index 1f9a1f95c187..dc8a1d3974fd 100644
--- a/buildutils/src/index.ts
+++ b/buildutils/src/index.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
diff --git a/buildutils/src/patch-release.ts b/buildutils/src/patch-release.ts
index 4c68b41f93a8..788901f77631 100755
--- a/buildutils/src/patch-release.ts
+++ b/buildutils/src/patch-release.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -29,7 +29,7 @@ commander
if (options.force) {
cmd += ' --yes';
}
- let oldVersion = utils.run(
+ const oldVersion = utils.run(
'git rev-parse HEAD',
{
stdio: 'pipe',
@@ -38,7 +38,7 @@ commander
true
);
utils.run(cmd);
- let newVersion = utils.run(
+ const newVersion = utils.run(
'git rev-parse HEAD',
{
stdio: 'pipe',
@@ -47,7 +47,7 @@ commander
true
);
if (oldVersion === newVersion) {
- console.log('aborting');
+ console.debug('aborting');
// lerna didn't version anything, so we assume the user aborted
throw new Error('Lerna aborted');
}
diff --git a/buildutils/src/prepublish-check.ts b/buildutils/src/prepublish-check.ts
index b39a300cca40..0e78b4be7a69 100644
--- a/buildutils/src/prepublish-check.ts
+++ b/buildutils/src/prepublish-check.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -19,7 +19,7 @@ utils.getLernaPaths().forEach(pkgPath => {
if (!pkgData.public) {
return;
}
- console.log(`Checking ${name}...`);
+ console.debug(`Checking ${name}...`);
// Make sure each glob resolves to at least one file.
pkgData.files.forEach((fGlob: string) => {
diff --git a/buildutils/src/publish.ts b/buildutils/src/publish.ts
index 0ace787d8b21..27841190bfa2 100644
--- a/buildutils/src/publish.ts
+++ b/buildutils/src/publish.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -82,12 +82,12 @@ commander
utils.run(`git tag v${curr}`);
// Prompt the user to finalize.
- console.log('*'.repeat(40));
- console.log('*'.repeat(40));
- console.log('Ready to publish!');
- console.log('Run these command when ready:');
- console.log('twine upload dist/*');
- console.log('git push origin --tags');
+ console.debug('*'.repeat(40));
+ console.debug('*'.repeat(40));
+ console.debug('Ready to publish!');
+ console.debug('Run these command when ready:');
+ console.debug('twine upload dist/*');
+ console.debug('git push origin --tags');
});
commander.parse(process.argv);
diff --git a/buildutils/src/remove-dependency.ts b/buildutils/src/remove-dependency.ts
index 04f54185d5df..a9d6dce51bcb 100755
--- a/buildutils/src/remove-dependency.ts
+++ b/buildutils/src/remove-dependency.ts
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -9,12 +9,12 @@ import * as utils from './utils';
// Make sure we have required command line arguments.
if (process.argv.length !== 3) {
- let msg = '** Must supply a library name\n';
+ const msg = '** Must supply a library name\n';
process.stderr.write(msg);
process.exit(1);
}
-let name = process.argv[2];
+const name = process.argv[2];
// Handle the packages
utils.getLernaPaths().forEach(pkgPath => {
@@ -32,13 +32,13 @@ function handlePackage(packagePath: string): void {
try {
data = utils.readJSONFile(packagePath);
} catch (e) {
- console.log('Skipping package ' + packagePath);
+ console.debug('Skipping package ' + packagePath);
return;
}
// Update dependencies as appropriate.
- for (let dtype of ['dependencies', 'devDependencies']) {
- let deps = data[dtype] || {};
+ for (const dtype of ['dependencies', 'devDependencies']) {
+ const deps = data[dtype] || {};
delete deps[name];
}
diff --git a/buildutils/src/remove-package.ts b/buildutils/src/remove-package.ts
index 20d5704b8421..ad425dd7b838 100755
--- a/buildutils/src/remove-package.ts
+++ b/buildutils/src/remove-package.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -17,19 +17,19 @@ import * as utils from './utils';
// Make sure we have required command line arguments.
if (process.argv.length < 3) {
- let msg = '** Must supply a target extension name';
+ const msg = '** Must supply a target extension name';
process.stderr.write(msg);
process.exit(1);
}
// Get the package name or path.
-let target = process.argv[2];
-let basePath = path.resolve('.');
+const target = process.argv[2];
+const basePath = path.resolve('.');
// Get the package.json of the extension.
-let packagePath = path.join(basePath, 'packages', target, 'package.json');
+const packagePath = path.join(basePath, 'packages', target, 'package.json');
if (!fs.existsSync(packagePath)) {
- let msg = '** Absolute paths for packages are not allowed.';
+ const msg = '** Absolute paths for packages are not allowed.';
process.stderr.write(msg);
process.exit(1);
}
diff --git a/buildutils/src/update-core-mode.ts b/buildutils/src/update-core-mode.ts
index 6bf7132c0495..211afef51c23 100644
--- a/buildutils/src/update-core-mode.ts
+++ b/buildutils/src/update-core-mode.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -11,7 +11,7 @@ import * as utils from './utils';
utils.run('jlpm integrity');
// Get the dev mode package.json file.
-let data = utils.readJSONFile('./dev_mode/package.json');
+const data = utils.readJSONFile('./dev_mode/package.json');
// Update the values that need to change and write to staging.
data['jupyterlab']['buildDir'] = './build';
@@ -19,7 +19,7 @@ data['jupyterlab']['outputDir'] = '..';
data['jupyterlab']['staticDir'] = '../static';
data['jupyterlab']['linkedPackages'] = {};
-let staging = './jupyterlab/staging';
+const staging = './jupyterlab/staging';
// Ensure a clean staging directory.
const keep = ['yarn.js', '.yarnrc'];
diff --git a/buildutils/src/update-dependency.ts b/buildutils/src/update-dependency.ts
index c3895bf90f45..00c4849ff039 100755
--- a/buildutils/src/update-dependency.ts
+++ b/buildutils/src/update-dependency.ts
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -11,7 +11,7 @@ import packageJson from 'package-json';
import commander from 'commander';
import semver from 'semver';
-let versionCache = new Map();
+const versionCache = new Map();
/**
* Matches a simple semver range, where the version number could be an npm tag.
@@ -49,13 +49,13 @@ async function getSpecifier(
// A tag with no sigil adopts the sigil from the current specification
if (!suggestedSigil) {
- let match = currentSpecifier.match(SEMVER_RANGE);
+ const match = currentSpecifier.match(SEMVER_RANGE);
if (match === null) {
throw Error(
`Current version range is not recognized: ${currentSpecifier}`
);
}
- let [, currentSigil] = match;
+ const [, currentSigil] = match;
if (currentSigil) {
suggestedSigil = currentSigil;
}
@@ -64,19 +64,19 @@ async function getSpecifier(
}
async function getVersion(pkg: string, specifier: string) {
- let key = JSON.stringify([pkg, specifier]);
+ const key = JSON.stringify([pkg, specifier]);
if (versionCache.has(key)) {
return versionCache.get(key);
}
if (semver.validRange(specifier) === null) {
// We have a tag, with possibly a range specifier, such as ^latest
- let match = specifier.match(SEMVER_RANGE);
+ const match = specifier.match(SEMVER_RANGE);
if (match === null) {
throw Error(`Invalid version specifier: ${specifier}`);
}
// Look up the actual version corresponding to the tag
- let { version } = await packageJson(pkg, { version: match[2] });
+ const { version } = await packageJson(pkg, { version: match[2] });
specifier = match[1] + version;
}
versionCache.set(key, specifier);
@@ -112,11 +112,11 @@ async function handleDependency(
suggestedSpecifier: string,
minimal: boolean
): Promise<{ updated: boolean; log: string[] }> {
- let log = [];
+ const log = [];
let updated = false;
- let oldRange = dependencies[dep];
- let specifier = await getSpecifier(oldRange, suggestedSpecifier);
- let newRange = await getVersion(dep, specifier);
+ const oldRange = dependencies[dep];
+ const specifier = await getSpecifier(oldRange, suggestedSpecifier);
+ const newRange = await getVersion(dep, specifier);
if (minimal && subset(newRange, oldRange)) {
log.push(`SKIPPING ${dep} ${oldRange} -> ${newRange}`);
@@ -139,7 +139,7 @@ async function handlePackage(
minimal = false
) {
let fileUpdated = false;
- let fileLog: string[] = [];
+ const fileLog: string[] = [];
// Read in the package.json.
packagePath = path.join(packagePath, 'package.json');
@@ -147,17 +147,17 @@ async function handlePackage(
try {
data = utils.readJSONFile(packagePath);
} catch (e) {
- console.log('Skipping package ' + packagePath);
+ console.debug('Skipping package ' + packagePath);
return;
}
// Update dependencies as appropriate.
- for (let dtype of ['dependencies', 'devDependencies']) {
- let deps = data[dtype] || {};
+ for (const dtype of ['dependencies', 'devDependencies']) {
+ const deps = data[dtype] || {};
if (typeof name === 'string') {
- let dep = name;
+ const dep = name;
if (dep in deps) {
- let { updated, log } = await handleDependency(
+ const { updated, log } = await handleDependency(
deps,
dep,
specifier,
@@ -169,11 +169,11 @@ async function handlePackage(
fileLog.push(...log);
}
} else {
- let keys = Object.keys(deps);
+ const keys = Object.keys(deps);
keys.sort();
- for (let dep of keys) {
+ for (const dep of keys) {
if (dep.match(name)) {
- let { updated, log } = await handleDependency(
+ const { updated, log } = await handleDependency(
deps,
dep,
specifier,
@@ -189,9 +189,9 @@ async function handlePackage(
}
if (fileLog.length > 0) {
- console.log(packagePath);
- console.log(fileLog.join('\n'));
- console.log();
+ console.debug(packagePath);
+ console.debug(fileLog.join('\n'));
+ console.debug();
}
// Write the file back to disk.
@@ -211,15 +211,15 @@ commander
.arguments(' [versionspec]')
.action(
async (name: string | RegExp, version: string = '^latest', args: any) => {
- let basePath = path.resolve(args.path || '.');
- let pkg = args.regex ? new RegExp(name) : name;
+ const basePath = path.resolve(args.path || '.');
+ const pkg = args.regex ? new RegExp(name) : name;
if (args.lerna) {
- let paths = utils.getLernaPaths(basePath).sort();
+ const paths = utils.getLernaPaths(basePath).sort();
// We use a loop instead of Promise.all so that the output is in
// alphabetical order.
- for (let pkgPath of paths) {
+ for (const pkgPath of paths) {
await handlePackage(pkg, version, pkgPath, args.dryRun, args.minimal);
}
}
@@ -228,7 +228,7 @@ commander
);
commander.on('--help', function() {
- console.log(`
+ console.debug(`
Examples
--------
diff --git a/buildutils/src/update-dist-tag.ts b/buildutils/src/update-dist-tag.ts
index b57d3e96352f..719daff97802 100755
--- a/buildutils/src/update-dist-tag.ts
+++ b/buildutils/src/update-dist-tag.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -21,7 +21,7 @@ export async function handlePackage(packagePath: string): Promise {
try {
data = utils.readJSONFile(packagePath);
} catch (e) {
- console.log('Skipping package ' + packagePath);
+ console.debug('Skipping package ' + packagePath);
return cmds;
}
@@ -31,14 +31,14 @@ export async function handlePackage(packagePath: string): Promise {
const pkg = data.name;
- let npmData = await packageJson(pkg, { allVersions: true });
- let versions = Object.keys(npmData.versions).sort(semver.rcompare);
- let tags = npmData['dist-tags'];
+ const npmData = await packageJson(pkg, { allVersions: true });
+ const versions = Object.keys(npmData.versions).sort(semver.rcompare);
+ const tags = npmData['dist-tags'];
// Go through the versions. The latest prerelease is 'next', the latest
// non-prerelease should be 'stable'.
- let next = semver.prerelease(versions[0]) ? versions[0] : undefined;
- let latest = versions.find(i => !semver.prerelease(i));
+ const next = semver.prerelease(versions[0]) ? versions[0] : undefined;
+ const latest = versions.find(i => !semver.prerelease(i));
if (latest && latest !== tags.latest) {
cmds.push(`npm dist-tag add ${pkg}@${latest} latest`);
@@ -68,7 +68,7 @@ points to the latest prerelease after it.`
.option('--lerna', 'Update dist-tags in all lerna packages')
.option('--path [path]', 'Path to package or monorepo to update')
.action(async (args: any) => {
- let basePath = path.resolve(args.path || '.');
+ const basePath = path.resolve(args.path || '.');
let cmds: string[][] = [];
let paths: string[] = [];
if (args.lerna) {
@@ -76,9 +76,9 @@ points to the latest prerelease after it.`
cmds = await Promise.all(paths.map(handlePackage));
}
cmds.push(await handlePackage(basePath));
- let out = flatten(cmds).join('\n');
+ const out = flatten(cmds).join('\n');
if (out) {
- console.log(out);
+ console.debug(out);
}
});
diff --git a/buildutils/src/utils.ts b/buildutils/src/utils.ts
index 8264c998f7dd..d41f937bcf8c 100644
--- a/buildutils/src/utils.ts
+++ b/buildutils/src/utils.ts
@@ -33,7 +33,7 @@ export function getLernaPaths(basePath = '.'): string[] {
throw e;
}
let paths: string[] = [];
- for (let config of packages) {
+ for (const config of packages) {
paths = paths.concat(glob.sync(path.join(basePath, config)));
}
return paths.filter(pkgPath => {
@@ -45,7 +45,7 @@ export function getLernaPaths(basePath = '.'): string[] {
* Get all of the core package paths.
*/
export function getCorePaths(): string[] {
- let spec = path.resolve(path.join('.', 'packages', '*'));
+ const spec = path.resolve(path.join('.', 'packages', '*'));
return glob.sync(spec);
}
@@ -59,8 +59,8 @@ export function getCorePaths(): string[] {
* @returns Whether the file has changed.
*/
export function writePackageData(pkgJsonPath: string, data: any): boolean {
- let text = JSON.stringify(sortPackageJson(data), null, 2) + '\n';
- let orig = fs
+ const text = JSON.stringify(sortPackageJson(data), null, 2) + '\n';
+ const orig = fs
.readFileSync(pkgJsonPath, 'utf8')
.split('\r\n')
.join('\n');
@@ -100,7 +100,7 @@ export function writeJSONFile(filePath: string, data: any): boolean {
}, {})
: value;
}
- let text = JSON.stringify(data, sortObjByKey(data), 2) + '\n';
+ const text = JSON.stringify(data, sortObjByKey(data), 2) + '\n';
let orig = {};
try {
orig = readJSONFile(filePath);
@@ -150,8 +150,8 @@ export function fromTemplate(
// try to match the indentation level of the {{var}} in the input template.
templ = templ.split(`{{${key}}}`).reduce((acc, cur) => {
// Regex: 0 or more non-newline whitespaces followed by end of string
- let indentRe = acc.match(/([^\S\r\n]*).*$/);
- let indent = indentRe ? indentRe[1] : '';
+ const indentRe = acc.match(/([^\S\r\n]*).*$/);
+ const indent = indentRe ? indentRe[1] : '';
return acc + val.split('\n').join('\n' + indent) + cur;
});
} else {
@@ -198,7 +198,7 @@ export function prebump() {
run('python -m pip install bump2version');
// Make sure we start in a clean git state.
- let status = run('git status --porcelain', {
+ const status = run('git status --porcelain', {
stdio: 'pipe',
encoding: 'utf8'
});
@@ -220,8 +220,8 @@ export function postbump() {
const curr = getPythonVersion();
// Update the dev mode version.
- let filePath = path.resolve(path.join('.', 'dev_mode', 'package.json'));
- let data = readJSONFile(filePath);
+ const filePath = path.resolve(path.join('.', 'dev_mode', 'package.json'));
+ const data = readJSONFile(filePath);
data.jupyterlab.version = curr;
writeJSONFile(filePath, data);
@@ -242,7 +242,7 @@ export function run(
options = options || {};
options['stdio'] = options.stdio || 'inherit';
if (!quiet) {
- console.log('>', cmd);
+ console.debug('>', cmd);
}
const value = childProcess.execSync(cmd, options);
if (value === null) {
diff --git a/buildutils/src/webpack-plugins.ts b/buildutils/src/webpack-plugins.ts
index b91275a9a696..f2d4d2e84aba 100644
--- a/buildutils/src/webpack-plugins.ts
+++ b/buildutils/src/webpack-plugins.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
diff --git a/buildutils/template/src/index.ts b/buildutils/template/src/index.ts
index 215ca5d2e743..2a221b25319e 100644
--- a/buildutils/template/src/index.ts
+++ b/buildutils/template/src/index.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
diff --git a/dev_mode/webpack.config.js b/dev_mode/webpack.config.js
index 870fa123be1a..f2a39629ef5e 100644
--- a/dev_mode/webpack.config.js
+++ b/dev_mode/webpack.config.js
@@ -1,47 +1,49 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
-var plib = require('path');
-var fs = require('fs-extra');
-var Handlebars = require('handlebars');
-var HtmlWebpackPlugin = require('html-webpack-plugin');
-var webpack = require('webpack');
-var BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
+const plib = require('path');
+const fs = require('fs-extra');
+const Handlebars = require('handlebars');
+const HtmlWebpackPlugin = require('html-webpack-plugin');
+const webpack = require('webpack');
+const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
.BundleAnalyzerPlugin;
-var Build = require('@jupyterlab/buildutils').Build;
-var WPPlugin = require('@jupyterlab/buildutils').WPPlugin;
-var package_data = require('./package.json');
+const Build = require('@jupyterlab/buildutils').Build;
+const WPPlugin = require('@jupyterlab/buildutils').WPPlugin;
+const package_data = require('./package.json');
// Handle the extensions.
-var jlab = package_data.jupyterlab;
-var extensions = jlab.extensions;
-var mimeExtensions = jlab.mimeExtensions;
-var packageNames = Object.keys(mimeExtensions).concat(Object.keys(extensions));
+const jlab = package_data.jupyterlab;
+const extensions = jlab.extensions;
+const mimeExtensions = jlab.mimeExtensions;
+const packageNames = Object.keys(mimeExtensions).concat(
+ Object.keys(extensions)
+);
// Ensure a clear build directory.
-var buildDir = plib.resolve(jlab.buildDir);
+const buildDir = plib.resolve(jlab.buildDir);
if (fs.existsSync(buildDir)) {
fs.removeSync(buildDir);
}
fs.ensureDirSync(buildDir);
// Build the assets
-var extraConfig = Build.ensureAssets({
+const extraConfig = Build.ensureAssets({
packageNames: packageNames,
output: jlab.outputDir
});
// Create the entry point file.
-var source = fs.readFileSync('index.js').toString();
-var template = Handlebars.compile(source);
-var data = {
+const source = fs.readFileSync('index.js').toString();
+const template = Handlebars.compile(source);
+const data = {
jupyterlab_extensions: extensions,
jupyterlab_mime_extensions: mimeExtensions
};
-var result = template(data);
+const result = template(data);
fs.writeFileSync(plib.join(buildDir, 'index.out.js'), result);
fs.copySync('./package.json', plib.join(buildDir, 'package.json'));
@@ -51,16 +53,18 @@ fs.copySync(
);
// Set up variables for the watch mode ignore plugins
-let watched = {};
-let ignoreCache = Object.create(null);
+const watched = {};
+const ignoreCache = Object.create(null);
Object.keys(jlab.linkedPackages).forEach(function(name) {
- if (name in watched) return;
+ if (name in watched) {
+ return;
+ }
const localPkgPath = require.resolve(plib.join(name, 'package.json'));
watched[name] = plib.dirname(localPkgPath);
});
// Set up source-map-loader to look in watched lib dirs
-let sourceMapRes = Object.values(watched).reduce((res, name) => {
+const sourceMapRes = Object.values(watched).reduce((res, name) => {
res.push(new RegExp(name + '/lib'));
return res;
}, []);
diff --git a/dev_mode/webpack.prod.config.js b/dev_mode/webpack.prod.config.js
index a48980bcdaeb..4d16ccedd500 100644
--- a/dev_mode/webpack.prod.config.js
+++ b/dev_mode/webpack.prod.config.js
@@ -1,5 +1,5 @@
-var merge = require('webpack-merge');
-var config = require('./webpack.config');
+const merge = require('webpack-merge');
+const config = require('./webpack.config');
config[0] = merge(config[0], {
mode: 'production',
diff --git a/dev_mode/webpack.prod.minimize.config.js b/dev_mode/webpack.prod.minimize.config.js
index 9f91ed057c35..35be13f60cf9 100644
--- a/dev_mode/webpack.prod.minimize.config.js
+++ b/dev_mode/webpack.prod.minimize.config.js
@@ -1,6 +1,6 @@
const TerserPlugin = require('terser-webpack-plugin');
-var merge = require('webpack-merge');
-var config = require('./webpack.config');
+const merge = require('webpack-merge');
+const config = require('./webpack.config');
config[0] = merge(config[0], {
mode: 'production',
diff --git a/dev_mode/webpack.prod.release.config.js b/dev_mode/webpack.prod.release.config.js
index fee3567efb08..57cd5b91367f 100644
--- a/dev_mode/webpack.prod.release.config.js
+++ b/dev_mode/webpack.prod.release.config.js
@@ -1,5 +1,5 @@
-var merge = require('webpack-merge');
-var config = require('./webpack.prod.minimize.config');
+const merge = require('webpack-merge');
+const config = require('./webpack.prod.minimize.config');
config[0] = merge(config[0], {
// Turn off source maps
diff --git a/docs/scripts/graph-dependencies.js b/docs/scripts/graph-dependencies.js
index 4da89eae4e5f..67127e210a6c 100644
--- a/docs/scripts/graph-dependencies.js
+++ b/docs/scripts/graph-dependencies.js
@@ -1,23 +1,23 @@
-var childProcess = require('child_process');
-var fs = require('fs-extra');
-var glob = require('glob');
-var path = require('path');
-var url = require('url');
+const childProcess = require('child_process');
+const fs = require('fs-extra');
+const glob = require('glob');
+const path = require('path');
+const url = require('url');
-var basePath = path.resolve('..');
-var baseUrl = 'https://github.com/jupyterlab/jupyterlab/tree/master/packages';
-var packages = glob.sync(path.join(basePath, 'packages/*'));
+const basePath = path.resolve('..');
+const baseUrl = 'https://github.com/jupyterlab/jupyterlab/tree/master/packages';
+const packages = glob.sync(path.join(basePath, 'packages/*'));
// Begin the graph specification
-var text = 'digraph G {\n';
+let text = 'digraph G {\n';
text += 'ratio = 0.6;\n';
text += 'rankdir=LR;\n';
packages.forEach(function(packagePath) {
// Load the package.json data.
- var dataPath = path.join(packagePath, 'package.json');
+ const dataPath = path.join(packagePath, 'package.json');
try {
- var data = require(dataPath);
+ const data = require(dataPath); // eslint-disable-line @typescript-eslint/no-unused-vars
} catch (e) {
return;
}
@@ -44,14 +44,14 @@ packages.forEach(function(packagePath) {
}
// Construct a URL to the package on GitHub.
- var Url = url.resolve(baseUrl, 'packages/' + path.basename(packagePath));
+ const Url = url.resolve(baseUrl, 'packages/' + path.basename(packagePath));
// Remove the '@jupyterlab' part of the name.
- var name = '"' + data.name.split('/')[1] + '"';
+ const name = '"' + data.name.split('/')[1] + '"';
text += name + '[URL="' + Url + '"];\n';
- var deps = data.dependencies || [];
- for (var dep in deps) {
+ const deps = data.dependencies || [];
+ for (let dep in deps) {
// Don't include non-jupyterlab dependencies.
if (dep.indexOf('@jupyterlab') === -1) {
continue;
@@ -66,4 +66,4 @@ fs.writeFileSync('./dependencies.gv', text);
childProcess.execSync(
'cat dependencies.gv | tred | dot -Tsvg -o dependency-graph.svg'
);
-fs.unlink('./dependencies.gv');
+fs.unlinkSync('./dependencies.gv');
diff --git a/examples/app/index.js b/examples/app/index.js
index aa9bf195b5d0..31b06f859ee6 100644
--- a/examples/app/index.js
+++ b/examples/app/index.js
@@ -10,9 +10,9 @@ __webpack_public_path__ = PageConfig.getOption('fullStaticUrl') + '/';
require('./build/imports.css');
window.addEventListener('load', async function() {
- var JupyterLab = require('@jupyterlab/application').JupyterLab;
+ const JupyterLab = require('@jupyterlab/application').JupyterLab;
- var mods = [
+ const mods = [
require('@jupyterlab/application-extension'),
require('@jupyterlab/apputils-extension'),
require('@jupyterlab/codemirror-extension'),
@@ -42,7 +42,7 @@ window.addEventListener('load', async function() {
require('@jupyterlab/tooltip-extension'),
require('@jupyterlab/ui-components-extension')
];
- var lab = new JupyterLab();
+ const lab = new JupyterLab();
lab.registerPluginModules(mods);
/* eslint-disable no-console */
console.log('Starting app');
diff --git a/examples/app/webpack.config.js b/examples/app/webpack.config.js
index 0b26cf668bc4..39e7536a546c 100644
--- a/examples/app/webpack.config.js
+++ b/examples/app/webpack.config.js
@@ -1,14 +1,14 @@
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
-var data = require('./package.json');
-var Build = require('@jupyterlab/buildutils').Build;
+const data = require('./package.json');
+const Build = require('@jupyterlab/buildutils').Build;
-var names = Object.keys(data.dependencies).filter(function(name) {
- var packageData = require(name + '/package.json');
+const names = Object.keys(data.dependencies).filter(function(name) {
+ const packageData = require(name + '/package.json');
return packageData.jupyterlab !== undefined;
});
-var extras = Build.ensureAssets({
+const extras = Build.ensureAssets({
packageNames: names,
output: './build'
});
diff --git a/examples/cell/src/index.ts b/examples/cell/src/index.ts
index d2759fca9e1d..78f14fe464a1 100755
--- a/examples/cell/src/index.ts
+++ b/examples/cell/src/index.ts
@@ -146,7 +146,7 @@ function main(): void {
// Start up the kernel.
void sessionContext.initialize().then(() => {
- console.log('Example started!');
+ console.debug('Example started!');
});
}
diff --git a/examples/console/src/index.ts b/examples/console/src/index.ts
index 43c8cf275915..236c1c8cf0b6 100644
--- a/examples/console/src/index.ts
+++ b/examples/console/src/index.ts
@@ -25,18 +25,18 @@ import {
standardRendererFactories as initialFactories
} from '@jupyterlab/rendermime';
-let TITLE = 'Console';
+const TITLE = 'Console';
function main(): void {
- console.log('in main');
+ console.debug('in main');
let path = '';
- let query: { [key: string]: string } = Object.create(null);
+ const query: { [key: string]: string } = Object.create(null);
window.location.search
.substr(1)
.split('&')
.forEach(item => {
- let pair = item.split('=');
+ const pair = item.split('=');
if (pair[0]) {
query[pair[0]] = pair[1];
}
@@ -46,7 +46,7 @@ function main(): void {
path = query['path'];
}
- let manager = new ServiceManager();
+ const manager = new ServiceManager();
void manager.ready.then(() => {
startApp(path, manager);
});
@@ -56,20 +56,20 @@ function main(): void {
* Start the application.
*/
function startApp(path: string, manager: ServiceManager.IManager) {
- console.log('starting app');
+ console.debug('starting app');
// Initialize the command registry with the key bindings.
- let commands = new CommandRegistry();
+ const commands = new CommandRegistry();
// Setup the keydown listener for the document.
document.addEventListener('keydown', event => {
commands.processKeydownEvent(event);
});
- let rendermime = new RenderMimeRegistry({ initialFactories });
+ const rendermime = new RenderMimeRegistry({ initialFactories });
- let editorFactory = editorServices.factoryService.newInlineEditor;
- let contentFactory = new ConsolePanel.ContentFactory({ editorFactory });
- let consolePanel = new ConsolePanel({
+ const editorFactory = editorServices.factoryService.newInlineEditor;
+ const contentFactory = new ConsolePanel.ContentFactory({ editorFactory });
+ const consolePanel = new ConsolePanel({
rendermime,
manager,
path,
@@ -78,9 +78,9 @@ function startApp(path: string, manager: ServiceManager.IManager) {
});
consolePanel.title.label = TITLE;
- let palette = new CommandPalette({ commands });
+ const palette = new CommandPalette({ commands });
- let panel = new SplitPanel();
+ const panel = new SplitPanel();
panel.id = 'main';
panel.orientation = 'horizontal';
panel.spacing = 0;
@@ -97,8 +97,8 @@ function startApp(path: string, manager: ServiceManager.IManager) {
panel.update();
});
- let selector = '.jp-ConsolePanel';
- let category = 'Console';
+ const selector = '.jp-ConsolePanel';
+ const category = 'Console';
let command: string;
// Add the commands.
@@ -141,7 +141,7 @@ function startApp(path: string, manager: ServiceManager.IManager) {
palette.addItem({ command, category });
commands.addKeyBinding({ command, selector, keys: ['Ctrl Enter'] });
- console.log('Example started!');
+ console.debug('Example started!');
}
window.addEventListener('load', main);
diff --git a/examples/filebrowser/src/index.ts b/examples/filebrowser/src/index.ts
index 666943f2d3e2..884a2435f224 100644
--- a/examples/filebrowser/src/index.ts
+++ b/examples/filebrowser/src/index.ts
@@ -37,17 +37,17 @@ import { FileEditorFactory } from '@jupyterlab/fileeditor';
import { addIcon } from '@jupyterlab/ui-components';
function main(): void {
- let manager = new ServiceManager();
+ const manager = new ServiceManager();
void manager.ready.then(() => {
createApp(manager);
});
}
function createApp(manager: ServiceManager.IManager): void {
- let widgets: Widget[] = [];
+ const widgets: Widget[] = [];
let activeWidget: Widget;
- let opener = {
+ const opener = {
open: (widget: Widget) => {
if (widgets.indexOf(widget) === -1) {
dock.addWidget(widget, { mode: 'tab-after' });
@@ -56,23 +56,23 @@ function createApp(manager: ServiceManager.IManager): void {
dock.activateWidget(widget);
activeWidget = widget;
widget.disposed.connect((w: Widget) => {
- let index = widgets.indexOf(w);
+ const index = widgets.indexOf(w);
widgets.splice(index, 1);
});
}
};
- let docRegistry = new DocumentRegistry();
- let docManager = new DocumentManager({
+ const docRegistry = new DocumentRegistry();
+ const docManager = new DocumentManager({
registry: docRegistry,
manager,
opener
});
- let editorServices = {
+ const editorServices = {
factoryService: new CodeMirrorEditorFactory(),
mimeTypeService: new CodeMirrorMimeTypeService()
};
- let wFactory = new FileEditorFactory({
+ const wFactory = new FileEditorFactory({
editorServices,
factoryOptions: {
name: 'Editor',
@@ -85,18 +85,18 @@ function createApp(manager: ServiceManager.IManager): void {
});
docRegistry.addWidgetFactory(wFactory);
- let commands = new CommandRegistry();
+ const commands = new CommandRegistry();
- let fbModel = new FileBrowserModel({
+ const fbModel = new FileBrowserModel({
manager: docManager
});
- let fbWidget = new FileBrowser({
+ const fbWidget = new FileBrowser({
id: 'filebrowser',
model: fbModel
});
// Add a creator toolbar item.
- let creator = new ToolbarButton({
+ const creator = new ToolbarButton({
icon: addIcon,
onClick: () => {
void docManager
@@ -111,18 +111,18 @@ function createApp(manager: ServiceManager.IManager): void {
});
fbWidget.toolbar.insertItem(0, 'create', creator);
- let panel = new SplitPanel();
+ const panel = new SplitPanel();
panel.id = 'main';
panel.addWidget(fbWidget);
SplitPanel.setStretch(fbWidget, 0);
- let dock = new DockPanel();
+ const dock = new DockPanel();
panel.addWidget(dock);
SplitPanel.setStretch(dock, 1);
dock.spacing = 8;
document.addEventListener('focus', event => {
for (let i = 0; i < widgets.length; i++) {
- let widget = widgets[i];
+ const widget = widgets[i];
if (widget.node.contains(event.target as HTMLElement)) {
activeWidget = widget;
break;
@@ -151,7 +151,7 @@ function createApp(manager: ServiceManager.IManager): void {
});
commands.addCommand('file-save', {
execute: () => {
- let context = docManager.contextForWidget(activeWidget);
+ const context = docManager.contextForWidget(activeWidget);
return context?.save();
}
});
@@ -217,7 +217,7 @@ function createApp(manager: ServiceManager.IManager): void {
commands.addCommand('file-info-demo', {
label: 'Info Demo',
execute: () => {
- let msg = 'The quick brown fox jumped over the lazy dog';
+ const msg = 'The quick brown fox jumped over the lazy dog';
void showDialog({
title: 'Cool Title',
body: msg,
@@ -241,7 +241,7 @@ function createApp(manager: ServiceManager.IManager): void {
});
// Create a context menu.
- let menu = new Menu({ commands });
+ const menu = new Menu({ commands });
menu.addItem({ command: 'file-open' });
menu.addItem({ command: 'file-rename' });
menu.addItem({ command: 'file-remove' });
@@ -255,11 +255,11 @@ function createApp(manager: ServiceManager.IManager): void {
menu.addItem({ command: 'file-info-demo' });
// Add a context menu to the dir listing.
- let node = fbWidget.node.getElementsByClassName('jp-DirListing-content')[0];
+ const node = fbWidget.node.getElementsByClassName('jp-DirListing-content')[0];
node.addEventListener('contextmenu', (event: MouseEvent) => {
event.preventDefault();
- let x = event.clientX;
- let y = event.clientY;
+ const x = event.clientX;
+ const y = event.clientY;
menu.open(x, y);
});
@@ -271,22 +271,22 @@ function createApp(manager: ServiceManager.IManager): void {
panel.update();
});
- console.log('Example started!');
+ console.debug('Example started!');
}
/**
* Create a non-functional dialog demo.
*/
function dialogDemo(): void {
- let body = document.createElement('div');
- let input = document.createElement('input');
+ const body = document.createElement('div');
+ const input = document.createElement('input');
input.value = 'Untitled.ipynb';
- let selector = document.createElement('select');
- let option0 = document.createElement('option');
+ const selector = document.createElement('select');
+ const option0 = document.createElement('option');
option0.value = 'python';
option0.text = 'Python 3';
selector.appendChild(option0);
- let option1 = document.createElement('option');
+ const option1 = document.createElement('option');
option1.value = 'julia';
option1.text = 'Julia';
selector.appendChild(option1);
diff --git a/examples/notebook/src/commands.ts b/examples/notebook/src/commands.ts
index 165e080cf4df..465f7a7d8da5 100644
--- a/examples/notebook/src/commands.ts
+++ b/examples/notebook/src/commands.ts
@@ -233,7 +233,7 @@ export const SetupCommands = (
cmdIds.redo
].forEach(command => palette.addItem({ command, category }));
- let bindings = [
+ const bindings = [
{
selector: '.jp-Notebook.jp-mod-editMode .jp-mod-completer-enabled',
keys: ['Tab'],
diff --git a/examples/notebook/src/index.ts b/examples/notebook/src/index.ts
index 55f1e9446c5b..688f1ba70bd8 100755
--- a/examples/notebook/src/index.ts
+++ b/examples/notebook/src/index.ts
@@ -46,7 +46,7 @@ import {
import { SetupCommands } from './commands';
function main(): void {
- let manager = new ServiceManager();
+ const manager = new ServiceManager();
void manager.ready.then(() => {
createApp(manager);
});
@@ -54,8 +54,8 @@ function main(): void {
function createApp(manager: ServiceManager.IManager): void {
// Initialize the command registry with the bindings.
- let commands = new CommandRegistry();
- let useCapture = true;
+ const commands = new CommandRegistry();
+ const useCapture = true;
// Setup the keydown listener for the document.
document.addEventListener(
@@ -66,7 +66,7 @@ function createApp(manager: ServiceManager.IManager): void {
useCapture
);
- let rendermime = new RenderMimeRegistry({
+ const rendermime = new RenderMimeRegistry({
initialFactories: initialFactories,
latexTypesetter: new MathJaxTypesetter({
url: PageConfig.getOption('mathjaxUrl'),
@@ -74,23 +74,23 @@ function createApp(manager: ServiceManager.IManager): void {
})
});
- let opener = {
+ const opener = {
open: (widget: Widget) => {
// Do nothing for sibling widgets for now.
}
};
- let docRegistry = new DocumentRegistry();
- let docManager = new DocumentManager({
+ const docRegistry = new DocumentRegistry();
+ const docManager = new DocumentManager({
registry: docRegistry,
manager,
opener
});
- let mFactory = new NotebookModelFactory({});
- let editorFactory = editorServices.factoryService.newInlineEditor;
- let contentFactory = new NotebookPanel.ContentFactory({ editorFactory });
+ const mFactory = new NotebookModelFactory({});
+ const editorFactory = editorServices.factoryService.newInlineEditor;
+ const contentFactory = new NotebookPanel.ContentFactory({ editorFactory });
- let wFactory = new NotebookWidgetFactory({
+ const wFactory = new NotebookWidgetFactory({
name: 'Notebook',
modelName: 'notebook',
fileTypes: ['notebook'],
@@ -104,9 +104,9 @@ function createApp(manager: ServiceManager.IManager): void {
docRegistry.addModelFactory(mFactory);
docRegistry.addWidgetFactory(wFactory);
- let notebookPath = PageConfig.getOption('notebookPath');
- let nbWidget = docManager.open(notebookPath) as NotebookPanel;
- let palette = new CommandPalette({ commands });
+ const notebookPath = PageConfig.getOption('notebookPath');
+ const nbWidget = docManager.open(notebookPath) as NotebookPanel;
+ const palette = new CommandPalette({ commands });
palette.addClass('notebookCommandPalette');
const editor =
@@ -136,7 +136,7 @@ function createApp(manager: ServiceManager.IManager): void {
// Hide the widget when it first loads.
completer.hide();
- let panel = new SplitPanel();
+ const panel = new SplitPanel();
panel.id = 'main';
panel.orientation = 'horizontal';
panel.spacing = 0;
@@ -156,7 +156,7 @@ function createApp(manager: ServiceManager.IManager): void {
SetupCommands(commands, palette, nbWidget, handler);
- console.log('Example started!');
+ console.debug('Example started!');
}
window.addEventListener('load', main);
diff --git a/examples/terminal/src/index.ts b/examples/terminal/src/index.ts
index 782e9239113e..48b3e646f507 100644
--- a/examples/terminal/src/index.ts
+++ b/examples/terminal/src/index.ts
@@ -17,7 +17,7 @@ import { TerminalManager } from '@jupyterlab/services';
import { Terminal } from '@jupyterlab/terminal';
async function main(): Promise {
- let dock = new DockPanel();
+ const dock = new DockPanel();
dock.id = 'main';
// Attach the widget to the dom.
@@ -39,7 +39,7 @@ async function main(): Promise {
term2.title.closable = true;
dock.addWidget(term2, { mode: 'tab-before' });
- console.log('Example started!');
+ console.debug('Example started!');
}
window.addEventListener('load', main);
diff --git a/jupyterlab/node-version-check.js b/jupyterlab/node-version-check.js
index 413c66464325..ac858a211349 100644
--- a/jupyterlab/node-version-check.js
+++ b/jupyterlab/node-version-check.js
@@ -1,15 +1,15 @@
#!/usr/bin/env node
-var pkg = require('./staging/package.json');
+const pkg = require('./staging/package.json');
function parser(part) {
return parseInt(part, 10);
}
-var engine = pkg.engines.node.replace('>=', '');
-var eparts = engine.split('.').map(parser);
+const engine = pkg.engines.node.replace('>=', '');
+const eparts = engine.split('.').map(parser);
-var version = process.version.replace('v', '');
-var vparts = version.split('.').map(parser);
+const version = process.version.replace('v', '');
+const vparts = version.split('.').map(parser);
// eslint-disable-next-line
console.log('Node', process.version);
diff --git a/jupyterlab/staging/webpack.config.js b/jupyterlab/staging/webpack.config.js
index e3e515c18dfd..3176dcc6da8e 100644
--- a/jupyterlab/staging/webpack.config.js
+++ b/jupyterlab/staging/webpack.config.js
@@ -1,48 +1,50 @@
// This file is auto-generated from the corresponding file in /dev_mode
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
-var plib = require('path');
-var fs = require('fs-extra');
-var Handlebars = require('handlebars');
-var HtmlWebpackPlugin = require('html-webpack-plugin');
-var webpack = require('webpack');
-var BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
+const plib = require('path');
+const fs = require('fs-extra');
+const Handlebars = require('handlebars');
+const HtmlWebpackPlugin = require('html-webpack-plugin');
+const webpack = require('webpack');
+const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
.BundleAnalyzerPlugin;
-var Build = require('@jupyterlab/buildutils').Build;
-var WPPlugin = require('@jupyterlab/buildutils').WPPlugin;
-var package_data = require('./package.json');
+const Build = require('@jupyterlab/buildutils').Build;
+const WPPlugin = require('@jupyterlab/buildutils').WPPlugin;
+const package_data = require('./package.json');
// Handle the extensions.
-var jlab = package_data.jupyterlab;
-var extensions = jlab.extensions;
-var mimeExtensions = jlab.mimeExtensions;
-var packageNames = Object.keys(mimeExtensions).concat(Object.keys(extensions));
+const jlab = package_data.jupyterlab;
+const extensions = jlab.extensions;
+const mimeExtensions = jlab.mimeExtensions;
+const packageNames = Object.keys(mimeExtensions).concat(
+ Object.keys(extensions)
+);
// Ensure a clear build directory.
-var buildDir = plib.resolve(jlab.buildDir);
+const buildDir = plib.resolve(jlab.buildDir);
if (fs.existsSync(buildDir)) {
fs.removeSync(buildDir);
}
fs.ensureDirSync(buildDir);
// Build the assets
-var extraConfig = Build.ensureAssets({
+const extraConfig = Build.ensureAssets({
packageNames: packageNames,
output: jlab.outputDir
});
// Create the entry point file.
-var source = fs.readFileSync('index.js').toString();
-var template = Handlebars.compile(source);
-var data = {
+const source = fs.readFileSync('index.js').toString();
+const template = Handlebars.compile(source);
+const data = {
jupyterlab_extensions: extensions,
jupyterlab_mime_extensions: mimeExtensions
};
-var result = template(data);
+const result = template(data);
fs.writeFileSync(plib.join(buildDir, 'index.out.js'), result);
fs.copySync('./package.json', plib.join(buildDir, 'package.json'));
@@ -52,16 +54,18 @@ fs.copySync(
);
// Set up variables for the watch mode ignore plugins
-let watched = {};
-let ignoreCache = Object.create(null);
+const watched = {};
+const ignoreCache = Object.create(null);
Object.keys(jlab.linkedPackages).forEach(function(name) {
- if (name in watched) return;
+ if (name in watched) {
+ return;
+ }
const localPkgPath = require.resolve(plib.join(name, 'package.json'));
watched[name] = plib.dirname(localPkgPath);
});
// Set up source-map-loader to look in watched lib dirs
-let sourceMapRes = Object.values(watched).reduce((res, name) => {
+const sourceMapRes = Object.values(watched).reduce((res, name) => {
res.push(new RegExp(name + '/lib'));
return res;
}, []);
diff --git a/jupyterlab/staging/webpack.prod.config.js b/jupyterlab/staging/webpack.prod.config.js
index c8c4eaf7a903..7d484c7ba991 100644
--- a/jupyterlab/staging/webpack.prod.config.js
+++ b/jupyterlab/staging/webpack.prod.config.js
@@ -1,6 +1,6 @@
// This file is auto-generated from the corresponding file in /dev_mode
-var merge = require('webpack-merge');
-var config = require('./webpack.config');
+const merge = require('webpack-merge');
+const config = require('./webpack.config');
config[0] = merge(config[0], {
mode: 'production',
diff --git a/jupyterlab/staging/webpack.prod.minimize.config.js b/jupyterlab/staging/webpack.prod.minimize.config.js
index af01013e601f..fafc472643b3 100644
--- a/jupyterlab/staging/webpack.prod.minimize.config.js
+++ b/jupyterlab/staging/webpack.prod.minimize.config.js
@@ -1,7 +1,7 @@
// This file is auto-generated from the corresponding file in /dev_mode
const TerserPlugin = require('terser-webpack-plugin');
-var merge = require('webpack-merge');
-var config = require('./webpack.config');
+const merge = require('webpack-merge');
+const config = require('./webpack.config');
config[0] = merge(config[0], {
mode: 'production',
diff --git a/jupyterlab/staging/webpack.prod.release.config.js b/jupyterlab/staging/webpack.prod.release.config.js
index 5b4497310456..91d826d7184b 100644
--- a/jupyterlab/staging/webpack.prod.release.config.js
+++ b/jupyterlab/staging/webpack.prod.release.config.js
@@ -1,6 +1,6 @@
// This file is auto-generated from the corresponding file in /dev_mode
-var merge = require('webpack-merge');
-var config = require('./webpack.prod.minimize.config');
+const merge = require('webpack-merge');
+const config = require('./webpack.prod.minimize.config');
config[0] = merge(config[0], {
// Turn off source maps
diff --git a/lint-staged.config.js b/lint-staged.config.js
index 875da8ac3f59..f6908c772c1e 100644
--- a/lint-staged.config.js
+++ b/lint-staged.config.js
@@ -16,15 +16,7 @@ module.exports = {
`git add ${escapedFileNames}`
];
},
- '**/*{.ts,.tsx}': filenames => {
- const escapedFileNames = escapeFileNames(filenames);
- return [
- `prettier --write ${escapedFileNames}`,
- `tslint --fix ${escapedFileNames}`,
- `git add ${escapedFileNames}`
- ];
- },
- '**/*{.js,.jsx}': filenames => {
+ '**/*{.ts,.tsx,.js,.jsx}': filenames => {
const escapedFileNames = escapeFileNames(filenames);
return [
`prettier --write ${escapedFileNames}`,
diff --git a/package.json b/package.json
index 4ed60419531a..14440203dba2 100644
--- a/package.json
+++ b/package.json
@@ -51,8 +51,8 @@
"create:theme": "node buildutils/lib/create-theme.js",
"deduplicate": "jlpm yarn-deduplicate -s fewer --fail",
"docs": "lerna run docs",
- "eslint": "eslint --fix .",
- "eslint:check": "eslint .",
+ "eslint": "eslint --ext .js,.jsx,.ts,.tsx --fix .",
+ "eslint:check": "eslint --ext .js,.jsx,.ts,.tsx .",
"get:dependency": "node buildutils/lib/get-dependency.js",
"postinstall": "node scripts/ensure-buildutils.js",
"integrity": "node scripts/ensure-buildutils.js && node buildutils/lib/ensure-repo.js",
@@ -60,8 +60,8 @@
"lighthouse:compare": "node testutils/lib/compare-lighthouse.js",
"lighthouse:throttling:start": "comcast --latency=40 --target-bw=30000 --packet-loss=0.2%",
"lighthouse:throttling:stop": "comcast --stop",
- "lint": "jlpm && jlpm run prettier && jlpm run eslint && jlpm run tslint",
- "lint:check": "jlpm run prettier:check && jlpm run eslint:check && jlpm run tslint:check",
+ "lint": "jlpm && jlpm run prettier && jlpm run eslint",
+ "lint:check": "jlpm run prettier:check && jlpm run eslint:check",
"patch:release": "node buildutils/lib/patch-release.js",
"prepublish:check": "node buildutils/lib/prepublish-check.js",
"prettier": "prettier --write \"**/*{.ts,.tsx,.js,.jsx,.css,.json,.md}\"",
@@ -78,9 +78,7 @@
"test:firefox": "lerna run test:firefox --scope \"@jupyterlab/*\" --concurrency 1 --stream",
"test:ie": "lerna run test:ie --scope \"@jupyterlab/*\" --concurrency 1 --stream",
"test:scope": "lerna run test --concurrency 1 --stream",
- "test:summary": "lerna run test --scope \"@jupyterlab/*\" --parallel --no-bail | grep -Ei '.* test.*(failed|passed|total|completed|skipped)' | sort",
- "tslint": "tslint --fix -c tslint.json --project tsconfigbase.json '**/*{.ts,.tsx}'",
- "tslint:check": "tslint -c tslint.json --project tsconfigbase.json '**/*{.ts,.tsx}'",
+ "test:summary": "lerna run test --scope \"@jupyterlab/test-*\" --parallel --no-bail | grep -Ei '.* test.*(failed|passed|total|completed|skipped)' | sort",
"update:dependency": "node buildutils/lib/update-dependency.js --lerna",
"watch": "python scripts/watch_dev.py",
"watch:main": "jlpm run watch",
@@ -94,18 +92,17 @@
},
"dependencies": {},
"devDependencies": {
- "eslint": "^6.7.2",
+ "@typescript-eslint/eslint-plugin": "^2.27.0",
+ "@typescript-eslint/parser": "^2.27.0",
+ "eslint": "^6.8.0",
"eslint-config-prettier": "^6.7.0",
"eslint-plugin-prettier": "^3.1.1",
+ "eslint-plugin-react": "^7.19.0",
"husky": "^3.1.0",
"lerna": "^3.19.0",
"lint-staged": "^9.5.0",
"prettier": "^1.19.1",
"shell-quote": "^1.7.2",
- "tslint": "^5.20.1",
- "tslint-config-prettier": "^1.18.0",
- "tslint-plugin-prettier": "^2.0.1",
- "tslint-react": "^4.1.0",
"yarn": "1.21.1"
}
}
diff --git a/packages/application-extension/src/index.tsx b/packages/application-extension/src/index.tsx
index 43ec1984b78b..d590898e59c2 100644
--- a/packages/application-extension/src/index.tsx
+++ b/packages/application-extension/src/index.tsx
@@ -108,7 +108,7 @@ const main: JupyterFrontEndPlugin = {
// will short-circuit and ask the user to navigate away.
const workspace = resolver.name;
- console.log(`Starting application in workspace: "${workspace}"`);
+ console.debug(`Starting application in workspace: "${workspace}"`);
// If there were errors registering plugins, tell the user.
if (app.registerPluginErrors.length !== 0) {
@@ -547,7 +547,7 @@ function addCommands(app: JupyterLab, palette: ICommandPalette | null): void {
if (!mainArea || mainArea.mode !== 'multiple-document') {
return null;
}
- let area = mainArea.dock?.main;
+ const area = mainArea.dock?.main;
if (!area) {
return null;
}
diff --git a/packages/application/src/lab.ts b/packages/application/src/lab.ts
index a2de106baddb..2aeeb95e5b68 100644
--- a/packages/application/src/lab.ts
+++ b/packages/application/src/lab.ts
@@ -79,7 +79,7 @@ export class JupyterLab extends JupyterFrontEnd {
this.docRegistry.addModelFactory(new Base64ModelFactory());
if (options.mimeExtensions) {
- for (let plugin of createRendermimePlugins(options.mimeExtensions)) {
+ for (const plugin of createRendermimePlugins(options.mimeExtensions)) {
this.registerPlugin(plugin);
}
}
diff --git a/packages/application/src/layoutrestorer.ts b/packages/application/src/layoutrestorer.ts
index 591fe98f9826..3cf41fe75573 100644
--- a/packages/application/src/layoutrestorer.ts
+++ b/packages/application/src/layoutrestorer.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -271,12 +271,12 @@ export class LayoutRestorer implements ILayoutRestorer {
save(data: ILabShell.ILayout): Promise {
// If there are promises that are unresolved, bail.
if (!this._promisesDone) {
- let warning = 'save() was called prematurely.';
+ const warning = 'save() was called prematurely.';
console.warn(warning);
return Promise.reject(warning);
}
- let dehydrated: Private.ILayout = {};
+ const dehydrated: Private.ILayout = {};
// Dehydrate main area.
dehydrated.main = this._dehydrateMainArea(data.mainArea);
@@ -327,9 +327,9 @@ export class LayoutRestorer implements ILayoutRestorer {
if (!area) {
return null;
}
- let dehydrated: Private.ISideArea = { collapsed: area.collapsed };
+ const dehydrated: Private.ISideArea = { collapsed: area.collapsed };
if (area.currentWidget) {
- let current = Private.nameProperty.get(area.currentWidget);
+ const current = Private.nameProperty.get(area.currentWidget);
if (current) {
dehydrated.current = current;
}
@@ -355,7 +355,7 @@ export class LayoutRestorer implements ILayoutRestorer {
if (!area) {
return { collapsed: true, currentWidget: null, widgets: null };
}
- let internal = this._widgets;
+ const internal = this._widgets;
const collapsed = area.hasOwnProperty('collapsed')
? !!area.collapsed
: false;
@@ -381,7 +381,7 @@ export class LayoutRestorer implements ILayoutRestorer {
* Handle a widget disposal.
*/
private _onWidgetDisposed(widget: Widget): void {
- let name = Private.nameProperty.get(widget);
+ const name = Private.nameProperty.get(widget);
this._widgets.delete(name);
}
@@ -580,13 +580,13 @@ namespace Private {
* Return a dehydrated, serializable version of the main dock panel.
*/
export function serializeMain(area: ILabShell.IMainArea): IMainArea {
- let dehydrated: IMainArea = {
+ const dehydrated: IMainArea = {
dock: (area && area.dock && serializeArea(area.dock.main)) || null
};
if (area) {
dehydrated.mode = area.mode;
if (area.currentWidget) {
- let current = Private.nameProperty.get(area.currentWidget);
+ const current = Private.nameProperty.get(area.currentWidget);
if (current) {
dehydrated.current = current;
}
@@ -623,7 +623,7 @@ namespace Private {
if (type === 'tab-area') {
const { currentIndex, widgets } = area as ITabArea;
- let hydrated: ILabShell.AreaConfig = {
+ const hydrated: ILabShell.AreaConfig = {
type: 'tab-area',
currentIndex: currentIndex || 0,
widgets:
@@ -643,7 +643,7 @@ namespace Private {
}
const { orientation, sizes, children } = area as ISplitArea;
- let hydrated: ILabShell.AreaConfig = {
+ const hydrated: ILabShell.AreaConfig = {
type: 'split-area',
orientation: orientation,
sizes: sizes || [],
diff --git a/packages/application/src/mimerenderers.ts b/packages/application/src/mimerenderers.ts
index 6dbe9fe3bc3d..64c367365aca 100644
--- a/packages/application/src/mimerenderers.ts
+++ b/packages/application/src/mimerenderers.ts
@@ -113,7 +113,7 @@ export function createRendermimePlugin(
return;
}
- let registry = app.docRegistry;
+ const registry = app.docRegistry;
let options: IRenderMime.IDocumentWidgetFactoryOptions[] = [];
if (Array.isArray(item.documentWidgetFactoryOptions)) {
options = item.documentWidgetFactoryOptions;
@@ -138,7 +138,7 @@ export function createRendermimePlugin(
const toolbarFactory = option.toolbarFactory
? (w: MimeDocument) => option.toolbarFactory!(w.content.renderer)
: undefined;
- let factory = new MimeDocumentFactory({
+ const factory = new MimeDocumentFactory({
renderTimeout: item.renderTimeout,
dataType: item.dataType,
rendermime,
diff --git a/packages/application/src/router.ts b/packages/application/src/router.ts
index 4ead623ba8b6..e3386c3ceb7e 100644
--- a/packages/application/src/router.ts
+++ b/packages/application/src/router.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -162,7 +162,7 @@ export class Router implements IRouter {
const result = await commands.execute(command, current);
if (result === stop) {
queue.length = 0;
- console.log(`Routing ${request} was short-circuited by ${command}`);
+ console.debug(`Routing ${request} was short-circuited by ${command}`);
}
} catch (reason) {
console.warn(`Routing ${request} to ${command} failed`, reason);
diff --git a/packages/application/src/shell.ts b/packages/application/src/shell.ts
index 1a107e283fab..b9c6f59bfdfb 100644
--- a/packages/application/src/shell.ts
+++ b/packages/application/src/shell.ts
@@ -175,17 +175,17 @@ export class LabShell extends Widget implements JupyterFrontEnd.IShell {
this.addClass(APPLICATION_SHELL_CLASS);
this.id = 'main';
- let headerPanel = (this._headerPanel = new BoxPanel());
- let topHandler = (this._topHandler = new Private.PanelHandler());
- let bottomPanel = (this._bottomPanel = new BoxPanel());
- let hboxPanel = new BoxPanel();
- let dockPanel = (this._dockPanel = new DockPanelSvg());
+ const headerPanel = (this._headerPanel = new BoxPanel());
+ const topHandler = (this._topHandler = new Private.PanelHandler());
+ const bottomPanel = (this._bottomPanel = new BoxPanel());
+ const hboxPanel = new BoxPanel();
+ const dockPanel = (this._dockPanel = new DockPanelSvg());
MessageLoop.installMessageHook(dockPanel, this._dockChildHook);
- let hsplitPanel = new SplitPanel();
- let leftHandler = (this._leftHandler = new Private.SideBarHandler());
- let rightHandler = (this._rightHandler = new Private.SideBarHandler());
- let rootLayout = new BoxLayout();
+ const hsplitPanel = new SplitPanel();
+ const leftHandler = (this._leftHandler = new Private.SideBarHandler());
+ const rightHandler = (this._rightHandler = new Private.SideBarHandler());
+ const rootLayout = new BoxLayout();
headerPanel.id = 'jp-header-panel';
topHandler.panel.id = 'jp-top-panel';
@@ -435,12 +435,12 @@ export class LabShell extends Widget implements JupyterFrontEnd.IShell {
* Activate the next Tab in the active TabBar.
*/
activateNextTab(): void {
- let current = this._currentTabBar();
+ const current = this._currentTabBar();
if (!current) {
return;
}
- let ci = current.currentIndex;
+ const ci = current.currentIndex;
if (ci === -1) {
return;
}
@@ -454,7 +454,7 @@ export class LabShell extends Widget implements JupyterFrontEnd.IShell {
}
if (ci === current.titles.length - 1) {
- let nextBar = this._adjacentBar('next');
+ const nextBar = this._adjacentBar('next');
if (nextBar) {
nextBar.currentIndex = 0;
if (nextBar.currentTitle) {
@@ -468,12 +468,12 @@ export class LabShell extends Widget implements JupyterFrontEnd.IShell {
* Activate the previous Tab in the active TabBar.
*/
activatePreviousTab(): void {
- let current = this._currentTabBar();
+ const current = this._currentTabBar();
if (!current) {
return;
}
- let ci = current.currentIndex;
+ const ci = current.currentIndex;
if (ci === -1) {
return;
}
@@ -487,9 +487,9 @@ export class LabShell extends Widget implements JupyterFrontEnd.IShell {
}
if (ci === 0) {
- let prevBar = this._adjacentBar('previous');
+ const prevBar = this._adjacentBar('previous');
if (prevBar) {
- let len = prevBar.titles.length;
+ const len = prevBar.titles.length;
prevBar.currentIndex = len - 1;
if (prevBar.currentTitle) {
prevBar.currentTitle.owner.activate();
@@ -502,7 +502,7 @@ export class LabShell extends Widget implements JupyterFrontEnd.IShell {
* Activate the next TabBar.
*/
activateNextTabBar(): void {
- let nextBar = this._adjacentBar('next');
+ const nextBar = this._adjacentBar('next');
if (nextBar) {
if (nextBar.currentTitle) {
nextBar.currentTitle.owner.activate();
@@ -514,7 +514,7 @@ export class LabShell extends Widget implements JupyterFrontEnd.IShell {
* Activate the next TabBar.
*/
activatePreviousTabBar(): void {
- let nextBar = this._adjacentBar('previous');
+ const nextBar = this._adjacentBar('previous');
if (nextBar) {
if (nextBar.currentTitle) {
nextBar.currentTitle.owner.activate();
@@ -733,7 +733,7 @@ export class LabShell extends Widget implements JupyterFrontEnd.IShell {
}
options = options || this._sideOptionsCache.get(widget) || {};
this._sideOptionsCache.set(widget, options);
- let rank = 'rank' in options ? options.rank : DEFAULT_RANK;
+ const rank = 'rank' in options ? options.rank : DEFAULT_RANK;
this._leftHandler.addWidget(widget, rank!);
this._onLayoutModified();
}
@@ -1148,7 +1148,7 @@ namespace Private {
* @param id - The widget's unique ID.
*/
activate(id: string): void {
- let widget = this._findWidgetByID(id);
+ const widget = this._findWidgetByID(id);
if (widget) {
this._sideBar.currentTitle = widget.title;
widget.activate();
@@ -1177,8 +1177,8 @@ namespace Private {
addWidget(widget: Widget, rank: number): void {
widget.parent = null;
widget.hide();
- let item = { widget, rank };
- let index = this._findInsertIndex(item);
+ const item = { widget, rank };
+ const index = this._findInsertIndex(item);
ArrayExt.insert(this._items, index, item);
this._stackedPanel.insertWidget(index, widget);
const title = this._sideBar.insertTab(index, widget.title);
@@ -1203,9 +1203,9 @@ namespace Private {
* Dehydrate the side bar data.
*/
dehydrate(): ILabShell.ISideArea {
- let collapsed = this._sideBar.currentTitle === null;
- let widgets = toArray(this._stackedPanel.widgets);
- let currentWidget = widgets[this._sideBar.currentIndex];
+ const collapsed = this._sideBar.currentTitle === null;
+ const widgets = toArray(this._stackedPanel.widgets);
+ const currentWidget = widgets[this._sideBar.currentIndex];
return { collapsed, currentWidget, widgets };
}
@@ -1238,7 +1238,7 @@ namespace Private {
* Find the widget which owns the given title, or `null`.
*/
private _findWidgetByTitle(title: Title): Widget | null {
- let item = find(this._items, value => value.widget.title === title);
+ const item = find(this._items, value => value.widget.title === title);
return item ? item.widget : null;
}
@@ -1246,7 +1246,7 @@ namespace Private {
* Find the widget with the given id, or `null`.
*/
private _findWidgetByID(id: string): Widget | null {
- let item = find(this._items, value => value.widget.id === id);
+ const item = find(this._items, value => value.widget.id === id);
return item ? item.widget : null;
}
diff --git a/packages/apputils-extension/src/index.ts b/packages/apputils-extension/src/index.ts
index 4bb4f3995f57..852c4232dacb 100644
--- a/packages/apputils-extension/src/index.ts
+++ b/packages/apputils-extension/src/index.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -341,7 +341,7 @@ const state: JupyterFrontEndPlugin = {
transform.resolve({ type: 'overwrite', contents: saved.data });
}
} catch ({ message }) {
- console.log(`Fetching workspace "${workspace}" failed.`, message);
+ console.warn(`Fetching workspace "${workspace}" failed.`, message);
// If the workspace does not exist, cancel the data transformation
// and save a workspace with the current user state data.
@@ -474,8 +474,8 @@ const utilityCommands: JupyterFrontEndPlugin = {
const commandArgs: any = args.args;
const argList = Array.isArray(args);
for (let i = 0; i < commands.length; i++) {
- let cmd = commands[i];
- let arg = argList ? commandArgs[i] : commandArgs;
+ const cmd = commands[i];
+ const arg = argList ? commandArgs[i] : commandArgs;
if (app.commands.isEnabled(cmd, arg)) {
return app.commands.execute(cmd, arg);
}
diff --git a/packages/apputils-extension/src/palette.ts b/packages/apputils-extension/src/palette.ts
index dcf010084c06..c50f29966f7e 100644
--- a/packages/apputils-extension/src/palette.ts
+++ b/packages/apputils-extension/src/palette.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -58,7 +58,7 @@ export class Palette implements ICommandPalette {
* @returns A disposable that will remove the item from the palette.
*/
addItem(options: IPaletteItem): IDisposable {
- let item = this._palette.addItem(options as CommandPalette.IItemOptions);
+ const item = this._palette.addItem(options as CommandPalette.IItemOptions);
return new DisposableDelegate(() => {
this._palette.removeItem(item);
});
diff --git a/packages/apputils-extension/src/settingconnector.ts b/packages/apputils-extension/src/settingconnector.ts
index b34738a2a7e2..07f4dcd4a35c 100644
--- a/packages/apputils-extension/src/settingconnector.ts
+++ b/packages/apputils-extension/src/settingconnector.ts
@@ -40,7 +40,7 @@ export class SettingConnector extends DataConnector<
query: 'active' | 'all' = 'all'
): Promise<{ ids: string[]; values: ISettingRegistry.IPlugin[] }> {
const { isDeferred, isDisabled } = PageConfig.Extension;
- let { ids, values } = await this._connector.list();
+ const { ids, values } = await this._connector.list();
if (query === 'all') {
return { ids, values };
diff --git a/packages/apputils-extension/src/settingsplugin.ts b/packages/apputils-extension/src/settingsplugin.ts
index 2cca4da33650..6442db0688f0 100644
--- a/packages/apputils-extension/src/settingsplugin.ts
+++ b/packages/apputils-extension/src/settingsplugin.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
diff --git a/packages/apputils-extension/src/themeplugins.ts b/packages/apputils-extension/src/themeplugins.ts
index e1d434caebe0..c16249db24d1 100644
--- a/packages/apputils-extension/src/themeplugins.ts
+++ b/packages/apputils-extension/src/themeplugins.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
diff --git a/packages/apputils/src/clipboard.ts b/packages/apputils/src/clipboard.ts
index ed0dcabfbc29..5ccc978f2b57 100644
--- a/packages/apputils/src/clipboard.ts
+++ b/packages/apputils/src/clipboard.ts
@@ -31,9 +31,9 @@ export namespace Clipboard {
* This can only be called in response to a user input event.
*/
export function copyToSystem(clipboardData: ClipboardData): void {
- let node = document.body;
- let handler = (event: ClipboardEvent) => {
- let data = event.clipboardData || (window as any).clipboardData;
+ const node = document.body;
+ const handler = (event: ClipboardEvent) => {
+ const data = event.clipboardData || (window as any).clipboardData;
if (typeof clipboardData === 'string') {
data.setData('text', clipboardData);
} else {
@@ -69,13 +69,13 @@ export namespace Clipboard {
let sel = window.getSelection();
// Save the current selection.
- let savedRanges: any[] = [];
+ const savedRanges: any[] = [];
for (let i = 0, len = sel?.rangeCount || 0; i < len; ++i) {
savedRanges[i] = sel!.getRangeAt(i).cloneRange();
}
// Select the node content.
- let range = document.createRange();
+ const range = document.createRange();
range.selectNodeContents(node);
if (sel) {
sel.removeAllRanges();
diff --git a/packages/apputils/src/collapse.ts b/packages/apputils/src/collapse.ts
index 0b49247fe17d..931895fdf7fb 100644
--- a/packages/apputils/src/collapse.ts
+++ b/packages/apputils/src/collapse.ts
@@ -21,7 +21,7 @@ export class Collapse extends Widget {
this._content = new Panel();
this._content.addClass('jp-Collapse-contents');
- let layout = new PanelLayout();
+ const layout = new PanelLayout();
this.layout = layout;
layout.addWidget(this._header);
layout.addWidget(this._content);
@@ -37,7 +37,7 @@ export class Collapse extends Widget {
return this._widget;
}
set widget(widget: T) {
- let oldWidget = this._widget;
+ const oldWidget = this._widget;
if (oldWidget) {
oldWidget.title.changed.disconnect(this._onTitleChanged, this);
oldWidget.parent = null;
diff --git a/packages/apputils/src/commandlinker.ts b/packages/apputils/src/commandlinker.ts
index 835b145fee02..f5e69050a988 100644
--- a/packages/apputils/src/commandlinker.ts
+++ b/packages/apputils/src/commandlinker.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -176,11 +176,11 @@ export class CommandLinker implements IDisposable {
while (target && target.parentElement) {
if (target.hasAttribute(`data-${COMMAND_ATTR}`)) {
event.preventDefault();
- let command = target.getAttribute(`data-${COMMAND_ATTR}`);
+ const command = target.getAttribute(`data-${COMMAND_ATTR}`);
if (!command) {
return;
}
- let argsValue = target.getAttribute(`data-${ARGS_ATTR}`);
+ const argsValue = target.getAttribute(`data-${ARGS_ATTR}`);
let args = JSONExt.emptyObject;
if (argsValue) {
args = JSON.parse(argsValue);
diff --git a/packages/apputils/src/commandpalette.ts b/packages/apputils/src/commandpalette.ts
index 2b65aaab457b..27448a6f7857 100644
--- a/packages/apputils/src/commandpalette.ts
+++ b/packages/apputils/src/commandpalette.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
diff --git a/packages/apputils/src/dialog.ts b/packages/apputils/src/dialog.ts
index 06f9828e28a9..f811d6a4250d 100644
--- a/packages/apputils/src/dialog.ts
+++ b/packages/apputils/src/dialog.ts
@@ -27,7 +27,7 @@ import { WidgetTracker } from './widgettracker';
export function showDialog(
options: Partial> = {}
): Promise> {
- let dialog = new Dialog(options);
+ const dialog = new Dialog(options);
return dialog.launch();
}
@@ -50,13 +50,13 @@ export function showErrorMessage(
// Cache promises to prevent multiple copies of identical dialogs showing
// to the user.
- let body = typeof error === 'string' ? error : error.message;
- let key = title + '----' + body;
- let promise = Private.errorMessagePromiseCache.get(key);
+ const body = typeof error === 'string' ? error : error.message;
+ const key = title + '----' + body;
+ const promise = Private.errorMessagePromiseCache.get(key);
if (promise) {
return promise;
} else {
- let dialogPromise = showDialog({
+ const dialogPromise = showDialog({
title: title,
body: body,
buttons: buttons
@@ -87,8 +87,8 @@ export class Dialog extends Widget {
constructor(options: Partial> = {}) {
super();
this.addClass('jp-Dialog');
- let normalized = Private.handleOptions(options);
- let renderer = normalized.renderer;
+ const normalized = Private.handleOptions(options);
+ const renderer = normalized.renderer;
this._host = normalized.host;
this._defaultButton = normalized.defaultButton;
@@ -99,16 +99,16 @@ export class Dialog extends Widget {
})
);
- let layout = (this.layout = new PanelLayout());
- let content = new Panel();
+ const layout = (this.layout = new PanelLayout());
+ const content = new Panel();
content.addClass('jp-Dialog-content');
layout.addWidget(content);
this._body = normalized.body;
- let header = renderer.createHeader(normalized.title);
- let body = renderer.createBody(normalized.body);
- let footer = renderer.createFooter(this._buttonNodes);
+ const header = renderer.createHeader(normalized.title);
+ const body = renderer.createBody(normalized.body);
+ const footer = renderer.createFooter(this._buttonNodes);
content.addWidget(header);
content.addWidget(body);
content.addWidget(footer);
@@ -144,7 +144,7 @@ export class Dialog extends Widget {
return this._promise.promise;
}
const promise = (this._promise = new PromiseDelegate>());
- let promises = Promise.all(Private.launchQueue);
+ const promises = Promise.all(Private.launchQueue);
Private.launchQueue.push(this._promise.promise);
return promises.then(() => {
Widget.attach(this, this._host);
@@ -219,7 +219,7 @@ export class Dialog extends Widget {
* A message handler invoked on an `'after-attach'` message.
*/
protected onAfterAttach(msg: Message): void {
- let node = this.node;
+ const node = this.node;
node.addEventListener('keydown', this, true);
node.addEventListener('contextmenu', this, true);
node.addEventListener('click', this, true);
@@ -227,8 +227,8 @@ export class Dialog extends Widget {
this._first = Private.findFirstFocusable(this.node);
this._original = document.activeElement as HTMLElement;
if (this._focusNodeSelector) {
- let body = this.node.querySelector('.jp-Dialog-body');
- let el = body?.querySelector(this._focusNodeSelector);
+ const body = this.node.querySelector('.jp-Dialog-body');
+ const el = body?.querySelector(this._focusNodeSelector);
if (el) {
this._primary = el as HTMLElement;
@@ -241,7 +241,7 @@ export class Dialog extends Widget {
* A message handler invoked on an `'after-detach'` message.
*/
protected onAfterDetach(msg: Message): void {
- let node = this.node;
+ const node = this.node;
node.removeEventListener('keydown', this, true);
node.removeEventListener('contextmenu', this, true);
node.removeEventListener('click', this, true);
@@ -265,7 +265,7 @@ export class Dialog extends Widget {
* @param event - The DOM event sent to the widget
*/
protected _evtClick(event: MouseEvent): void {
- let content = this.node.getElementsByClassName(
+ const content = this.node.getElementsByClassName(
'jp-Dialog-content'
)[0] as HTMLElement;
if (!content.contains(event.target as HTMLElement)) {
@@ -274,9 +274,9 @@ export class Dialog extends Widget {
this.reject();
return;
}
- for (let buttonNode of this._buttonNodes) {
+ for (const buttonNode of this._buttonNodes) {
if (buttonNode.contains(event.target as HTMLElement)) {
- let index = this._buttonNodes.indexOf(buttonNode);
+ const index = this._buttonNodes.indexOf(buttonNode);
this.resolve(index);
}
}
@@ -297,7 +297,7 @@ export class Dialog extends Widget {
break;
case 9: // Tab.
// Handle a tab on the last button.
- let node = this._buttonNodes[this._buttons.length - 1];
+ const node = this._buttonNodes[this._buttons.length - 1];
if (document.activeElement === node && !event.shiftKey) {
event.stopPropagation();
event.preventDefault();
@@ -320,7 +320,7 @@ export class Dialog extends Widget {
* @param event - The DOM event sent to the widget
*/
protected _evtFocus(event: FocusEvent): void {
- let target = event.target as HTMLElement;
+ const target = event.target as HTMLElement;
if (!this.node.contains(target as HTMLElement)) {
event.stopPropagation();
this._buttonNodes[this._defaultButton].focus();
@@ -339,7 +339,7 @@ export class Dialog extends Widget {
}
this._promise = null;
ArrayExt.removeFirstOf(Private.launchQueue, promise.promise);
- let body = this._body;
+ const body = this._body;
let value: T | null = null;
if (
button.accept &&
@@ -541,7 +541,7 @@ export namespace Dialog {
*/
export function createButton(value: Partial): Readonly {
value.accept = value.accept !== false;
- let defaultLabel = value.accept ? 'OK' : 'Cancel';
+ const defaultLabel = value.accept ? 'OK' : 'Cancel';
return {
label: value.label || defaultLabel,
iconClass: value.iconClass || '',
@@ -651,7 +651,7 @@ export namespace Dialog {
* @returns A widget for the footer.
*/
createFooter(buttons: ReadonlyArray): Widget {
- let footer = new Widget();
+ const footer = new Widget();
footer.addClass('jp-Dialog-footer');
each(buttons, button => {
footer.node.appendChild(button);
@@ -697,7 +697,7 @@ export namespace Dialog {
}
// Add the extra class.
- let extra = data.className;
+ const extra = data.className;
if (extra) {
name += ` ${extra}`;
}
@@ -728,8 +728,8 @@ export namespace Dialog {
* @returns The full class name for the item icon.
*/
createIconClass(data: IButton): string {
- let name = 'jp-Dialog-buttonIcon';
- let extra = data.iconClass;
+ const name = 'jp-Dialog-buttonIcon';
+ const extra = data.iconClass;
return extra ? `${name} ${extra}` : name;
}
@@ -769,9 +769,9 @@ namespace Private {
/**
* The queue for launching dialogs.
*/
- export let launchQueue: Promise>[] = [];
+ export const launchQueue: Promise>[] = [];
- export let errorMessagePromiseCache: Map> = new Map();
+ export const errorMessagePromiseCache: Map> = new Map();
/**
* Handle the input options for a dialog.
@@ -783,7 +783,10 @@ namespace Private {
export function handleOptions(
options: Partial> = {}
): Dialog.IOptions {
- let buttons = options.buttons || [Dialog.cancelButton(), Dialog.okButton()];
+ const buttons = options.buttons || [
+ Dialog.cancelButton(),
+ Dialog.okButton()
+ ];
let defaultButton = buttons.length - 1;
if (options.defaultButton !== undefined) {
defaultButton = options.defaultButton;
@@ -803,7 +806,7 @@ namespace Private {
* Find the first focusable item in the dialog.
*/
export function findFirstFocusable(node: HTMLElement): HTMLElement {
- let candidateSelectors = [
+ const candidateSelectors = [
'input',
'select',
'a[href]',
diff --git a/packages/apputils/src/hoverbox.ts b/packages/apputils/src/hoverbox.ts
index 686a1f73810b..a502fcbc4520 100644
--- a/packages/apputils/src/hoverbox.ts
+++ b/packages/apputils/src/hoverbox.ts
@@ -187,7 +187,7 @@ export namespace HoverBox {
}
// Move left to fit in the window.
- let right = node.getBoundingClientRect().right;
+ const right = node.getBoundingClientRect().right;
if (right > window.innerWidth) {
left -= right - window.innerWidth;
node.style.left = `${Math.ceil(left)}px`;
diff --git a/packages/apputils/src/iframe.ts b/packages/apputils/src/iframe.ts
index 672d9b78f7b8..520774b1fd65 100644
--- a/packages/apputils/src/iframe.ts
+++ b/packages/apputils/src/iframe.ts
@@ -141,8 +141,8 @@ namespace Private {
* Create the main content node of an iframe widget.
*/
export function createNode(): HTMLElement {
- let node = document.createElement('div');
- let iframe = document.createElement('iframe');
+ const node = document.createElement('div');
+ const iframe = document.createElement('iframe');
iframe.setAttribute('sandbox', '');
iframe.style.height = '100%';
iframe.style.width = '100%';
diff --git a/packages/apputils/src/inputdialog.ts b/packages/apputils/src/inputdialog.ts
index 2fbd757ca9ef..f63b839f67ab 100644
--- a/packages/apputils/src/inputdialog.ts
+++ b/packages/apputils/src/inputdialog.ts
@@ -227,7 +227,7 @@ class InputDialogBase extends Widget implements Dialog.IBodyWidget {
this.addClass(INPUT_DIALOG_CLASS);
if (label !== undefined) {
- let labelElement = document.createElement('label');
+ const labelElement = document.createElement('label');
labelElement.textContent = label;
// Initialize the node
@@ -388,7 +388,7 @@ class InputItemsDialog extends InputDialogBase {
this._list = document.createElement('select');
options.items.forEach((item, index) => {
- let option = document.createElement('option');
+ const option = document.createElement('option');
if (index === defaultIndex) {
option.selected = true;
current = item;
@@ -400,7 +400,7 @@ class InputItemsDialog extends InputDialogBase {
if (options.editable) {
/* Use of list and datalist */
- let data = document.createElement('datalist');
+ const data = document.createElement('datalist');
data.id = 'input-dialog-items';
data.appendChild(this._list);
diff --git a/packages/apputils/src/sessioncontext.tsx b/packages/apputils/src/sessioncontext.tsx
index 3ccedf129146..bfc8dce5ecfe 100644
--- a/packages/apputils/src/sessioncontext.tsx
+++ b/packages/apputils/src/sessioncontext.tsx
@@ -440,7 +440,7 @@ export class SessionContext implements ISessionContext {
* kernel.
*/
get kernelDisplayName(): string {
- let kernel = this.session?.kernel;
+ const kernel = this.session?.kernel;
if (this._pendingKernelName === Private.NO_KERNEL) {
return Private.NO_KERNEL;
}
@@ -485,7 +485,7 @@ export class SessionContext implements ISessionContext {
* the user.
*/
get kernelDisplayStatus(): ISessionContext.KernelDisplayStatus {
- let kernel = this.session?.kernel;
+ const kernel = this.session?.kernel;
if (this._pendingKernelName === Private.NO_KERNEL) {
return 'idle';
}
@@ -629,15 +629,15 @@ export class SessionContext implements ISessionContext {
* This makes it easier to consolidate promise handling logic.
*/
async _initialize(): Promise {
- let manager = this.sessionManager;
+ const manager = this.sessionManager;
await manager.ready;
await manager.refreshRunning();
- let model = find(manager.running(), item => {
+ const model = find(manager.running(), item => {
return item.path === this._path;
});
if (model) {
try {
- let session = manager.connectTo({ model });
+ const session = manager.connectTo({ model });
this._handleNewSession(session);
} catch (err) {
void this._handleSessionError(err);
@@ -676,7 +676,7 @@ export class SessionContext implements ISessionContext {
* @returns Whether to ask the user to pick a kernel.
*/
private async _startIfNecessary(): Promise {
- let preference = this.kernelPreference;
+ const preference = this.kernelPreference;
if (
this.isDisposed ||
this.session?.kernel ||
@@ -691,7 +691,7 @@ export class SessionContext implements ISessionContext {
if (preference.id) {
options = { id: preference.id };
} else {
- let name = SessionContext.getDefaultKernel({
+ const name = SessionContext.getDefaultKernel({
specs: this.specsManager.specs,
sessions: this.sessionManager.running(),
preference
@@ -1109,7 +1109,7 @@ export const sessionContextDialogs: ISessionContext.IDialogs = {
Dialog.okButton({ label: 'Select' })
];
- let dialog = new Dialog({
+ const dialog = new Dialog({
title: 'Select Kernel',
body: new Private.KernelSelector(sessionContext),
buttons
@@ -1119,7 +1119,7 @@ export const sessionContextDialogs: ISessionContext.IDialogs = {
if (sessionContext.isDisposed || !result.button.accept) {
return;
}
- let model = result.value;
+ const model = result.value;
if (
model === null &&
sessionContext.kernelDisplayName !== Private.NO_KERNEL
@@ -1146,7 +1146,7 @@ export const sessionContextDialogs: ISessionContext.IDialogs = {
if (sessionContext.isDisposed) {
throw new Error('session already disposed');
}
- let kernel = sessionContext.session?.kernel;
+ const kernel = sessionContext.session?.kernel;
if (!kernel && sessionContext.prevKernelName) {
await sessionContext.changeKernel({
name: sessionContext.prevKernelName
@@ -1158,7 +1158,7 @@ export const sessionContextDialogs: ISessionContext.IDialogs = {
throw new Error('No kernel to restart');
}
- let restartBtn = Dialog.warnButton({ label: 'Restart' });
+ const restartBtn = Dialog.warnButton({ label: 'Restart' });
const result = await showDialog({
title: 'Restart Kernel?',
body:
@@ -1201,7 +1201,7 @@ namespace Private {
* Get the value of the kernel selector widget.
*/
getValue(): Kernel.IModel {
- let selector = this.node.querySelector('select') as HTMLSelectElement;
+ const selector = this.node.querySelector('select') as HTMLSelectElement;
return JSON.parse(selector.value) as Kernel.IModel;
}
}
@@ -1211,13 +1211,13 @@ namespace Private {
*/
function createSelectorNode(sessionContext: ISessionContext) {
// Create the dialog body.
- let body = document.createElement('div');
- let text = document.createElement('label');
+ const body = document.createElement('div');
+ const text = document.createElement('label');
text.textContent = `Select kernel for: "${sessionContext.name}"`;
body.appendChild(text);
- let options = getKernelSearch(sessionContext);
- let selector = document.createElement('select');
+ const options = getKernelSearch(sessionContext);
+ const selector = document.createElement('select');
populateKernelSelect(selector, options);
body.appendChild(selector);
return body;
@@ -1229,8 +1229,8 @@ namespace Private {
export function getDefaultKernel(
options: SessionContext.IKernelSearch
): string | null {
- let { specs, preference } = options;
- let {
+ const { specs, preference } = options;
+ const {
name,
language,
shouldStart,
@@ -1242,14 +1242,14 @@ namespace Private {
return null;
}
- let defaultName = autoStartDefault ? specs.default : null;
+ const defaultName = autoStartDefault ? specs.default : null;
if (!name && !language) {
return defaultName;
}
// Look for an exact match of a spec name.
- for (let specName in specs.kernelspecs) {
+ for (const specName in specs.kernelspecs) {
if (specName === name) {
return name;
}
@@ -1261,17 +1261,17 @@ namespace Private {
}
// Check for a single kernel matching the language.
- let matches: string[] = [];
- for (let specName in specs.kernelspecs) {
- let kernelLanguage = specs.kernelspecs[specName]?.language;
+ const matches: string[] = [];
+ for (const specName in specs.kernelspecs) {
+ const kernelLanguage = specs.kernelspecs[specName]?.language;
if (language === kernelLanguage) {
matches.push(specName);
}
}
if (matches.length === 1) {
- let specName = matches[0];
- console.log(
+ const specName = matches[0];
+ console.warn(
'No exact match found for ' +
specName +
', using kernel ' +
@@ -1298,8 +1298,8 @@ namespace Private {
node.removeChild(node.firstChild);
}
- let { preference, sessions, specs } = options;
- let { name, id, language, canStart, shouldStart } = preference;
+ const { preference, sessions, specs } = options;
+ const { name, id, language, canStart, shouldStart } = preference;
if (!specs || canStart === false) {
node.appendChild(optionForNone());
@@ -1311,23 +1311,23 @@ namespace Private {
node.disabled = false;
// Create mappings of display names and languages for kernel name.
- let displayNames: { [key: string]: string } = Object.create(null);
- let languages: { [key: string]: string } = Object.create(null);
- for (let name in specs.kernelspecs) {
- let spec = specs.kernelspecs[name]!;
+ const displayNames: { [key: string]: string } = Object.create(null);
+ const languages: { [key: string]: string } = Object.create(null);
+ for (const name in specs.kernelspecs) {
+ const spec = specs.kernelspecs[name]!;
displayNames[name] = spec.display_name;
languages[name] = spec.language;
}
// Handle a kernel by name.
- let names: string[] = [];
+ const names: string[] = [];
if (name && name in specs.kernelspecs) {
names.push(name);
}
// Then look by language.
if (language) {
- for (let specName in specs.kernelspecs) {
+ for (const specName in specs.kernelspecs) {
if (name !== specName && languages[specName] === language) {
names.push(specName);
}
@@ -1340,11 +1340,11 @@ namespace Private {
}
// Handle a preferred kernels in order of display name.
- let preferred = document.createElement('optgroup');
+ const preferred = document.createElement('optgroup');
preferred.label = 'Start Preferred Kernel';
names.sort((a, b) => displayNames[a].localeCompare(displayNames[b]));
- for (let name of names) {
+ for (const name of names) {
preferred.appendChild(optionForName(name, displayNames[name]));
}
@@ -1355,19 +1355,19 @@ namespace Private {
// Add an option for no kernel
node.appendChild(optionForNone());
- let other = document.createElement('optgroup');
+ const other = document.createElement('optgroup');
other.label = 'Start Other Kernel';
// Add the rest of the kernel names in alphabetical order.
- let otherNames: string[] = [];
- for (let specName in specs.kernelspecs) {
+ const otherNames: string[] = [];
+ for (const specName in specs.kernelspecs) {
if (names.indexOf(specName) !== -1) {
continue;
}
otherNames.push(specName);
}
otherNames.sort((a, b) => displayNames[a].localeCompare(displayNames[b]));
- for (let otherName of otherNames) {
+ for (const otherName of otherNames) {
other.appendChild(optionForName(otherName, displayNames[otherName]));
}
// Add a separator option if there were any other names.
@@ -1388,8 +1388,8 @@ namespace Private {
}
// Add the sessions using the preferred language first.
- let matchingSessions: Session.IModel[] = [];
- let otherSessions: Session.IModel[] = [];
+ const matchingSessions: Session.IModel[] = [];
+ const otherSessions: Session.IModel[] = [];
each(sessions, session => {
if (
@@ -1404,7 +1404,7 @@ namespace Private {
}
});
- let matching = document.createElement('optgroup');
+ const matching = document.createElement('optgroup');
matching.label = 'Use Kernel from Preferred Session';
node.appendChild(matching);
@@ -1414,12 +1414,12 @@ namespace Private {
});
each(matchingSessions, session => {
- let name = session.kernel ? displayNames[session.kernel.name] : '';
+ const name = session.kernel ? displayNames[session.kernel.name] : '';
matching.appendChild(optionForSession(session, name));
});
}
- let otherSessionsNode = document.createElement('optgroup');
+ const otherSessionsNode = document.createElement('optgroup');
otherSessionsNode.label = 'Use Kernel from Other Session';
node.appendChild(otherSessionsNode);
@@ -1429,7 +1429,7 @@ namespace Private {
});
each(otherSessions, session => {
- let name = session.kernel
+ const name = session.kernel
? displayNames[session.kernel.name] || session.kernel.name
: '';
otherSessionsNode.appendChild(optionForSession(session, name));
@@ -1454,7 +1454,7 @@ namespace Private {
* Create an option element for a kernel name.
*/
function optionForName(name: string, displayName: string): HTMLOptionElement {
- let option = document.createElement('option');
+ const option = document.createElement('option');
option.text = displayName;
option.value = JSON.stringify({ name });
return option;
@@ -1464,9 +1464,9 @@ namespace Private {
* Create an option for no kernel.
*/
function optionForNone(): HTMLOptGroupElement {
- let group = document.createElement('optgroup');
+ const group = document.createElement('optgroup');
group.label = 'Use No Kernel';
- let option = document.createElement('option');
+ const option = document.createElement('option');
option.text = Private.NO_KERNEL;
option.value = 'null';
group.appendChild(option);
@@ -1480,8 +1480,8 @@ namespace Private {
session: Session.IModel,
displayName: string
): HTMLOptionElement {
- let option = document.createElement('option');
- let sessionName = session.name || PathExt.basename(session.path);
+ const option = document.createElement('option');
+ const sessionName = session.name || PathExt.basename(session.path);
option.text = sessionName;
option.value = JSON.stringify({ id: session.kernel?.id });
option.title =
diff --git a/packages/apputils/src/spinner.ts b/packages/apputils/src/spinner.ts
index 52483cee61ba..f951e43888e5 100644
--- a/packages/apputils/src/spinner.ts
+++ b/packages/apputils/src/spinner.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -18,7 +18,7 @@ export class Spinner extends Widget {
super();
this.addClass('jp-Spinner');
this.node.tabIndex = -1;
- let content = document.createElement('div');
+ const content = document.createElement('div');
content.className = 'jp-SpinnerContent';
this.node.appendChild(content);
}
diff --git a/packages/apputils/src/styling.ts b/packages/apputils/src/styling.ts
index 2ee01dcb22e3..b0832a533475 100644
--- a/packages/apputils/src/styling.ts
+++ b/packages/apputils/src/styling.ts
@@ -41,9 +41,9 @@ export namespace Styling {
if (node.localName === 'select') {
wrapSelect(node as HTMLSelectElement);
}
- let nodes = node.getElementsByTagName(tagName);
+ const nodes = node.getElementsByTagName(tagName);
for (let i = 0; i < nodes.length; i++) {
- let child = nodes[i];
+ const child = nodes[i];
child.classList.add('jp-mod-styled');
if (className) {
child.classList.add(className);
@@ -58,7 +58,7 @@ export namespace Styling {
* Wrap a select node.
*/
export function wrapSelect(node: HTMLSelectElement): HTMLElement {
- let wrapper = document.createElement('div');
+ const wrapper = document.createElement('div');
wrapper.classList.add('jp-select-wrapper');
node.addEventListener('focus', Private.onFocus);
node.addEventListener('blur', Private.onFocus);
@@ -91,8 +91,8 @@ namespace Private {
* Handle a focus event on a styled select.
*/
export function onFocus(event: FocusEvent): void {
- let target = event.target as Element;
- let parent = target.parentElement;
+ const target = event.target as Element;
+ const parent = target.parentElement;
if (!parent) {
return;
}
diff --git a/packages/apputils/src/toolbar.tsx b/packages/apputils/src/toolbar.tsx
index 1b1c779481b8..6f334c2580d1 100644
--- a/packages/apputils/src/toolbar.tsx
+++ b/packages/apputils/src/toolbar.tsx
@@ -187,7 +187,7 @@ export class Toolbar extends Widget {
* @returns An iterator over the toolbar item names.
*/
names(): IIterator {
- let layout = this.layout as ToolbarLayout;
+ const layout = this.layout as ToolbarLayout;
return map(layout.widgets, widget => {
return Private.nameProperty.get(widget);
});
@@ -209,7 +209,7 @@ export class Toolbar extends Widget {
* The item can be removed from the toolbar by setting its parent to `null`.
*/
addItem(name: string, widget: T): boolean {
- let layout = this.layout as ToolbarLayout;
+ const layout = this.layout as ToolbarLayout;
return this.insertItem(layout.widgets.length, name, widget);
}
@@ -230,12 +230,12 @@ export class Toolbar extends Widget {
* The item can be removed from the toolbar by setting its parent to `null`.
*/
insertItem(index: number, name: string, widget: T): boolean {
- let existing = find(this.names(), value => value === name);
+ const existing = find(this.names(), value => value === name);
if (existing) {
return false;
}
widget.addClass(TOOLBAR_ITEM_CLASS);
- let layout = this.layout as ToolbarLayout;
+ const layout = this.layout as ToolbarLayout;
layout.insertWidget(index, widget);
Private.nameProperty.set(widget, name);
return true;
@@ -287,10 +287,10 @@ export class Toolbar extends Widget {
name: string,
widget: T
): boolean {
- let nameWithIndex = map(this.names(), (name, i) => {
+ const nameWithIndex = map(this.names(), (name, i) => {
return { name: name, index: i };
});
- let target = find(nameWithIndex, x => x.name === at);
+ const target = find(nameWithIndex, x => x.name === at);
if (target) {
return this.insertItem(target.index + offset, name, widget);
}
@@ -609,7 +609,7 @@ namespace Private {
export function propsFromCommand(
options: CommandToolbarButtonComponent.IProps
): ToolbarButtonComponent.IProps {
- let { commands, id, args } = options;
+ const { commands, id, args } = options;
const iconClass = commands.iconClass(id, args);
const iconLabel = commands.iconLabel(id, args);
@@ -727,7 +727,7 @@ namespace Private {
return;
}
- let status = sessionContext.kernelDisplayStatus;
+ const status = sessionContext.kernelDisplayStatus;
// set the icon
if (this._isBusy(status)) {
diff --git a/packages/apputils/src/vdom.ts b/packages/apputils/src/vdom.ts
index dc2e1161ea09..6d540ed60971 100644
--- a/packages/apputils/src/vdom.ts
+++ b/packages/apputils/src/vdom.ts
@@ -76,7 +76,7 @@ export abstract class ReactWidget extends Widget {
*/
private renderDOM(): Promise {
return new Promise(resolve => {
- let vnode = this.render();
+ const vnode = this.render();
// Split up the array/element cases so type inference chooses the right
// signature.
if (Array.isArray(vnode)) {
diff --git a/packages/apputils/src/windowresolver.ts b/packages/apputils/src/windowresolver.ts
index d6b869c32844..fdb96648d098 100644
--- a/packages/apputils/src/windowresolver.ts
+++ b/packages/apputils/src/windowresolver.ts
@@ -107,12 +107,12 @@ namespace Private {
/**
* The window name promise.
*/
- let delegate = new PromiseDelegate();
+ const delegate = new PromiseDelegate();
/**
* The known window names.
*/
- let known: { [window: string]: null } = {};
+ const known: { [window: string]: null } = {};
/**
* The window name.
diff --git a/packages/attachments/src/index.ts b/packages/attachments/src/index.ts
index e6f235adbe07..56d8e76c00d7 100644
--- a/packages/attachments/src/index.ts
+++ b/packages/attachments/src/index.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
diff --git a/packages/attachments/src/model.ts b/packages/attachments/src/model.ts
index 973e4d0d6b7d..d39a0057f60b 100644
--- a/packages/attachments/src/model.ts
+++ b/packages/attachments/src/model.ts
@@ -145,7 +145,7 @@ export class AttachmentsModel implements IAttachmentsModel {
this.contentFactory =
options.contentFactory || AttachmentsModel.defaultContentFactory;
if (options.values) {
- for (let key of Object.keys(options.values)) {
+ for (const key of Object.keys(options.values)) {
if (options.values[key] !== undefined) {
this.set(key, options.values[key]!);
}
@@ -238,7 +238,7 @@ export class AttachmentsModel implements IAttachmentsModel {
*/
set(key: string, value: nbformat.IMimeBundle): void {
// Normalize stream data.
- let item = this._createItem({ value });
+ const item = this._createItem({ value });
this._map.set(key, item);
}
@@ -278,8 +278,8 @@ export class AttachmentsModel implements IAttachmentsModel {
* Serialize the model to JSON.
*/
toJSON(): nbformat.IAttachments {
- let ret: nbformat.IAttachments = {};
- for (let key of this._map.keys()) {
+ const ret: nbformat.IAttachments = {};
+ for (const key of this._map.keys()) {
ret[key] = this._map.get(key)!.toJSON();
}
return ret;
@@ -289,8 +289,8 @@ export class AttachmentsModel implements IAttachmentsModel {
* Create an attachment item and hook up its signals.
*/
private _createItem(options: IAttachmentModel.IOptions): IAttachmentModel {
- let factory = this.contentFactory;
- let item = factory.createAttachmentModel(options);
+ const factory = this.contentFactory;
+ const item = factory.createAttachmentModel(options);
item.changed.connect(this._onGenericChange, this);
return item;
}
diff --git a/packages/cells/src/celldragutils.ts b/packages/cells/src/celldragutils.ts
index 8a243c7184c9..f44ea59a49bf 100644
--- a/packages/cells/src/celldragutils.ts
+++ b/packages/cells/src/celldragutils.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -125,8 +125,8 @@ export namespace CellDragUtils {
nextX: number,
nextY: number
): boolean {
- let dx = Math.abs(nextX - prevX);
- let dy = Math.abs(nextY - prevY);
+ const dx = Math.abs(nextX - prevX);
+ const dy = Math.abs(nextY - prevY);
return dx >= DRAG_THRESHOLD || dy >= DRAG_THRESHOLD;
}
@@ -143,7 +143,8 @@ export namespace CellDragUtils {
const count = selectedCells.length;
let promptNumber: string;
if (activeCell.model.type === 'code') {
- let executionCount = (activeCell.model as ICodeCellModel).executionCount;
+ const executionCount = (activeCell.model as ICodeCellModel)
+ .executionCount;
promptNumber = ' ';
if (executionCount) {
promptNumber = executionCount.toString();
diff --git a/packages/cells/src/collapser.tsx b/packages/cells/src/collapser.tsx
index e53bf3f3f1ca..0f03aeb0d749 100644
--- a/packages/cells/src/collapser.tsx
+++ b/packages/cells/src/collapser.tsx
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -57,7 +57,7 @@ export abstract class Collapser extends ReactWidget {
* Render the collapser with the virtual DOM.
*/
protected render(): React.ReactElement {
- let childClass = COLLAPSER_CHILD_CLASS;
+ const childClass = COLLAPSER_CHILD_CLASS;
return this.handleClick(e)} />;
}
@@ -83,7 +83,7 @@ export class InputCollapser extends Collapser {
* Is the cell's input collapsed?
*/
get collapsed(): boolean {
- let cell = this.parent?.parent as Cell | undefined | null;
+ const cell = this.parent?.parent as Cell | undefined | null;
if (cell) {
return cell.inputHidden;
} else {
@@ -95,7 +95,7 @@ export class InputCollapser extends Collapser {
* Handle a click event for the user to collapse the cell's input.
*/
protected handleClick(e: React.MouseEvent
): void {
- let cell = this.parent?.parent as Cell | undefined | null;
+ const cell = this.parent?.parent as Cell | undefined | null;
if (cell) {
cell.inputHidden = !cell.inputHidden;
}
@@ -120,7 +120,7 @@ export class OutputCollapser extends Collapser {
* Is the cell's output collapsed?
*/
get collapsed(): boolean {
- let cell = this.parent?.parent as CodeCell | undefined | null;
+ const cell = this.parent?.parent as CodeCell | undefined | null;
if (cell) {
return cell.outputHidden;
} else {
@@ -132,7 +132,7 @@ export class OutputCollapser extends Collapser {
* Handle a click event for the user to collapse the cell's output.
*/
protected handleClick(e: React.MouseEvent): void {
- let cell = this.parent?.parent as CodeCell | undefined | null;
+ const cell = this.parent?.parent as CodeCell | undefined | null;
if (cell) {
cell.outputHidden = !cell.outputHidden;
}
diff --git a/packages/cells/src/headerfooter.ts b/packages/cells/src/headerfooter.ts
index 45ab296926d6..bb1ba6283806 100644
--- a/packages/cells/src/headerfooter.ts
+++ b/packages/cells/src/headerfooter.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
diff --git a/packages/cells/src/index.ts b/packages/cells/src/index.ts
index 39967bf3c55d..ace44899a338 100644
--- a/packages/cells/src/index.ts
+++ b/packages/cells/src/index.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
diff --git a/packages/cells/src/inputarea.ts b/packages/cells/src/inputarea.ts
index 7c80f7dfce56..ebd45b387be3 100644
--- a/packages/cells/src/inputarea.ts
+++ b/packages/cells/src/inputarea.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -33,7 +33,7 @@ const INPUT_PROMPT_CLASS = 'jp-InputPrompt';
*/
const INPUT_AREA_EDITOR_CLASS = 'jp-InputArea-editor';
-/******************************************************************************
+/** ****************************************************************************
* InputArea
******************************************************************************/
@@ -47,24 +47,24 @@ export class InputArea extends Widget {
constructor(options: InputArea.IOptions) {
super();
this.addClass(INPUT_AREA_CLASS);
- let model = (this.model = options.model);
- let contentFactory = (this.contentFactory =
+ const model = (this.model = options.model);
+ const contentFactory = (this.contentFactory =
options.contentFactory || InputArea.defaultContentFactory);
// Prompt
- let prompt = (this._prompt = contentFactory.createInputPrompt());
+ const prompt = (this._prompt = contentFactory.createInputPrompt());
prompt.addClass(INPUT_AREA_PROMPT_CLASS);
// Editor
- let editorOptions = {
+ const editorOptions = {
model,
factory: contentFactory.editorFactory,
updateOnShow: options.updateOnShow
};
- let editor = (this._editor = new CodeEditorWrapper(editorOptions));
+ const editor = (this._editor = new CodeEditorWrapper(editorOptions));
editor.addClass(INPUT_AREA_EDITOR_CLASS);
- let layout = (this.layout = new PanelLayout());
+ const layout = (this.layout = new PanelLayout());
layout.addWidget(prompt);
layout.addWidget(editor);
}
@@ -104,7 +104,7 @@ export class InputArea extends Widget {
* Render an input instead of the text editor.
*/
renderInput(widget: Widget): void {
- let layout = this.layout as PanelLayout;
+ const layout = this.layout as PanelLayout;
if (this._rendered) {
this._rendered.parent = null;
}
@@ -248,7 +248,7 @@ export namespace InputArea {
* A function to create the default CodeMirror editor factory.
*/
function _createDefaultEditorFactory(): CodeEditor.Factory {
- let editorServices = new CodeMirrorEditorFactory();
+ const editorServices = new CodeMirrorEditorFactory();
return editorServices.newInlineEditor;
}
@@ -263,7 +263,7 @@ export namespace InputArea {
export const defaultContentFactory = new ContentFactory({});
}
-/******************************************************************************
+/** ****************************************************************************
* InputPrompt
******************************************************************************/
diff --git a/packages/cells/src/model.ts b/packages/cells/src/model.ts
index 0c37c7375cf1..cb705162fedf 100644
--- a/packages/cells/src/model.ts
+++ b/packages/cells/src/model.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -168,14 +168,14 @@ export class CellModel extends CodeEditor.Model implements ICellModel {
this.value.changed.connect(this.onGenericChange, this);
- let cellType = this.modelDB.createValue('type');
+ const cellType = this.modelDB.createValue('type');
cellType.set(this.type);
- let observableMetadata = this.modelDB.createMap('metadata');
+ const observableMetadata = this.modelDB.createMap('metadata');
observableMetadata.changed.connect(this.onGenericChange, this);
- let cell = options.cell;
- let trusted = this.modelDB.createValue('trusted');
+ const cell = options.cell;
+ const trusted = this.modelDB.createValue('trusted');
trusted.changed.connect(this.onTrustedChanged, this);
if (!cell) {
@@ -190,7 +190,7 @@ export class CellModel extends CodeEditor.Model implements ICellModel {
} else {
this.value.text = cell.source as string;
}
- let metadata = JSONExt.deepCopy(cell.metadata);
+ const metadata = JSONExt.deepCopy(cell.metadata);
if (this.type !== 'raw') {
delete metadata['format'];
}
@@ -199,7 +199,7 @@ export class CellModel extends CodeEditor.Model implements ICellModel {
delete metadata['scrolled'];
}
- for (let key in metadata) {
+ for (const key in metadata) {
observableMetadata.set(key, metadata[key]);
}
}
@@ -242,7 +242,7 @@ export class CellModel extends CodeEditor.Model implements ICellModel {
* Set the trusted state of the model.
*/
set trusted(newValue: boolean) {
- let oldValue = this.trusted;
+ const oldValue = this.trusted;
if (oldValue === newValue) {
return;
}
@@ -253,9 +253,9 @@ export class CellModel extends CodeEditor.Model implements ICellModel {
* Serialize the model to JSON.
*/
toJSON(): nbformat.ICell {
- let metadata: nbformat.IBaseCellMetadata = Object.create(null);
- for (let key of this.metadata.keys()) {
- let value = JSON.parse(JSON.stringify(this.metadata.get(key)));
+ const metadata: nbformat.IBaseCellMetadata = Object.create(null);
+ for (const key of this.metadata.keys()) {
+ const value = JSON.parse(JSON.stringify(this.metadata.get(key)));
metadata[key] = value as JSONValue;
}
if (this.trusted) {
@@ -322,10 +322,10 @@ export class AttachmentsCellModel extends CellModel {
*/
constructor(options: AttachmentsCellModel.IOptions) {
super(options);
- let factory =
+ const factory =
options.contentFactory || AttachmentsCellModel.defaultContentFactory;
let attachments: nbformat.IAttachments | undefined;
- let cell = options.cell;
+ const cell = options.cell;
if (cell && (cell.cell_type === 'raw' || cell.cell_type === 'markdown')) {
attachments = (cell as nbformat.IRawCell | nbformat.IMarkdownCell)
.attachments;
@@ -349,7 +349,7 @@ export class AttachmentsCellModel extends CellModel {
* Serialize the model to JSON.
*/
toJSON(): nbformat.IRawCell | nbformat.IMarkdownCell {
- let cell = super.toJSON() as nbformat.IRawCell | nbformat.IMarkdownCell;
+ const cell = super.toJSON() as nbformat.IRawCell | nbformat.IMarkdownCell;
if (this.attachments.length) {
cell.attachments = this.attachments.toJSON();
}
@@ -461,11 +461,12 @@ export class CodeCellModel extends CellModel implements ICodeCellModel {
*/
constructor(options: CodeCellModel.IOptions) {
super(options);
- let factory = options.contentFactory || CodeCellModel.defaultContentFactory;
- let trusted = this.trusted;
- let cell = options.cell as nbformat.ICodeCell;
+ const factory =
+ options.contentFactory || CodeCellModel.defaultContentFactory;
+ const trusted = this.trusted;
+ const cell = options.cell as nbformat.ICodeCell;
let outputs: nbformat.IOutput[] = [];
- let executionCount = this.modelDB.createValue('executionCount');
+ const executionCount = this.modelDB.createValue('executionCount');
if (!executionCount.get()) {
if (cell && cell.cell_type === 'code') {
executionCount.set(cell.execution_count || null);
@@ -487,7 +488,7 @@ export class CodeCellModel extends CellModel implements ICodeCellModel {
// Sync `collapsed` and `jupyter.outputs_hidden` for the first time, giving
// preference to `collapsed`.
if (this.metadata.has('collapsed')) {
- let collapsed = this.metadata.get('collapsed') as boolean | undefined;
+ const collapsed = this.metadata.get('collapsed') as boolean | undefined;
Private.collapseChanged(this.metadata, {
type: 'change',
key: 'collapsed',
@@ -495,7 +496,7 @@ export class CodeCellModel extends CellModel implements ICodeCellModel {
newValue: collapsed
});
} else if (this.metadata.has('jupyter')) {
- let jupyter = this.metadata.get('jupyter') as JSONObject;
+ const jupyter = this.metadata.get('jupyter') as JSONObject;
if (jupyter.hasOwnProperty('outputs_hidden')) {
Private.collapseChanged(this.metadata, {
type: 'change',
@@ -521,7 +522,7 @@ export class CodeCellModel extends CellModel implements ICodeCellModel {
return this.modelDB.getValue('executionCount') as nbformat.ExecutionCount;
}
set executionCount(newValue: nbformat.ExecutionCount) {
- let oldValue = this.executionCount;
+ const oldValue = this.executionCount;
if (newValue === oldValue) {
return;
}
@@ -557,7 +558,7 @@ export class CodeCellModel extends CellModel implements ICodeCellModel {
* Serialize the model to JSON.
*/
toJSON(): nbformat.ICodeCell {
- let cell = super.toJSON() as nbformat.ICodeCell;
+ const cell = super.toJSON() as nbformat.ICodeCell;
cell.execution_count = this.executionCount || null;
cell.outputs = this.outputs.toJSON();
return cell;
diff --git a/packages/cells/src/placeholder.tsx b/packages/cells/src/placeholder.tsx
index 87ad9eced947..2f578389b29f 100644
--- a/packages/cells/src/placeholder.tsx
+++ b/packages/cells/src/placeholder.tsx
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -59,7 +59,7 @@ export abstract class Placeholder extends ReactWidget {
* Handle the click event.
*/
protected handleClick(e: React.MouseEvent): void {
- let callback = this._callback;
+ const callback = this._callback;
callback(e);
}
diff --git a/packages/cells/src/widget.ts b/packages/cells/src/widget.ts
index 7dd1db0b0c45..9f82a511374e 100644
--- a/packages/cells/src/widget.ts
+++ b/packages/cells/src/widget.ts
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -164,7 +164,7 @@ const RENDER_TIMEOUT = 1000;
*/
const CONTENTS_MIME_RICH = 'application/x-jupyter-icontentsrich';
-/******************************************************************************
+/** ****************************************************************************
* Cell
******************************************************************************/
@@ -178,22 +178,22 @@ export class Cell extends Widget {
constructor(options: Cell.IOptions) {
super();
this.addClass(CELL_CLASS);
- let model = (this._model = options.model);
- let contentFactory = (this.contentFactory =
+ const model = (this._model = options.model);
+ const contentFactory = (this.contentFactory =
options.contentFactory || Cell.defaultContentFactory);
this.layout = new PanelLayout();
// Header
- let header = contentFactory.createCellHeader();
+ const header = contentFactory.createCellHeader();
header.addClass(CELL_HEADER_CLASS);
(this.layout as PanelLayout).addWidget(header);
// Input
- let inputWrapper = (this._inputWrapper = new Panel());
+ const inputWrapper = (this._inputWrapper = new Panel());
inputWrapper.addClass(CELL_INPUT_WRAPPER_CLASS);
- let inputCollapser = new InputCollapser();
+ const inputCollapser = new InputCollapser();
inputCollapser.addClass(CELL_INPUT_COLLAPSER_CLASS);
- let input = (this._input = new InputArea({
+ const input = (this._input = new InputArea({
model,
contentFactory,
updateOnShow: options.updateEditorOnShow
@@ -208,7 +208,7 @@ export class Cell extends Widget {
});
// Footer
- let footer = this.contentFactory.createCellFooter();
+ const footer = this.contentFactory.createCellFooter();
footer.addClass(CELL_FOOTER_CLASS);
(this.layout as PanelLayout).addWidget(footer);
@@ -351,7 +351,7 @@ export class Cell extends Widget {
if (this._inputHidden === value) {
return;
}
- let layout = this._inputWrapper.layout as PanelLayout;
+ const layout = this._inputWrapper.layout as PanelLayout;
if (value) {
this._input.parent = null;
layout.addWidget(this._inputPlaceholder);
@@ -447,7 +447,7 @@ export class Cell extends Widget {
* Clone the cell, using the same model.
*/
clone(): Cell {
- let constructor = this.constructor as typeof Cell;
+ const constructor = this.constructor as typeof Cell;
return new constructor({
model: this.model,
contentFactory: this.contentFactory
@@ -673,7 +673,7 @@ export namespace Cell {
export const defaultContentFactory = new ContentFactory();
}
-/******************************************************************************
+/** ****************************************************************************
* CodeCell
******************************************************************************/
@@ -689,16 +689,16 @@ export class CodeCell extends Cell {
this.addClass(CODE_CELL_CLASS);
// Only save options not handled by parent constructor.
- let rendermime = (this._rendermime = options.rendermime);
- let contentFactory = this.contentFactory;
- let model = this.model;
+ const rendermime = (this._rendermime = options.rendermime);
+ const contentFactory = this.contentFactory;
+ const model = this.model;
// Insert the output before the cell footer.
- let outputWrapper = (this._outputWrapper = new Panel());
+ const outputWrapper = (this._outputWrapper = new Panel());
outputWrapper.addClass(CELL_OUTPUT_WRAPPER_CLASS);
- let outputCollapser = new OutputCollapser();
+ const outputCollapser = new OutputCollapser();
outputCollapser.addClass(CELL_OUTPUT_COLLAPSER_CLASS);
- let output = (this._output = new OutputArea({
+ const output = (this._output = new OutputArea({
model: model.outputs,
rendermime,
contentFactory: contentFactory
@@ -758,7 +758,7 @@ export class CodeCell extends Cell {
if (this._outputHidden === value) {
return;
}
- let layout = this._outputWrapper.layout as PanelLayout;
+ const layout = this._outputWrapper.layout as PanelLayout;
if (value) {
layout.removeWidget(this._output);
layout.addWidget(this._outputPlaceholder);
@@ -909,7 +909,7 @@ export class CodeCell extends Cell {
* Clone the cell, using the same model.
*/
clone(): CodeCell {
- let constructor = this.constructor as typeof CodeCell;
+ const constructor = this.constructor as typeof CodeCell;
return new constructor({
model: this.model,
contentFactory: this.contentFactory,
@@ -991,7 +991,7 @@ export class CodeCell extends Cell {
* Handle changes in the number of outputs in the output area.
*/
private _outputLengthHandler(sender: OutputArea, args: number) {
- let force = args === 0 ? true : false;
+ const force = args === 0 ? true : false;
this.toggleClass(NO_OUTPUTS_CLASS, force);
}
@@ -1032,13 +1032,13 @@ export namespace CodeCell {
sessionContext: ISessionContext,
metadata?: JSONObject
): Promise {
- let model = cell.model;
- let code = model.value.text;
+ const model = cell.model;
+ const code = model.value.text;
if (!code.trim() || !sessionContext.session?.kernel) {
model.clearExecution();
return;
}
- let cellId = { cellId: model.id };
+ const cellId = { cellId: model.id };
metadata = {
...model.metadata.toJSON(),
...metadata,
@@ -1178,7 +1178,7 @@ export abstract class AttachmentsCell extends Cell {
*/
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
- let node = this.node;
+ const node = this.node;
node.addEventListener('lm-dragover', this);
node.addEventListener('lm-drop', this);
node.addEventListener('dragenter', this);
@@ -1192,7 +1192,7 @@ export abstract class AttachmentsCell extends Cell {
* message
*/
protected onBeforeDetach(msg: Message): void {
- let node = this.node;
+ const node = this.node;
node.removeEventListener('drop', this);
node.removeEventListener('dragover', this);
node.removeEventListener('dragenter', this);
@@ -1357,7 +1357,7 @@ export abstract class AttachmentsCell extends Cell {
readonly model: IAttachmentsCellModel;
}
-/******************************************************************************
+/** ****************************************************************************
* MarkdownCell
******************************************************************************/
@@ -1489,11 +1489,11 @@ export class MarkdownCell extends AttachmentsCell {
* Update the rendered input.
*/
private _updateRenderedInput(): Promise {
- let model = this.model;
- let text = (model && model.value.text) || DEFAULT_MARKDOWN_TEXT;
+ const model = this.model;
+ const text = (model && model.value.text) || DEFAULT_MARKDOWN_TEXT;
// Do not re-render if the text has not changed.
if (text !== this._prevText) {
- let mimeModel = new MimeModel({ data: { 'text/markdown': text } });
+ const mimeModel = new MimeModel({ data: { 'text/markdown': text } });
if (!this._renderer) {
this._renderer = this._rendermime.createRenderer('text/markdown');
this._renderer.addClass(MARKDOWN_OUTPUT_CLASS);
@@ -1508,7 +1508,7 @@ export class MarkdownCell extends AttachmentsCell {
* Clone the cell, using the same model.
*/
clone(): MarkdownCell {
- let constructor = this.constructor as typeof MarkdownCell;
+ const constructor = this.constructor as typeof MarkdownCell;
return new constructor({
model: this.model,
contentFactory: this.contentFactory,
@@ -1544,7 +1544,7 @@ export namespace MarkdownCell {
}
}
-/******************************************************************************
+/** ****************************************************************************
* RawCell
******************************************************************************/
@@ -1564,7 +1564,7 @@ export class RawCell extends Cell {
* Clone the cell, using the same model.
*/
clone(): RawCell {
- let constructor = this.constructor as typeof RawCell;
+ const constructor = this.constructor as typeof RawCell;
return new constructor({
model: this.model,
contentFactory: this.contentFactory
diff --git a/packages/celltags-extension/tsconfig.json b/packages/celltags-extension/tsconfig.json
index a68cc31546ae..eb95d15c2cca 100644
--- a/packages/celltags-extension/tsconfig.json
+++ b/packages/celltags-extension/tsconfig.json
@@ -31,5 +31,6 @@
{
"path": "../notebook"
}
- ]
+ ],
+ "extends": "../../tsconfigbase"
}
diff --git a/packages/celltags/src/addwidget.ts b/packages/celltags/src/addwidget.ts
index 815f16cc4b10..71f52bf2bc63 100644
--- a/packages/celltags/src/addwidget.ts
+++ b/packages/celltags/src/addwidget.ts
@@ -22,16 +22,16 @@ export class AddWidget extends Widget {
* Create input box with icon and attach to this.node.
*/
buildTag() {
- let text = document.createElement('input');
+ const text = document.createElement('input');
text.value = 'Add Tag';
text.contentEditable = 'true';
text.className = 'add-tag';
text.style.width = '49px';
this.input = text;
- let tag = document.createElement('div');
+ const tag = document.createElement('div');
tag.className = 'tag-holder';
tag.appendChild(text);
- let iconContainer = addIcon.element({
+ const iconContainer = addIcon.element({
tag: 'span',
elementPosition: 'center',
height: '18px',
@@ -105,7 +105,7 @@ export class AddWidget extends Widget {
this.input.focus();
} else if (event.target !== this.input) {
if (this.input.value !== '') {
- let value = this.input.value;
+ const value = this.input.value;
(this.parent as TagTool).addTag(value);
this.input.blur();
this._evtBlur();
@@ -129,7 +129,7 @@ export class AddWidget extends Widget {
* @param event - The DOM event sent to the widget
*/
private _evtKeyDown(event: KeyboardEvent) {
- let tmp = document.createElement('span');
+ const tmp = document.createElement('span');
tmp.className = 'add-tag';
tmp.innerHTML = this.input.value;
// set width to the pixel length of the text
@@ -138,7 +138,7 @@ export class AddWidget extends Widget {
document.body.removeChild(tmp);
// if they hit Enter, add the tag and reset state
if (event.keyCode === 13) {
- let value = this.input.value;
+ const value = this.input.value;
(this.parent as TagTool).addTag(value);
this.input.blur();
this._evtBlur();
diff --git a/packages/celltags/src/tool.ts b/packages/celltags/src/tool.ts
index a866eb3323ab..b2b95292b622 100644
--- a/packages/celltags/src/tool.ts
+++ b/packages/celltags/src/tool.ts
@@ -31,8 +31,8 @@ export class TagTool extends NotebookTools.Tool {
* Add an AddWidget input box to the layout.
*/
createTagInput() {
- let layout = this.layout as PanelLayout;
- let input = new AddWidget();
+ const layout = this.layout as PanelLayout;
+ const input = new AddWidget();
input.id = 'add-tag';
layout.insertWidget(0, input);
}
@@ -46,7 +46,9 @@ export class TagTool extends NotebookTools.Tool {
*/
checkApplied(name: string): boolean {
if (this.tracker.activeCell) {
- let tags = this.tracker.activeCell.model.metadata.get('tags') as string[];
+ const tags = this.tracker.activeCell.model.metadata.get(
+ 'tags'
+ ) as string[];
if (tags) {
for (let i = 0; i < tags.length; i++) {
if (tags[i] === name) {
@@ -64,9 +66,9 @@ export class TagTool extends NotebookTools.Tool {
* @param name - The name of the tag.
*/
addTag(name: string) {
- let cell = this.tracker.activeCell;
+ const cell = this.tracker.activeCell;
let tags = cell.model.metadata.get('tags') as string[];
- let newTags = name.split(/[,\s]+/);
+ const newTags = name.split(/[,\s]+/);
if (tags === undefined) {
tags = [];
}
@@ -86,9 +88,9 @@ export class TagTool extends NotebookTools.Tool {
* @param name - The name of the tag.
*/
removeTag(name: string) {
- let cell = this.tracker.activeCell;
- let tags = cell.model.metadata.get('tags') as string[];
- let idx = tags.indexOf(name);
+ const cell = this.tracker.activeCell;
+ const tags = cell.model.metadata.get('tags') as string[];
+ const idx = tags.indexOf(name);
if (idx > -1) {
tags.splice(idx, 1);
}
@@ -105,7 +107,7 @@ export class TagTool extends NotebookTools.Tool {
* active cell.
*/
loadActiveTags() {
- let layout = this.layout as PanelLayout;
+ const layout = this.layout as PanelLayout;
for (let i = 0; i < layout.widgets.length; i++) {
layout.widgets[i].update();
}
@@ -116,16 +118,16 @@ export class TagTool extends NotebookTools.Tool {
* stored tag list.
*/
pullTags() {
- let notebook = this.tracker.currentWidget;
+ const notebook = this.tracker.currentWidget;
if (this.tracker && this.tracker.currentWidget) {
- let cells = notebook.model.cells;
- let allTags: string[] = [];
+ const cells = notebook.model.cells;
+ const allTags: string[] = [];
for (let i = 0; i < cells.length; i++) {
- let metadata = cells.get(i).metadata;
- let tags = metadata.get('tags') as string[];
+ const metadata = cells.get(i).metadata;
+ const tags = metadata.get('tags') as string[];
if (tags) {
for (let j = 0; j < tags.length; j++) {
- let name = tags[j] as string;
+ const name = tags[j] as string;
if (name !== '') {
if (allTags.indexOf(name) < 0) {
allTags.push(name);
@@ -144,12 +146,12 @@ export class TagTool extends NotebookTools.Tool {
*/
refreshTags() {
this.pullTags();
- let layout = this.layout as PanelLayout;
- let tags: string[] = this.tagList;
- let toDispose: TagWidget[] = [];
- let nWidgets = layout.widgets.length;
+ const layout = this.layout as PanelLayout;
+ const tags: string[] = this.tagList;
+ const toDispose: TagWidget[] = [];
+ const nWidgets = layout.widgets.length;
for (let i = 0; i < nWidgets; i++) {
- let idx = tags.indexOf((layout.widgets[i] as TagWidget).name);
+ const idx = tags.indexOf((layout.widgets[i] as TagWidget).name);
if (idx < 0 && layout.widgets[i].id !== 'add-tag') {
toDispose.push(layout.widgets[i] as TagWidget);
} else if (layout.widgets[i].id !== 'add-tag') {
@@ -160,8 +162,8 @@ export class TagTool extends NotebookTools.Tool {
toDispose[i].dispose();
}
for (let i = 0; i < tags.length; i++) {
- let widget = new TagWidget(tags[i]);
- let idx = layout.widgets.length - 1;
+ const widget = new TagWidget(tags[i]);
+ const idx = layout.widgets.length - 1;
layout.insertWidget(idx, widget);
}
}
@@ -171,10 +173,10 @@ export class TagTool extends NotebookTools.Tool {
* that each string doesn't include spaces.
*/
validateTags(cell: Cell, taglist: string[]) {
- let results: string[] = [];
+ const results: string[] = [];
for (let i = 0; i < taglist.length; i++) {
if (taglist[i] !== '' && typeof taglist[i] === 'string') {
- let spl = taglist[i].split(/[,\s]+/);
+ const spl = taglist[i].split(/[,\s]+/);
for (let j = 0; j < spl.length; j++) {
if (spl[j] !== '' && results.indexOf(spl[j]) < 0) {
results.push(spl[j]);
@@ -234,7 +236,7 @@ export class TagTool extends NotebookTools.Tool {
* Handle a change to active cell metadata.
*/
protected onActiveCellMetadataChanged(): void {
- let tags = this.tracker.activeCell.model.metadata.get('tags');
+ const tags = this.tracker.activeCell.model.metadata.get('tags');
let taglist: string[] = [];
if (tags === undefined) {
return;
diff --git a/packages/celltags/src/widget.ts b/packages/celltags/src/widget.ts
index 6a951063f143..16553a2d4837 100644
--- a/packages/celltags/src/widget.ts
+++ b/packages/celltags/src/widget.ts
@@ -23,13 +23,13 @@ export class TagWidget extends Widget {
* Create tag div with icon and attach to this.node.
*/
buildTag() {
- let text = document.createElement('span');
+ const text = document.createElement('span');
text.textContent = this.name;
text.style.textOverflow = 'ellipsis';
- let tag = document.createElement('div');
+ const tag = document.createElement('div');
tag.className = 'tag-holder';
tag.appendChild(text);
- let iconContainer = checkIcon.element({
+ const iconContainer = checkIcon.element({
tag: 'span',
elementPosition: 'center',
height: '18px',
@@ -95,7 +95,7 @@ export class TagWidget extends Widget {
* Handle `update-request` messages. Check if applied to current active cell.
*/
onUpdateRequest() {
- let applied = this.parent.checkApplied(this.name);
+ const applied = this.parent.checkApplied(this.name);
if (applied !== this.applied) {
this.toggleApplied();
}
diff --git a/packages/celltags/tsconfig.json b/packages/celltags/tsconfig.json
index d2fd9e21416c..1c5d8122646e 100644
--- a/packages/celltags/tsconfig.json
+++ b/packages/celltags/tsconfig.json
@@ -34,5 +34,6 @@
{
"path": "../ui-components"
}
- ]
+ ],
+ "extends": "../../tsconfigbase"
}
diff --git a/packages/codeeditor/src/editor.ts b/packages/codeeditor/src/editor.ts
index c34d87b24e6c..e555b9402a1a 100644
--- a/packages/codeeditor/src/editor.ts
+++ b/packages/codeeditor/src/editor.ts
@@ -216,10 +216,10 @@ export namespace CodeEditor {
this.modelDB = new ModelDB();
}
- let value = this.modelDB.createString('value');
+ const value = this.modelDB.createString('value');
value.text = value.text || options.value || '';
- let mimeType = this.modelDB.createValue('mimeType');
+ const mimeType = this.modelDB.createValue('mimeType');
mimeType.set(options.mimeType || 'text/plain');
mimeType.changed.connect(this._onMimeTypeChanged, this);
@@ -655,7 +655,7 @@ export namespace CodeEditor {
/**
* The default configuration options for an editor.
*/
- export let defaultConfig: IConfig = {
+ export const defaultConfig: IConfig = {
fontFamily: null,
fontSize: null,
lineHeight: null,
diff --git a/packages/codeeditor/src/jsoneditor.ts b/packages/codeeditor/src/jsoneditor.ts
index 1c58f97c3324..eb7d57d5821e 100644
--- a/packages/codeeditor/src/jsoneditor.ts
+++ b/packages/codeeditor/src/jsoneditor.ts
@@ -69,7 +69,7 @@ export class JSONEditor extends Widget {
this.node.appendChild(this.headerNode);
this.node.appendChild(this.editorHostNode);
- let model = new CodeEditor.Model();
+ const model = new CodeEditor.Model();
model.value.text = 'No data!';
model.mimeType = 'application/json';
@@ -164,7 +164,7 @@ export class JSONEditor extends Widget {
* Handle `after-attach` messages for the widget.
*/
protected onAfterAttach(msg: Message): void {
- let node = this.editorHostNode;
+ const node = this.editorHostNode;
node.addEventListener('blur', this, true);
node.addEventListener('click', this, true);
this.revertButtonNode.hidden = true;
@@ -193,7 +193,7 @@ export class JSONEditor extends Widget {
* Handle `before-detach` messages for the widget.
*/
protected onBeforeDetach(msg: Message): void {
- let node = this.editorHostNode;
+ const node = this.editorHostNode;
node.removeEventListener('blur', this, true);
node.removeEventListener('click', this, true);
this.headerNode.removeEventListener('click', this);
@@ -222,7 +222,7 @@ export class JSONEditor extends Widget {
private _onValueChanged(): void {
let valid = true;
try {
- let value = JSON.parse(this.editor.model.value.text);
+ const value = JSON.parse(this.editor.model.value.text);
this.removeClass(ERROR_CLASS);
this._inputDirty =
!this._changeGuard && !JSONExt.deepEqual(value, this._originalValue);
@@ -249,7 +249,7 @@ export class JSONEditor extends Widget {
* Handle click events for the buttons.
*/
private _evtClick(event: MouseEvent): void {
- let target = event.target as HTMLElement;
+ const target = event.target as HTMLElement;
if (this.revertButtonNode.contains(target)) {
this._setValue();
} else if (this.commitButtonNode.contains(target)) {
@@ -268,23 +268,23 @@ export class JSONEditor extends Widget {
* Merge the user content.
*/
private _mergeContent(): void {
- let model = this.editor.model;
- let old = this._originalValue;
- let user = JSON.parse(model.value.text) as JSONObject;
- let source = this.source;
+ const model = this.editor.model;
+ const old = this._originalValue;
+ const user = JSON.parse(model.value.text) as JSONObject;
+ const source = this.source;
if (!source) {
return;
}
// If it is in user and has changed from old, set in new.
- for (let key in user) {
+ for (const key in user) {
if (!JSONExt.deepEqual(user[key], old[key] || null)) {
source.set(key, user[key]);
}
}
// If it was in old and is not in user, remove from source.
- for (let key in old) {
+ for (const key in old) {
if (!(key in user)) {
source.delete(key);
}
@@ -300,14 +300,14 @@ export class JSONEditor extends Widget {
this.revertButtonNode.hidden = true;
this.commitButtonNode.hidden = true;
this.removeClass(ERROR_CLASS);
- let model = this.editor.model;
- let content = this._source ? this._source.toJSON() : {};
+ const model = this.editor.model;
+ const content = this._source ? this._source.toJSON() : {};
this._changeGuard = true;
if (content === void 0) {
model.value.text = 'No data!';
this._originalValue = JSONExt.emptyObject;
} else {
- let value = JSON.stringify(content, null, 4);
+ const value = JSON.stringify(content, null, 4);
model.value.text = value;
this._originalValue = content;
// Move the cursor to within the brace.
diff --git a/packages/codeeditor/src/widget.ts b/packages/codeeditor/src/widget.ts
index 65236ef474e3..67066fb96ba5 100644
--- a/packages/codeeditor/src/widget.ts
+++ b/packages/codeeditor/src/widget.ts
@@ -116,7 +116,7 @@ export class CodeEditorWrapper extends Widget {
*/
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
- let node = this.node;
+ const node = this.node;
node.addEventListener('lm-dragenter', this);
node.addEventListener('lm-dragleave', this);
node.addEventListener('lm-dragover', this);
@@ -133,7 +133,7 @@ export class CodeEditorWrapper extends Widget {
* Handle `before-detach` messages for the widget.
*/
protected onBeforeDetach(msg: Message): void {
- let node = this.node;
+ const node = this.node;
node.removeEventListener('lm-dragenter', this);
node.removeEventListener('lm-dragleave', this);
node.removeEventListener('lm-dragover', this);
diff --git a/packages/codemirror-extension/src/index.ts b/packages/codemirror-extension/src/index.ts
index 6c0a15ff9fd3..4b1baa070138 100644
--- a/packages/codemirror-extension/src/index.ts
+++ b/packages/codemirror-extension/src/index.ts
@@ -83,7 +83,7 @@ export const editorSyntaxStatus: JupyterFrontEndPlugin = {
// Automatically disable if statusbar missing
return;
}
- let item = new EditorSyntaxStatus({ commands: app.commands });
+ const item = new EditorSyntaxStatus({ commands: app.commands });
labShell.currentChanged.connect(() => {
const current = labShell.currentWidget;
if (current && tracker.has(current) && item.model) {
@@ -190,7 +190,7 @@ function activateEditorCommands(
function updateTracker(): void {
tracker.forEach(widget => {
if (widget.content.editor instanceof CodeMirrorEditor) {
- let cm = widget.content.editor.editor;
+ const cm = widget.content.editor.editor;
cm.setOption('keyMap', keyMap);
cm.setOption('theme', theme);
cm.setOption('scrollPastEnd', scrollPastEnd);
@@ -222,7 +222,7 @@ function activateEditorCommands(
*/
tracker.widgetAdded.connect((sender, widget) => {
if (widget.content.editor instanceof CodeMirrorEditor) {
- let cm = widget.content.editor.editor;
+ const cm = widget.content.editor.editor;
cm.setOption('keyMap', keyMap);
cm.setOption('theme', theme);
cm.setOption('scrollPastEnd', scrollPastEnd);
@@ -275,7 +275,7 @@ function activateEditorCommands(
commands.addCommand(CommandIDs.changeKeyMap, {
label: args => {
- let title = args['keyMap'] as string;
+ const title = args['keyMap'] as string;
return title === 'sublime' ? 'Sublime Text' : title;
},
execute: args => {
@@ -292,11 +292,11 @@ function activateEditorCommands(
commands.addCommand(CommandIDs.find, {
label: 'Find...',
execute: () => {
- let widget = tracker.currentWidget;
+ const widget = tracker.currentWidget;
if (!widget) {
return;
}
- let editor = widget.content.editor as CodeMirrorEditor;
+ const editor = widget.content.editor as CodeMirrorEditor;
editor.execCommand('find');
},
isEnabled
@@ -305,11 +305,11 @@ function activateEditorCommands(
commands.addCommand(CommandIDs.goToLine, {
label: 'Go to Line...',
execute: () => {
- let widget = tracker.currentWidget;
+ const widget = tracker.currentWidget;
if (!widget) {
return;
}
- let editor = widget.content.editor as CodeMirrorEditor;
+ const editor = widget.content.editor as CodeMirrorEditor;
editor.execCommand('jumpToLine');
},
isEnabled
@@ -318,10 +318,10 @@ function activateEditorCommands(
commands.addCommand(CommandIDs.changeMode, {
label: args => args['name'] as string,
execute: args => {
- let name = args['name'] as string;
- let widget = tracker.currentWidget;
+ const name = args['name'] as string;
+ const widget = tracker.currentWidget;
if (name && widget) {
- let spec = Mode.findByName(name);
+ const spec = Mode.findByName(name);
if (spec) {
widget.content.model.mimeType = spec.mime;
}
@@ -329,21 +329,21 @@ function activateEditorCommands(
},
isEnabled,
isToggled: args => {
- let widget = tracker.currentWidget;
+ const widget = tracker.currentWidget;
if (!widget) {
return false;
}
- let mime = widget.content.model.mimeType;
- let spec = Mode.findByMIME(mime);
- let name = spec && spec.name;
+ const mime = widget.content.model.mimeType;
+ const spec = Mode.findByMIME(mime);
+ const name = spec && spec.name;
return args['name'] === name;
}
});
Mode.getModeInfo()
.sort((a, b) => {
- let aName = a.name || '';
- let bName = b.name || '';
+ const aName = a.name || '';
+ const bName = b.name || '';
return aName.localeCompare(bName);
})
.forEach(spec => {
@@ -404,7 +404,7 @@ function activateEditorCommands(
mainMenu.editMenu.goToLiners.add({
tracker,
goToLine: (widget: IDocumentWidget) => {
- let editor = widget.content.editor as CodeMirrorEditor;
+ const editor = widget.content.editor as CodeMirrorEditor;
editor.execCommand('jumpToLine');
}
} as IEditMenu.IGoToLiner>);
diff --git a/packages/codemirror/src/codemirror-ipython.ts b/packages/codemirror/src/codemirror-ipython.ts
index fae367118d74..4f0943de0674 100644
--- a/packages/codemirror/src/codemirror-ipython.ts
+++ b/packages/codemirror/src/codemirror-ipython.ts
@@ -14,8 +14,8 @@ import 'codemirror/mode/python/python';
CodeMirror.defineMode(
'ipython',
(config: CodeMirror.EditorConfiguration, modeOptions?: any) => {
- let pythonConf: any = {};
- for (let prop in modeOptions) {
+ const pythonConf: any = {};
+ for (const prop in modeOptions) {
if (modeOptions.hasOwnProperty(prop)) {
pythonConf[prop] = modeOptions[prop];
}
diff --git a/packages/codemirror/src/codemirror-ipythongfm.ts b/packages/codemirror/src/codemirror-ipythongfm.ts
index 3efcc9a5c6b6..20c9f3a49cdf 100644
--- a/packages/codemirror/src/codemirror-ipythongfm.ts
+++ b/packages/codemirror/src/codemirror-ipythongfm.ts
@@ -19,12 +19,12 @@ import 'codemirror/addon/mode/multiplex';
CodeMirror.defineMode(
'ipythongfm',
(config: CodeMirror.EditorConfiguration, modeOptions?: any) => {
- let gfmMode = CodeMirror.getMode(config, {
+ const gfmMode = CodeMirror.getMode(config, {
name: 'gfm',
// Override list3 with an under-used token, rather than `keyword`
tokenTypeOverrides: { list3: 'string-2' }
});
- let texMode = CodeMirror.getMode(config, {
+ const texMode = CodeMirror.getMode(config, {
name: 'stex',
inMathMode: true
});
diff --git a/packages/codemirror/src/editor.ts b/packages/codemirror/src/editor.ts
index 95fe6e9ce5d2..c51cd01cb85d 100644
--- a/packages/codemirror/src/editor.ts
+++ b/packages/codemirror/src/editor.ts
@@ -1,7 +1,7 @@
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
-///
-///
+// /
+// /
import CodeMirror from 'codemirror';
@@ -92,7 +92,7 @@ export class CodeMirrorEditor implements CodeEditor.IEditor {
* Construct a CodeMirror editor.
*/
constructor(options: CodeMirrorEditor.IOptions) {
- let host = (this.host = options.host);
+ const host = (this.host = options.host);
host.classList.add(EDITOR_CLASS);
host.classList.add('jp-Editor');
host.addEventListener('focus', this, true);
@@ -102,21 +102,21 @@ export class CodeMirrorEditor implements CodeEditor.IEditor {
this._uuid = options.uuid || UUID.uuid4();
// Handle selection style.
- let style = options.selectionStyle || {};
+ const style = options.selectionStyle || {};
this._selectionStyle = {
...CodeEditor.defaultSelectionStyle,
...(style as CodeEditor.ISelectionStyle)
};
- let model = (this._model = options.model);
- let config = options.config || {};
- let fullConfig = (this._config = {
+ const model = (this._model = options.model);
+ const config = options.config || {};
+ const fullConfig = (this._config = {
...CodeMirrorEditor.defaultConfig,
...config
});
- let editor = (this._editor = Private.createEditor(host, fullConfig));
+ const editor = (this._editor = Private.createEditor(host, fullConfig));
- let doc = editor.getDoc();
+ const doc = editor.getDoc();
// Handle initial values for text, mimetype, and selections.
doc.setValue(model.value.text);
@@ -140,7 +140,7 @@ export class CodeMirrorEditor implements CodeEditor.IEditor {
model.selections.changed.connect(this._onSelectionsChanged, this);
CodeMirror.on(editor, 'keydown', (editor: CodeMirror.Editor, event) => {
- let index = ArrayExt.findFirstIndex(this._keydownHandlers, handler => {
+ const index = ArrayExt.findFirstIndex(this._keydownHandlers, handler => {
if (handler(this, event) === true) {
event.preventDefault();
return true;
@@ -629,8 +629,8 @@ export class CodeMirrorEditor implements CodeEditor.IEditor {
* Handle keydown events from the editor.
*/
protected onKeydown(event: KeyboardEvent): boolean {
- let position = this.getCursorPosition();
- let { line, column } = position;
+ const position = this.getCursorPosition();
+ const { line, column } = position;
if (line === 0 && column === 0 && event.keyCode === UP_ARROW) {
if (!event.shiftKey) {
@@ -646,8 +646,8 @@ export class CodeMirrorEditor implements CodeEditor.IEditor {
return false;
}
- let lastLine = this.lineCount - 1;
- let lastCh = this.getLine(lastLine)!.length;
+ const lastLine = this.lineCount - 1;
+ const lastCh = this.getLine(lastLine)!.length;
if (
line === lastLine &&
column === lastCh &&
@@ -681,13 +681,13 @@ export class CodeMirrorEditor implements CodeEditor.IEditor {
*/
private _onMimeTypeChanged(): void {
const mime = this._model.mimeType;
- let editor = this._editor;
+ const editor = this._editor;
// TODO: should we provide a hook for when the
// mode is done being set?
void Mode.ensure(mime).then(spec => {
editor.setOption('mode', spec?.mime ?? 'null');
});
- let extraKeys = editor.getOption('extraKeys') || {};
+ const extraKeys = editor.getOption('extraKeys') || {};
const isCode = mime !== 'text/plain' && mime !== 'text/x-ipythongfm';
if (isCode) {
extraKeys['Backspace'] = 'delSpaceToPrevTabStop';
@@ -755,14 +755,14 @@ export class CodeMirrorEditor implements CodeEditor.IEditor {
// Selections only appear to render correctly if the anchor
// is before the head in the document. That is, reverse selections
// do not appear as intended.
- let forward: boolean =
+ const forward: boolean =
selection.start.line < selection.end.line ||
(selection.start.line === selection.end.line &&
selection.start.column <= selection.end.column);
- let anchor = this._toCodeMirrorPosition(
+ const anchor = this._toCodeMirrorPosition(
forward ? selection.start : selection.end
);
- let head = this._toCodeMirrorPosition(
+ const head = this._toCodeMirrorPosition(
forward ? selection.end : selection.start
);
let markerOptions: CodeMirror.TextMarkerOptions;
@@ -776,7 +776,7 @@ export class CodeMirrorEditor implements CodeEditor.IEditor {
}
markers.push(this.doc.markText(anchor, head, markerOptions));
} else if (collaborator) {
- let caret = this._getCaret(collaborator);
+ const caret = this._getCaret(collaborator);
markers.push(
this.doc.setBookmark(this._toCodeMirrorPosition(selection.end), {
widget: caret
@@ -819,10 +819,10 @@ export class CodeMirrorEditor implements CodeEditor.IEditor {
private _toTextMarkerOptions(
style: CodeEditor.ISelectionStyle
): CodeMirror.TextMarkerOptions {
- let r = parseInt(style.color.slice(1, 3), 16);
- let g = parseInt(style.color.slice(3, 5), 16);
- let b = parseInt(style.color.slice(5, 7), 16);
- let css = `background-color: rgba( ${r}, ${g}, ${b}, 0.15)`;
+ const r = parseInt(style.color.slice(1, 3), 16);
+ const g = parseInt(style.color.slice(3, 5), 16);
+ const b = parseInt(style.color.slice(5, 7), 16);
+ const css = `background-color: rgba( ${r}, ${g}, ${b}, 0.15)`;
return {
className: style.className,
title: style.displayName,
@@ -873,18 +873,18 @@ export class CodeMirrorEditor implements CodeEditor.IEditor {
return;
}
this._changeGuard = true;
- let doc = this.doc;
+ const doc = this.doc;
switch (args.type) {
case 'insert':
- let pos = doc.posFromIndex(args.start);
+ const pos = doc.posFromIndex(args.start);
// Replace the range, including a '+input' orign,
// which indicates that CodeMirror may merge changes
// for undo/redo purposes.
doc.replaceRange(args.value, pos, pos, '+input');
break;
case 'remove':
- let from = doc.posFromIndex(args.start);
- let to = doc.posFromIndex(args.end);
+ const from = doc.posFromIndex(args.start);
+ const to = doc.posFromIndex(args.end);
// Replace the range, including a '+input' orign,
// which indicates that CodeMirror may merge changes
// for undo/redo purposes.
@@ -910,10 +910,10 @@ export class CodeMirrorEditor implements CodeEditor.IEditor {
return;
}
this._changeGuard = true;
- let value = this._model.value;
- let start = doc.indexFromPos(change.from);
- let end = doc.indexFromPos(change.to);
- let inserted = change.text.join('\n');
+ const value = this._model.value;
+ const start = doc.indexFromPos(change.from);
+ const end = doc.indexFromPos(change.to);
+ const inserted = change.text.join('\n');
if (end !== start) {
value.remove(start, end);
@@ -998,17 +998,19 @@ export class CodeMirrorEditor implements CodeEditor.IEditor {
* of a collaborator's cursor.
*/
private _getCaret(collaborator: ICollaborator): HTMLElement {
- let name = collaborator ? collaborator.displayName : 'Anonymous';
- let color = collaborator ? collaborator.color : this._selectionStyle.color;
- let caret: HTMLElement = document.createElement('span');
+ const name = collaborator ? collaborator.displayName : 'Anonymous';
+ const color = collaborator
+ ? collaborator.color
+ : this._selectionStyle.color;
+ const caret: HTMLElement = document.createElement('span');
caret.className = COLLABORATOR_CURSOR_CLASS;
caret.style.borderBottomColor = color;
caret.onmouseenter = () => {
this._clearHover();
this._hoverId = collaborator.sessionId;
- let rect = caret.getBoundingClientRect();
+ const rect = caret.getBoundingClientRect();
// Construct and place the hover box.
- let hover = document.createElement('div');
+ const hover = document.createElement('div');
hover.className = COLLABORATOR_HOVER_CLASS;
hover.style.left = String(rect.left) + 'px';
hover.style.top = String(rect.bottom) + 'px';
@@ -1039,13 +1041,13 @@ export class CodeMirrorEditor implements CodeEditor.IEditor {
* Check for an out of sync editor.
*/
private _checkSync(): void {
- let change = this._lastChange;
+ const change = this._lastChange;
if (!change) {
return;
}
this._lastChange = null;
- let editor = this._editor;
- let doc = editor.getDoc();
+ const editor = this._editor;
+ const doc = editor.getDoc();
if (doc.getValue() === this._model.value.text) {
return;
}
@@ -1055,10 +1057,10 @@ export class CodeMirrorEditor implements CodeEditor.IEditor {
body:
'Please open your browser JavaScript console for bug report instructions'
});
- console.log(
+ console.warn(
'Please paste the following to https://github.com/jupyterlab/jupyterlab/issues/2951'
);
- console.log(
+ console.warn(
JSON.stringify({
model: this._model.value.text,
view: doc.getValue(),
@@ -1245,7 +1247,7 @@ export namespace CodeMirrorEditor {
/**
* The default configuration options for an editor.
*/
- export let defaultConfig: Required = {
+ export const defaultConfig: Required = {
...CodeEditor.defaultConfig,
mode: 'null',
theme: 'jupyter',
@@ -1291,7 +1293,7 @@ namespace Private {
host: HTMLElement,
config: CodeMirrorEditor.IConfig
): CodeMirror.Editor {
- let {
+ const {
autoClosingBrackets,
fontFamily,
fontSize,
@@ -1303,7 +1305,7 @@ namespace Private {
readOnly,
...otherOptions
} = config;
- let bareConfig = {
+ const bareConfig = {
autoCloseBrackets: autoClosingBrackets ? {} : false,
indentUnit: tabSize,
indentWithTabs: !insertSpaces,
@@ -1340,17 +1342,17 @@ namespace Private {
* Indent or insert a tab as appropriate.
*/
export function indentMoreOrinsertTab(cm: CodeMirror.Editor): void {
- let doc = cm.getDoc();
- let from = doc.getCursor('from');
- let to = doc.getCursor('to');
- let sel = !posEq(from, to);
+ const doc = cm.getDoc();
+ const from = doc.getCursor('from');
+ const to = doc.getCursor('to');
+ const sel = !posEq(from, to);
if (sel) {
CodeMirror.commands['indentMore'](cm);
return;
}
// Check for start of line.
- let line = doc.getLine(from.line);
- let before = line.slice(0, from.ch);
+ const line = doc.getLine(from.line);
+ const before = line.slice(0, from.ch);
if (/^\s*$/.test(before)) {
CodeMirror.commands['indentMore'](cm);
} else {
@@ -1366,35 +1368,35 @@ namespace Private {
* Delete spaces to the previous tab stob in a codemirror editor.
*/
export function delSpaceToPrevTabStop(cm: CodeMirror.Editor): void {
- let doc = cm.getDoc();
- let tabSize = cm.getOption('indentUnit');
- let ranges = doc.listSelections(); // handle multicursor
+ const doc = cm.getDoc();
+ const tabSize = cm.getOption('indentUnit');
+ const ranges = doc.listSelections(); // handle multicursor
for (let i = ranges.length - 1; i >= 0; i--) {
// iterate reverse so any deletions don't overlap
- let head = ranges[i].head;
- let anchor = ranges[i].anchor;
- let isSelection = !posEq(head, anchor);
+ const head = ranges[i].head;
+ const anchor = ranges[i].anchor;
+ const isSelection = !posEq(head, anchor);
if (isSelection) {
doc.replaceRange('', anchor, head);
} else {
- let line = doc.getLine(head.line).substring(0, head.ch);
+ const line = doc.getLine(head.line).substring(0, head.ch);
if (line.match(/^\ +$/) !== null) {
// delete tabs
- let prevTabStop = (Math.ceil(head.ch / tabSize) - 1) * tabSize;
- let from = CodeMirror.Pos(head.line, prevTabStop);
+ const prevTabStop = (Math.ceil(head.ch / tabSize) - 1) * tabSize;
+ const from = CodeMirror.Pos(head.line, prevTabStop);
doc.replaceRange('', from, head);
} else {
// delete non-tabs
if (head.ch === 0) {
if (head.line !== 0) {
- let from = CodeMirror.Pos(
+ const from = CodeMirror.Pos(
head.line - 1,
doc.getLine(head.line - 1).length
);
doc.replaceRange('', from, head);
}
} else {
- let from = CodeMirror.Pos(head.line, head.ch - 1);
+ const from = CodeMirror.Pos(head.line, head.ch - 1);
doc.replaceRange('', from, head);
}
}
@@ -1419,7 +1421,7 @@ namespace Private {
*/
function getActiveGutters(config: CodeMirrorEditor.IConfig): string[] {
// The order of the classes will be the gutters order
- let classToSwitch: { [val: string]: keyof CodeMirrorEditor.IConfig } = {
+ const classToSwitch: { [val: string]: keyof CodeMirrorEditor.IConfig } = {
'CodeMirror-linenumbers': 'lineNumbers',
'CodeMirror-foldgutter': 'codeFolding'
};
@@ -1437,7 +1439,7 @@ namespace Private {
value: CodeMirrorEditor.IConfig[K],
config: CodeMirrorEditor.IConfig
): void {
- let el = editor.getWrapperElement();
+ const el = editor.getWrapperElement();
switch (option) {
case 'lineWrap':
const lineWrapping = value === 'off' ? false : true;
@@ -1468,7 +1470,7 @@ namespace Private {
editor.setOption('autoCloseBrackets', value);
break;
case 'rulers':
- let rulers = value as Array;
+ const rulers = value as Array;
editor.setOption(
'rulers',
rulers.map(column => {
diff --git a/packages/codemirror/src/mimetype.ts b/packages/codemirror/src/mimetype.ts
index 7e8656081a3f..f871c79110bf 100644
--- a/packages/codemirror/src/mimetype.ts
+++ b/packages/codemirror/src/mimetype.ts
@@ -20,7 +20,7 @@ export class CodeMirrorMimeTypeService implements IEditorMimeTypeService {
* If a mime type cannot be found returns the defaul mime type `text/plain`, never `null`.
*/
getMimeTypeByLanguage(info: nbformat.ILanguageInfoMetadata): string {
- let ext = info.file_extension || '';
+ const ext = info.file_extension || '';
return Mode.findBest(
(info.codemirror_mode as any) || {
mimetype: info.mimetype,
@@ -43,7 +43,7 @@ export class CodeMirrorMimeTypeService implements IEditorMimeTypeService {
} else if (ext === '.md') {
return 'text/x-ipythongfm';
}
- let mode = Mode.findByFileName(path) || Mode.findBest('');
+ const mode = Mode.findByFileName(path) || Mode.findBest('');
return mode.mime;
}
}
diff --git a/packages/codemirror/src/mode.ts b/packages/codemirror/src/mode.ts
index 85f4f2b70ced..5b95c362e693 100644
--- a/packages/codemirror/src/mode.ts
+++ b/packages/codemirror/src/mode.ts
@@ -27,7 +27,7 @@ import 'codemirror/mode/sql/sql';
import { PathExt } from '@jupyterlab/coreutils';
// Stub for the require function.
-declare var require: any;
+declare let require: any;
/**
* The namespace for CodeMirror Mode functionality.
@@ -61,7 +61,7 @@ export namespace Mode {
(spec: ISpec): Promise;
}
- let specLoaders: Private.IRankItem[] = [
+ const specLoaders: Private.IRankItem[] = [
{
// Simplest, cheapest check by mode name.
loader: async spec => CodeMirror.modes.hasOwnProperty(spec.mode),
@@ -109,9 +109,9 @@ export namespace Mode {
* @returns A promise that resolves when the mode is available.
*/
export async function ensure(mode: string | ISpec): Promise {
- let spec = findBest(mode);
+ const spec = findBest(mode);
- for (let specLoader of specLoaders) {
+ for (const specLoader of specLoaders) {
if (await specLoader.loader(spec)) {
return spec;
}
@@ -121,8 +121,8 @@ export namespace Mode {
}
export function addSpecLoader(loader: ISpecLoader, rank: number) {
- let item = { loader, rank };
- let index = ArrayExt.upperBound(specLoaders, item, Private.itemCmp);
+ const item = { loader, rank };
+ const index = ArrayExt.upperBound(specLoaders, item, Private.itemCmp);
ArrayExt.insert(specLoaders, index, item);
}
@@ -130,9 +130,9 @@ export namespace Mode {
* Find a codemirror mode by name or CodeMirror spec.
*/
export function findBest(mode: string | ISpec): ISpec {
- let modename = typeof mode === 'string' ? mode : mode.mode || mode.name;
- let mimetype = typeof mode !== 'string' ? mode.mime : modename;
- let ext = typeof mode !== 'string' ? mode.ext ?? [] : [];
+ const modename = typeof mode === 'string' ? mode : mode.mode || mode.name;
+ const mimetype = typeof mode !== 'string' ? mode.mime : modename;
+ const ext = typeof mode !== 'string' ? mode.ext ?? [] : [];
return (
CodeMirror.findModeByName(modename || '') ||
@@ -161,7 +161,7 @@ export namespace Mode {
* Find a codemirror mode by filename.
*/
export function findByFileName(name: string): ISpec {
- let basename = PathExt.basename(name);
+ const basename = PathExt.basename(name);
return CodeMirror.findModeByFileName(basename);
}
@@ -173,7 +173,7 @@ export namespace Mode {
return CodeMirror.findModeByExtension(name);
}
for (let i = 0; i < ext.length; i++) {
- let mode = CodeMirror.findModeByExtension(ext[i]);
+ const mode = CodeMirror.findModeByExtension(ext[i]);
if (mode) {
return mode;
}
diff --git a/packages/codemirror/src/syntaxstatus.tsx b/packages/codemirror/src/syntaxstatus.tsx
index 196c3183e2ee..294b3d2398d6 100644
--- a/packages/codemirror/src/syntaxstatus.tsx
+++ b/packages/codemirror/src/syntaxstatus.tsx
@@ -90,14 +90,14 @@ export class EditorSyntaxStatus extends VDomRenderer {
*/
private _handleClick = () => {
const modeMenu = new Menu({ commands: this._commands });
- let command = 'codemirror:change-mode';
+ const command = 'codemirror:change-mode';
if (this._popup) {
this._popup.dispose();
}
Mode.getModeInfo()
.sort((a, b) => {
- let aName = a.name || '';
- let bName = b.name || '';
+ const aName = a.name || '';
+ const bName = b.name || '';
return aName.localeCompare(bName);
})
.forEach(spec => {
@@ -105,7 +105,7 @@ export class EditorSyntaxStatus extends VDomRenderer {
return;
}
- let args: JSONObject = {
+ const args: JSONObject = {
insertSpaces: true,
name: spec.name!
};
diff --git a/packages/completer-extension/src/index.ts b/packages/completer-extension/src/index.ts
index 38ee21dd1ed4..e9d230d29704 100644
--- a/packages/completer-extension/src/index.ts
+++ b/packages/completer-extension/src/index.ts
@@ -60,7 +60,7 @@ const manager: JupyterFrontEndPlugin = {
app.commands.addCommand(CommandIDs.invoke, {
execute: args => {
- let id = args && (args['id'] as string);
+ const id = args && (args['id'] as string);
if (!id) {
return;
}
@@ -74,7 +74,7 @@ const manager: JupyterFrontEndPlugin = {
app.commands.addCommand(CommandIDs.select, {
execute: args => {
- let id = args && (args['id'] as string);
+ const id = args && (args['id'] as string);
if (!id) {
return;
}
@@ -143,7 +143,7 @@ const consoles: JupyterFrontEndPlugin = {
const connector = new CompletionConnector({ session, editor });
const handler = manager.register({ connector, editor, parent: widget });
- let updateConnector = () => {
+ const updateConnector = () => {
const editor = anchor.promptCell?.editor ?? null;
const session = anchor.sessionContext.session;
@@ -208,7 +208,7 @@ const notebooks: JupyterFrontEndPlugin = {
const connector = new CompletionConnector({ session, editor });
const handler = manager.register({ connector, editor, parent: panel });
- let updateConnector = () => {
+ const updateConnector = () => {
const editor = panel.content.activeCell?.editor ?? null;
const session = panel.sessionContext.session;
diff --git a/packages/completer/src/handler.ts b/packages/completer/src/handler.ts
index 979bef5b6ac1..69b8c742283b 100644
--- a/packages/completer/src/handler.ts
+++ b/packages/completer/src/handler.ts
@@ -200,10 +200,10 @@ export class CompletionHandler implements IDisposable {
return;
}
- let editor = this._editor;
+ const editor = this._editor;
if (editor) {
this._makeRequest(editor.getCursorPosition()).catch(reason => {
- console.log('Invoke request bailed', reason);
+ console.warn('Invoke request bailed', reason);
});
}
}
diff --git a/packages/completer/src/model.ts b/packages/completer/src/model.ts
index 26bc83422c30..c9df3b436394 100644
--- a/packages/completer/src/model.ts
+++ b/packages/completer/src/model.ts
@@ -35,7 +35,7 @@ export class CompleterModel implements Completer.IModel {
return this._original;
}
set original(newValue: Completer.ITextState | null) {
- let unchanged =
+ const unchanged =
this._original === newValue ||
(this._original &&
newValue &&
@@ -359,16 +359,16 @@ export class CompleterModel implements Completer.IModel {
* Apply the query to the complete options list to return the matching subset.
*/
private _filter(): IIterator {
- let options = this._options || [];
- let query = this._query;
+ const options = this._options || [];
+ const query = this._query;
if (!query) {
return map(options, option => ({ raw: option, text: option }));
}
- let results: Private.IMatch[] = [];
- for (let option of options) {
- let match = StringExt.matchSumOfSquares(option, query);
+ const results: Private.IMatch[] = [];
+ for (const option of options) {
+ const match = StringExt.matchSumOfSquares(option, query);
if (match) {
- let marked = StringExt.highlight(option, match.indices, Private.mark);
+ const marked = StringExt.highlight(option, match.indices, Private.mark);
results.push({
raw: option,
score: match.score,
@@ -462,7 +462,7 @@ namespace Private {
* by locale order of the item text.
*/
export function scoreCmp(a: IMatch, b: IMatch): number {
- let delta = a.score - b.score;
+ const delta = a.score - b.score;
if (delta !== 0) {
return delta;
}
diff --git a/packages/completer/src/widget.ts b/packages/completer/src/widget.ts
index 9adffe125cad..e240650e89d2 100644
--- a/packages/completer/src/widget.ts
+++ b/packages/completer/src/widget.ts
@@ -169,7 +169,7 @@ export class Completer extends Widget {
* Emit the selected signal for the current active item and reset.
*/
selectActive(): void {
- let active = this.node.querySelector(`.${ACTIVE_CLASS}`) as HTMLElement;
+ const active = this.node.querySelector(`.${ACTIVE_CLASS}`) as HTMLElement;
if (!active) {
this.reset();
return;
@@ -225,7 +225,7 @@ export class Completer extends Widget {
return;
}
- let items = toArray(model.items());
+ const items = toArray(model.items());
// If there are no items, reset and bail.
if (!items || !items.length) {
@@ -250,16 +250,16 @@ export class Completer extends Widget {
}
// Clear the node.
- let node = this.node;
+ const node = this.node;
node.textContent = '';
// Compute an ordered list of all the types in the typeMap, this is computed
// once by the model each time new data arrives for efficiency.
- let orderedTypes = model.orderedTypes();
+ const orderedTypes = model.orderedTypes();
// Populate the completer items.
- for (let item of items) {
- let li = this._renderer.createItemNode(
+ for (const item of items) {
+ const li = this._renderer.createItemNode(
item!,
model.typeMap(),
orderedTypes
@@ -267,7 +267,7 @@ export class Completer extends Widget {
node.appendChild(li);
}
- let active = node.querySelectorAll(`.${ITEM_CLASS}`)[this._activeIndex];
+ const active = node.querySelectorAll(`.${ITEM_CLASS}`)[this._activeIndex];
active.classList.add(ACTIVE_CLASS);
// If this is the first time the current completer session has loaded,
@@ -298,8 +298,8 @@ export class Completer extends Widget {
* the first item, subsequent `up` cycles will remain on the first cycle.
*/
private _cycle(direction: Private.scrollType): void {
- let items = this.node.querySelectorAll(`.${ITEM_CLASS}`);
- let index = this._activeIndex;
+ const items = this.node.querySelectorAll(`.${ITEM_CLASS}`);
+ const index = this._activeIndex;
let active = this.node.querySelector(`.${ACTIVE_CLASS}`) as HTMLElement;
active.classList.remove(ACTIVE_CLASS);
@@ -347,11 +347,11 @@ export class Completer extends Widget {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
- let model = this._model;
+ const model = this._model;
if (!model) {
return;
}
- let populated = this._populateSubset();
+ const populated = this._populateSubset();
// If there is a common subset in the options,
// then emit a completion signal with that subset.
if (model.query) {
@@ -733,12 +733,12 @@ export namespace Completer {
typeMap: TypeMap,
orderedTypes: string[]
): HTMLLIElement {
- let li = document.createElement('li');
+ const li = document.createElement('li');
li.className = ITEM_CLASS;
// Set the raw, un-marked up value as a data attribute.
li.setAttribute('data-value', item.raw);
- let matchNode = document.createElement('code');
+ const matchNode = document.createElement('code');
matchNode.className = 'jp-Completer-match';
// Use innerHTML because search results include tags.
matchNode.innerHTML = defaultSanitizer.sanitize(item.text, {
@@ -747,14 +747,14 @@ export namespace Completer {
// If there are types provided add those.
if (!JSONExt.deepEqual(typeMap, {})) {
- let typeNode = document.createElement('span');
- let type = typeMap[item.raw] || '';
+ const typeNode = document.createElement('span');
+ const type = typeMap[item.raw] || '';
typeNode.textContent = (type[0] || '').toLowerCase();
- let colorIndex = (orderedTypes.indexOf(type) % N_COLORS) + 1;
+ const colorIndex = (orderedTypes.indexOf(type) % N_COLORS) + 1;
typeNode.className = 'jp-Completer-type';
typeNode.setAttribute(`data-color-index`, colorIndex.toString());
li.title = type;
- let typeExtendedNode = document.createElement('code');
+ const typeExtendedNode = document.createElement('code');
typeExtendedNode.className = 'jp-Completer-typeExtended';
typeExtendedNode.textContent = type.toLocaleLowerCase();
li.appendChild(typeNode);
@@ -796,14 +796,14 @@ namespace Private {
* Returns the common subset string that a list of strings shares.
*/
export function commonSubset(values: string[]): string {
- let len = values.length;
+ const len = values.length;
let subset = '';
if (len < 2) {
return subset;
}
- let strlen = values[0].length;
+ const strlen = values[0].length;
for (let i = 0; i < strlen; i++) {
- let ch = values[0][i];
+ const ch = values[0][i];
for (let j = 1; j < len; j++) {
if (values[j][i] !== ch) {
return subset;
@@ -818,7 +818,7 @@ namespace Private {
* Returns the list of raw item values currently in the DOM.
*/
export function itemValues(items: NodeList): string[] {
- let values: string[] = [];
+ const values: string[] = [];
for (let i = 0, len = items.length; i < len; i++) {
const attr = (items[i] as HTMLElement).getAttribute('data-value');
if (attr) {
diff --git a/packages/console-extension/src/foreign.ts b/packages/console-extension/src/foreign.ts
index 1be32fe75bc0..a00be85b6d37 100644
--- a/packages/console-extension/src/foreign.ts
+++ b/packages/console-extension/src/foreign.ts
@@ -57,8 +57,8 @@ function activateForeign(
// Get the current widget and activate unless the args specify otherwise.
function getCurrent(args: ReadonlyPartialJSONObject): ConsolePanel | null {
- let widget = tracker.currentWidget;
- let activate = args['activate'] !== false;
+ const widget = tracker.currentWidget;
+ const activate = args['activate'] !== false;
if (activate && widget) {
shell.activateById(widget.id);
}
@@ -68,7 +68,7 @@ function activateForeign(
commands.addCommand(toggleShowAllActivity, {
label: args => 'Show All Kernel Activity',
execute: args => {
- let current = getCurrent(args);
+ const current = getCurrent(args);
if (!current) {
return;
}
diff --git a/packages/console-extension/src/index.ts b/packages/console-extension/src/index.ts
index 0da198923d68..18e66ddc8984 100644
--- a/packages/console-extension/src/index.ts
+++ b/packages/console-extension/src/index.ts
@@ -195,13 +195,13 @@ async function activateConsole(
return;
}
disposables = new DisposableSet();
- let baseUrl = PageConfig.getBaseUrl();
- for (let name in specs.kernelspecs) {
- let rank = name === specs.default ? 0 : Infinity;
+ const baseUrl = PageConfig.getBaseUrl();
+ for (const name in specs.kernelspecs) {
+ const rank = name === specs.default ? 0 : Infinity;
const spec = specs.kernelspecs[name]!;
let kernelIconUrl = spec.resources['logo-64x64'];
if (kernelIconUrl) {
- let index = kernelIconUrl.indexOf('kernelspecs');
+ const index = kernelIconUrl.indexOf('kernelspecs');
kernelIconUrl = URLExt.join(baseUrl, kernelIconUrl.slice(index));
}
disposables.add(
@@ -327,8 +327,8 @@ async function activateConsole(
let command = CommandIDs.open;
commands.addCommand(command, {
execute: (args: IOpenOptions) => {
- let path = args['path'];
- let widget = tracker.find(value => {
+ const path = args['path'];
+ const widget = tracker.find(value => {
return value.console.sessionContext.session?.path === path;
});
if (widget) {
@@ -338,7 +338,7 @@ async function activateConsole(
return widget;
} else {
return manager.ready.then(() => {
- let model = find(manager.sessions.running(), item => {
+ const model = find(manager.sessions.running(), item => {
return item.path === path;
});
if (model) {
@@ -369,7 +369,7 @@ async function activateConsole(
},
icon: args => (args['isPalette'] ? undefined : consoleIcon),
execute: args => {
- let basePath =
+ const basePath =
(args['basePath'] as string) ||
(args['cwd'] as string) ||
browserFactory.defaultBrowser.model.path;
@@ -379,8 +379,8 @@ async function activateConsole(
// Get the current widget and activate unless the args specify otherwise.
function getCurrent(args: ReadonlyPartialJSONObject): ConsolePanel | null {
- let widget = tracker.currentWidget;
- let activate = args['activate'] !== false;
+ const widget = tracker.currentWidget;
+ const activate = args['activate'] !== false;
if (activate && widget) {
shell.activateById(widget.id);
}
@@ -390,7 +390,7 @@ async function activateConsole(
commands.addCommand(CommandIDs.clear, {
label: 'Clear Console Cells',
execute: args => {
- let current = getCurrent(args);
+ const current = getCurrent(args);
if (!current) {
return;
}
@@ -402,7 +402,7 @@ async function activateConsole(
commands.addCommand(CommandIDs.runUnforced, {
label: 'Run Cell (unforced)',
execute: args => {
- let current = getCurrent(args);
+ const current = getCurrent(args);
if (!current) {
return;
}
@@ -414,7 +414,7 @@ async function activateConsole(
commands.addCommand(CommandIDs.runForced, {
label: 'Run Cell (forced)',
execute: args => {
- let current = getCurrent(args);
+ const current = getCurrent(args);
if (!current) {
return;
}
@@ -426,7 +426,7 @@ async function activateConsole(
commands.addCommand(CommandIDs.linebreak, {
label: 'Insert Line Break',
execute: args => {
- let current = getCurrent(args);
+ const current = getCurrent(args);
if (!current) {
return;
}
@@ -438,7 +438,7 @@ async function activateConsole(
commands.addCommand(CommandIDs.replaceSelection, {
label: 'Replace Selection in Console',
execute: args => {
- let current = getCurrent(args);
+ const current = getCurrent(args);
if (!current) {
return;
}
@@ -451,11 +451,11 @@ async function activateConsole(
commands.addCommand(CommandIDs.interrupt, {
label: 'Interrupt Kernel',
execute: args => {
- let current = getCurrent(args);
+ const current = getCurrent(args);
if (!current) {
return;
}
- let kernel = current.console.sessionContext.session?.kernel;
+ const kernel = current.console.sessionContext.session?.kernel;
if (kernel) {
return kernel.interrupt();
}
@@ -466,7 +466,7 @@ async function activateConsole(
commands.addCommand(CommandIDs.restart, {
label: 'Restart Kernel…',
execute: args => {
- let current = getCurrent(args);
+ const current = getCurrent(args);
if (!current) {
return;
}
@@ -502,7 +502,7 @@ async function activateConsole(
commands.addCommand(CommandIDs.inject, {
execute: args => {
- let path = args['path'];
+ const path = args['path'];
tracker.find(widget => {
if (widget.console.sessionContext.session?.path === path) {
if (args['activate'] !== false) {
@@ -523,7 +523,7 @@ async function activateConsole(
commands.addCommand(CommandIDs.changeKernel, {
label: 'Change Kernel…',
execute: args => {
- let current = getCurrent(args);
+ const current = getCurrent(args);
if (!current) {
return;
}
@@ -579,7 +579,7 @@ async function activateConsole(
mainMenu.kernelMenu.kernelUsers.add({
tracker,
interruptKernel: current => {
- let kernel = current.console.sessionContext.session?.kernel;
+ const kernel = current.console.sessionContext.session?.kernel;
if (kernel) {
return kernel.interrupt();
}
diff --git a/packages/console/src/foreign.ts b/packages/console/src/foreign.ts
index 890aebc94f0e..705810c9b44d 100644
--- a/packages/console/src/foreign.ts
+++ b/packages/console/src/foreign.ts
@@ -83,26 +83,26 @@ export class ForeignHandler implements IDisposable {
if (!this._enabled) {
return false;
}
- let kernel = this.sessionContext.session?.kernel;
+ const kernel = this.sessionContext.session?.kernel;
if (!kernel) {
return false;
}
// Check whether this message came from an external session.
- let parent = this._parent;
- let session = (msg.parent_header as KernelMessage.IHeader).session;
+ const parent = this._parent;
+ const session = (msg.parent_header as KernelMessage.IHeader).session;
if (session === kernel.clientId) {
return false;
}
- let msgType = msg.header.msg_type;
- let parentHeader = msg.parent_header as KernelMessage.IHeader;
- let parentMsgId = parentHeader.msg_id as string;
+ const msgType = msg.header.msg_type;
+ const parentHeader = msg.parent_header as KernelMessage.IHeader;
+ const parentMsgId = parentHeader.msg_id as string;
let cell: CodeCell | undefined;
switch (msgType) {
case 'execute_input':
- let inputMsg = msg as KernelMessage.IExecuteInputMsg;
+ const inputMsg = msg as KernelMessage.IExecuteInputMsg;
cell = this._newCell(parentMsgId);
- let model = cell.model;
+ const model = cell.model;
model.executionCount = inputMsg.content.execution_count;
model.value.text = inputMsg.content.code;
model.trusted = true;
@@ -124,7 +124,7 @@ export class ForeignHandler implements IDisposable {
parent.update();
return true;
case 'clear_output':
- let wait = (msg as KernelMessage.IClearOutputMsg).content.wait;
+ const wait = (msg as KernelMessage.IClearOutputMsg).content.wait;
cell = this._parent.getCell(parentMsgId);
if (cell) {
cell.model.outputs.clear(wait);
@@ -139,7 +139,7 @@ export class ForeignHandler implements IDisposable {
* Create a new code cell for an input originated from a foreign session.
*/
private _newCell(parentMsgId: string): CodeCell {
- let cell = this.parent.createCodeCell();
+ const cell = this.parent.createCodeCell();
cell.addClass(FOREIGN_CELL_CLASS);
this._parent.addCell(cell, parentMsgId);
return cell;
diff --git a/packages/console/src/history.ts b/packages/console/src/history.ts
index 0ca5e71d60b2..e6397360d740 100644
--- a/packages/console/src/history.ts
+++ b/packages/console/src/history.ts
@@ -99,7 +99,7 @@ export class ConsoleHistory implements IConsoleHistory {
return;
}
- let prev = this._editor;
+ const prev = this._editor;
if (prev) {
prev.edgeRequested.disconnect(this.onEdgeRequest, this);
prev.model.value.changed.disconnect(this.onTextChange, this);
@@ -156,7 +156,7 @@ export class ConsoleHistory implements IConsoleHistory {
--this._cursor;
this._cursor = Math.max(0, this._cursor);
- let content = this._filtered[this._cursor];
+ const content = this._filtered[this._cursor];
return Promise.resolve(content);
}
@@ -180,7 +180,7 @@ export class ConsoleHistory implements IConsoleHistory {
++this._cursor;
this._cursor = Math.min(this._filtered.length - 1, this._cursor);
- let content = this._filtered[this._cursor];
+ const content = this._filtered[this._cursor];
return Promise.resolve(content);
}
@@ -254,8 +254,8 @@ export class ConsoleHistory implements IConsoleHistory {
editor: CodeEditor.IEditor,
location: CodeEditor.EdgeLocation
): void {
- let model = editor.model;
- let source = model.value.text;
+ const model = editor.model;
+ const source = model.value.text;
if (location === 'top' || location === 'topLine') {
void this.back(source).then(value => {
@@ -279,13 +279,13 @@ export class ConsoleHistory implements IConsoleHistory {
if (this.isDisposed) {
return;
}
- let text = value || this.placeholder;
+ const text = value || this.placeholder;
if (model.value.text === text) {
return;
}
this._setByHistory = true;
model.value.text = text;
- let pos = editor.getPositionAt(text.length);
+ const pos = editor.getPositionAt(text.length);
if (pos) {
editor.setCursorPosition(pos);
}
@@ -297,7 +297,7 @@ export class ConsoleHistory implements IConsoleHistory {
* Handle the current kernel changing.
*/
private async _handleKernel(): Promise {
- let kernel = this.sessionContext.session?.kernel;
+ const kernel = this.sessionContext.session?.kernel;
if (!kernel) {
this._history.length = 0;
return;
diff --git a/packages/console/src/panel.ts b/packages/console/src/panel.ts
index dad047280f61..4d667672810f 100644
--- a/packages/console/src/panel.ts
+++ b/packages/console/src/panel.ts
@@ -48,9 +48,9 @@ export class ConsolePanel extends MainAreaWidget {
modelFactory,
sessionContext
} = options;
- let contentFactory = (this.contentFactory =
+ const contentFactory = (this.contentFactory =
options.contentFactory || ConsolePanel.defaultContentFactory);
- let count = Private.count++;
+ const count = Private.count++;
if (!path) {
path = `${basePath || ''}/console-${count}-${UUID.uuid4()}`;
}
@@ -67,7 +67,7 @@ export class ConsolePanel extends MainAreaWidget {
setBusy: options.setBusy
});
- let resolver = new RenderMimeRegistry.UrlResolver({
+ const resolver = new RenderMimeRegistry.UrlResolver({
session: sessionContext,
contents: manager.contents
});
@@ -130,7 +130,7 @@ export class ConsolePanel extends MainAreaWidget {
* Handle `'activate-request'` messages.
*/
protected onActivateRequest(msg: Message): void {
- let prompt = this.console.promptCell;
+ const prompt = this.console.promptCell;
if (prompt) {
prompt.editor.focus();
}
@@ -293,7 +293,7 @@ namespace Private {
connected: Date | null,
executed: Date | null
) {
- let sessionContext = panel.console.sessionContext.session;
+ const sessionContext = panel.console.sessionContext.session;
if (sessionContext) {
let caption =
`Name: ${sessionContext.name}\n` +
diff --git a/packages/console/src/widget.ts b/packages/console/src/widget.ts
index 539e44f99fb2..2265689f3492 100644
--- a/packages/console/src/widget.ts
+++ b/packages/console/src/widget.ts
@@ -191,7 +191,7 @@ export class CodeConsole extends Widget {
* The console input prompt cell.
*/
get promptCell(): CodeCell | null {
- let inputLayout = this._input.layout as PanelLayout;
+ const inputLayout = this._input.layout as PanelLayout;
return (inputLayout.widgets[0] as CodeCell) || null;
}
@@ -226,14 +226,14 @@ export class CodeConsole extends Widget {
addBanner() {
if (this._banner) {
// An old banner just becomes a normal cell now.
- let cell = this._banner;
+ const cell = this._banner;
this._cells.push(this._banner);
cell.disposed.connect(this._onCellDisposed, this);
}
// Create the banner.
- let model = this.modelFactory.createRawCell({});
+ const model = this.modelFactory.createRawCell({});
model.value.text = '...';
- let banner = (this._banner = new RawCell({
+ const banner = (this._banner = new RawCell({
model,
contentFactory: this.contentFactory
})).initializeState();
@@ -247,7 +247,7 @@ export class CodeConsole extends Widget {
*/
clear(): void {
// Dispose all the content cells
- let cells = this._cells;
+ const cells = this._cells;
while (cells.length > 0) {
cells.get(0).dispose();
}
@@ -257,9 +257,9 @@ export class CodeConsole extends Widget {
* Create a new cell with the built-in factory.
*/
createCodeCell(): CodeCell {
- let factory = this.contentFactory;
- let options = this._createCodeCellOptions();
- let cell = factory.createCodeCell(options);
+ const factory = this.contentFactory;
+ const options = this._createCodeCellOptions();
+ const cell = factory.createCodeCell(options);
cell.readOnly = true;
cell.model.mimeType = this._mimetype;
return cell;
@@ -310,7 +310,7 @@ export class CodeConsole extends Widget {
}
// Check whether we should execute.
- let shouldExecute = await this._shouldExecute(timeout);
+ const shouldExecute = await this._shouldExecute(timeout);
if (this.isDisposed) {
return;
}
@@ -342,9 +342,9 @@ export class CodeConsole extends Widget {
* @returns A promise that indicates when the injected cell's execution ends.
*/
inject(code: string, metadata: JSONObject = {}): Promise {
- let cell = this.createCodeCell();
+ const cell = this.createCodeCell();
cell.model.value.text = code;
- for (let key of Object.keys(metadata)) {
+ for (const key of Object.keys(metadata)) {
cell.model.metadata.set(key, metadata[key]);
}
this.addCell(cell);
@@ -355,7 +355,7 @@ export class CodeConsole extends Widget {
* Insert a line break in the prompt cell.
*/
insertLinebreak(): void {
- let promptCell = this.promptCell;
+ const promptCell = this.promptCell;
if (!promptCell) {
return;
}
@@ -368,7 +368,7 @@ export class CodeConsole extends Widget {
* @param text - The text to replace the selection.
*/
replaceSelection(text: string): void {
- let promptCell = this.promptCell;
+ const promptCell = this.promptCell;
if (!promptCell) {
return;
}
@@ -385,7 +385,7 @@ export class CodeConsole extends Widget {
serialize(): nbformat.ICodeCell[] {
const cells: nbformat.ICodeCell[] = [];
each(this._cells, cell => {
- let model = cell.model;
+ const model = cell.model;
if (isCodeCellModel(model)) {
cells.push(model.toJSON());
}
@@ -413,7 +413,7 @@ export class CodeConsole extends Widget {
}
let target = event.target as HTMLElement;
- let cellFilter = (node: HTMLElement) =>
+ const cellFilter = (node: HTMLElement) =>
node.classList.contains(CONSOLE_CELL_CLASS);
let cellIndex = CellDragUtils.findCell(target, this._cells, cellFilter);
@@ -435,7 +435,7 @@ export class CodeConsole extends Widget {
const cell = this._cells.get(cellIndex);
- let targetArea: CellDragUtils.ICellTargetArea = CellDragUtils.detectTargetArea(
+ const targetArea: CellDragUtils.ICellTargetArea = CellDragUtils.detectTargetArea(
cell,
event.target as HTMLElement
);
@@ -482,7 +482,7 @@ export class CodeConsole extends Widget {
clientY: number
): Promise {
const cellModel = this._focusedCell!.model as ICodeCellModel;
- let selected: nbformat.ICell[] = [cellModel.toJSON()];
+ const selected: nbformat.ICell[] = [cellModel.toJSON()];
const dragImage = CellDragUtils.createCellDragImage(
this._focusedCell!,
@@ -547,7 +547,7 @@ export class CodeConsole extends Widget {
* Handle `after_attach` messages for the widget.
*/
protected onAfterAttach(msg: Message): void {
- let node = this.node;
+ const node = this.node;
node.addEventListener('keydown', this, true);
node.addEventListener('click', this);
node.addEventListener('mousedown', this);
@@ -564,7 +564,7 @@ export class CodeConsole extends Widget {
* Handle `before-detach` messages for the widget.
*/
protected onBeforeDetach(msg: Message): void {
- let node = this.node;
+ const node = this.node;
node.removeEventListener('keydown', this, true);
node.removeEventListener('click', this);
}
@@ -573,7 +573,7 @@ export class CodeConsole extends Widget {
* Handle `'activate-request'` messages.
*/
protected onActivateRequest(msg: Message): void {
- let editor = this.promptCell && this.promptCell.editor;
+ const editor = this.promptCell && this.promptCell.editor;
if (editor) {
editor.focus();
}
@@ -585,21 +585,21 @@ export class CodeConsole extends Widget {
*/
protected newPromptCell(): void {
let promptCell = this.promptCell;
- let input = this._input;
+ const input = this._input;
// Make the last prompt read-only, clear its signals, and move to content.
if (promptCell) {
promptCell.readOnly = true;
promptCell.removeClass(PROMPT_CLASS);
Signal.clearData(promptCell.editor);
- let child = input.widgets[0];
+ const child = input.widgets[0];
child.parent = null;
this.addCell(promptCell);
}
// Create the new prompt cell.
- let factory = this.contentFactory;
- let options = this._createCodeCellOptions();
+ const factory = this.contentFactory;
+ const options = this._createCodeCellOptions();
promptCell = factory.createCodeCell(options);
promptCell.model.mimeType = this._mimetype;
promptCell.addClass(PROMPT_CLASS);
@@ -608,7 +608,7 @@ export class CodeConsole extends Widget {
this._input.addWidget(promptCell);
// Suppress the default "Enter" key handling.
- let editor = promptCell.editor;
+ const editor = promptCell.editor;
editor.addKeydownHandler(this._onEditorKeydown);
this._history.editor = editor;
@@ -626,7 +626,7 @@ export class CodeConsole extends Widget {
* Handle the `'keydown'` event for the widget.
*/
private _evtKeyDown(event: KeyboardEvent): void {
- let editor = this.promptCell && this.promptCell.editor;
+ const editor = this.promptCell && this.promptCell.editor;
if (!editor) {
return;
}
@@ -657,7 +657,7 @@ export class CodeConsole extends Widget {
* Execute the code in the current prompt cell.
*/
private _execute(cell: CodeCell): Promise {
- let source = cell.model.value.text;
+ const source = cell.model.value.text;
this._history.push(source);
// If the source of the console is just "clear", clear the console as we
// do in IPython or QtConsole.
@@ -666,19 +666,19 @@ export class CodeConsole extends Widget {
return Promise.resolve(void 0);
}
cell.model.contentChanged.connect(this.update, this);
- let onSuccess = (value: KernelMessage.IExecuteReplyMsg) => {
+ const onSuccess = (value: KernelMessage.IExecuteReplyMsg) => {
if (this.isDisposed) {
return;
}
if (value && value.content.status === 'ok') {
- let content = value.content;
+ const content = value.content;
// Use deprecated payloads for backwards compatibility.
if (content.payload && content.payload.length) {
- let setNextInput = content.payload.filter(i => {
+ const setNextInput = content.payload.filter(i => {
return (i as any).source === 'set_next_input';
})[0];
if (setNextInput) {
- let text = (setNextInput as any).text;
+ const text = (setNextInput as any).text;
// Ignore the `replace` value and always set the next cell.
cell.model.value.text = text;
}
@@ -694,7 +694,7 @@ export class CodeConsole extends Widget {
this.update();
this._executed.emit(new Date());
};
- let onFailure = () => {
+ const onFailure = () => {
if (this.isDisposed) {
return;
}
@@ -716,7 +716,7 @@ export class CodeConsole extends Widget {
return;
}
this._banner!.model.value.text = info.banner;
- let lang = info.language_info as nbformat.ILanguageInfoMetadata;
+ const lang = info.language_info as nbformat.ILanguageInfoMetadata;
this._mimetype = this._mimeTypeService.getMimeTypeByLanguage(lang);
if (this.promptCell) {
this.promptCell.model.mimeType = this._mimetype;
@@ -727,10 +727,10 @@ export class CodeConsole extends Widget {
* Create the options used to initialize a code cell widget.
*/
private _createCodeCellOptions(): CodeCell.IOptions {
- let contentFactory = this.contentFactory;
- let modelFactory = this.modelFactory;
- let model = modelFactory.createCodeCell({});
- let rendermime = this.rendermime;
+ const contentFactory = this.contentFactory;
+ const modelFactory = this.modelFactory;
+ const model = modelFactory.createCodeCell({});
+ const rendermime = this.rendermime;
return { model, rendermime, contentFactory };
}
@@ -756,13 +756,13 @@ export class CodeConsole extends Widget {
if (!promptCell) {
return Promise.resolve(false);
}
- let model = promptCell.model;
- let code = model.value.text;
+ const model = promptCell.model;
+ const code = model.value.text;
return new Promise((resolve, reject) => {
- let timer = setTimeout(() => {
+ const timer = setTimeout(() => {
resolve(true);
}, timeout);
- let kernel = this.sessionContext.session?.kernel;
+ const kernel = this.sessionContext.session?.kernel;
if (!kernel) {
resolve(false);
return;
diff --git a/packages/console/test/foreign.spec.ts b/packages/console/test/foreign.spec.ts
index f1816ebd8c43..408716ae9df6 100644
--- a/packages/console/test/foreign.spec.ts
+++ b/packages/console/test/foreign.spec.ts
@@ -74,7 +74,7 @@ class TestHandler extends ForeignHandler {
) {
this.rejected.emit(msg);
} else {
- console.log(session, this.sessionContext.session?.kernel?.clientId);
+ console.debug(session, this.sessionContext.session?.kernel?.clientId);
}
}
this.received.emit(msg);
diff --git a/packages/coreutils/src/pageconfig.ts b/packages/coreutils/src/pageconfig.ts
index b3a9222b0669..36f09ff4dc60 100644
--- a/packages/coreutils/src/pageconfig.ts
+++ b/packages/coreutils/src/pageconfig.ts
@@ -10,8 +10,8 @@ import { URLExt } from './url';
/**
* Declare stubs for the node variables.
*/
-declare var process: any;
-declare var require: any;
+declare let process: any;
+declare let require: any;
/**
* The namespace for `PageConfig` functions.
@@ -65,10 +65,9 @@ export namespace PageConfig {
fullPath = path.resolve(process.env['JUPYTER_CONFIG_DATA']);
}
if (fullPath) {
- /* tslint:disable */
// Force Webpack to ignore this require.
+ // eslint-disable-next-line
configData = eval('require')(fullPath) as { [key: string]: string };
- /* tslint:enable */
}
} catch (e) {
console.error(e);
@@ -78,7 +77,7 @@ export namespace PageConfig {
if (!JSONExt.isObject(configData)) {
configData = Object.create(null);
} else {
- for (let key in configData) {
+ for (const key in configData) {
// PageConfig expects strings
if (typeof configData[key] !== 'string') {
configData[key] = JSON.stringify(configData[key]);
@@ -201,7 +200,7 @@ export namespace PageConfig {
if (typeof document === 'undefined' || !document.body) {
return '';
}
- let val = document.body.dataset[key];
+ const val = document.body.dataset[key];
if (typeof val === 'undefined') {
return '';
}
diff --git a/packages/coreutils/src/path-posix.d.ts b/packages/coreutils/src/path-posix.d.ts
index e04d58bc8f9f..cfdf2dda1162 100644
--- a/packages/coreutils/src/path-posix.d.ts
+++ b/packages/coreutils/src/path-posix.d.ts
@@ -8,6 +8,7 @@ declare module 'path-posix' {
/**
* A parsed path object generated by path.parse() or consumed by path.format().
*/
+ // eslint-disable-next-line
export interface ParsedPath {
/**
* The root of the path such as '/' or 'c:\'
@@ -100,11 +101,11 @@ declare module 'path-posix' {
/**
* The platform-specific file separator. '\\' or '/'.
*/
- export var sep: string;
+ export let sep: string;
/**
* The platform-specific file delimiter. ';' or ':'.
*/
- export var delimiter: string;
+ export let delimiter: string;
/**
* Returns an object from a path string - the opposite of format().
*
diff --git a/packages/coreutils/src/path.ts b/packages/coreutils/src/path.ts
index b7ee7919dce7..57dddd507e96 100644
--- a/packages/coreutils/src/path.ts
+++ b/packages/coreutils/src/path.ts
@@ -39,7 +39,7 @@ export namespace PathExt {
* @param path - The file path.
*/
export function dirname(path: string): string {
- let dir = removeSlash(posix.dirname(path));
+ const dir = removeSlash(posix.dirname(path));
return dir === '.' ? '' : dir;
}
diff --git a/packages/coreutils/src/text.ts b/packages/coreutils/src/text.ts
index fdbab161f8d9..2b037622f7f6 100644
--- a/packages/coreutils/src/text.ts
+++ b/packages/coreutils/src/text.ts
@@ -29,10 +29,10 @@ export namespace Text {
}
let charIdx = jsIdx;
for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {
- let charCode = text.charCodeAt(i);
+ const charCode = text.charCodeAt(i);
// check for surrogate pair
if (charCode >= 0xd800 && charCode <= 0xdbff) {
- let nextCharCode = text.charCodeAt(i + 1);
+ const nextCharCode = text.charCodeAt(i + 1);
if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {
charIdx--;
i++;
@@ -58,10 +58,10 @@ export namespace Text {
}
let jsIdx = charIdx;
for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {
- let charCode = text.charCodeAt(i);
+ const charCode = text.charCodeAt(i);
// check for surrogate pair
if (charCode >= 0xd800 && charCode <= 0xdbff) {
- let nextCharCode = text.charCodeAt(i + 1);
+ const nextCharCode = text.charCodeAt(i + 1);
if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {
jsIdx++;
i++;
diff --git a/packages/coreutils/src/url.ts b/packages/coreutils/src/url.ts
index 3f3a6721f0af..fe6fa5c94cf1 100644
--- a/packages/coreutils/src/url.ts
+++ b/packages/coreutils/src/url.ts
@@ -18,7 +18,7 @@ export namespace URLExt {
*/
export function parse(url: string): IUrl {
if (typeof document !== 'undefined' && document) {
- let a = document.createElement('a');
+ const a = document.createElement('a');
a.href = url;
return a;
}
diff --git a/packages/csvviewer-extension/src/index.ts b/packages/csvviewer-extension/src/index.ts
index d419b666c7b7..18873971d12e 100644
--- a/packages/csvviewer-extension/src/index.ts
+++ b/packages/csvviewer-extension/src/index.ts
@@ -118,7 +118,7 @@ function activateCsv(
}
app.docRegistry.addWidgetFactory(factory);
- let ft = app.docRegistry.getFileType('csv');
+ const ft = app.docRegistry.getFileType('csv');
factory.widgetCreated.connect((sender, widget) => {
// Track the widget.
void tracker.add(widget);
@@ -198,7 +198,7 @@ function activateTsv(
}
app.docRegistry.addWidgetFactory(factory);
- let ft = app.docRegistry.getFileType('tsv');
+ const ft = app.docRegistry.getFileType('tsv');
factory.widgetCreated.connect((sender, widget) => {
// Track the widget.
void tracker.add(widget);
diff --git a/packages/csvviewer/src/model.ts b/packages/csvviewer/src/model.ts
index 7a23e395db99..b105c4b836b7 100644
--- a/packages/csvviewer/src/model.ts
+++ b/packages/csvviewer/src/model.ts
@@ -62,7 +62,7 @@ export class DSVModel extends DataModel implements IDisposable {
// Guess the row delimiter if it was not supplied. This will be fooled if a
// different line delimiter possibility appears in the first row.
if (rowDelimiter === undefined) {
- let i = data.slice(0, 5000).indexOf('\r');
+ const i = data.slice(0, 5000).indexOf('\r');
if (i === -1) {
rowDelimiter = '\n';
} else if (data[i + 1] === '\n') {
@@ -84,7 +84,7 @@ export class DSVModel extends DataModel implements IDisposable {
// Cache the header row.
if (header === true && this._columnCount! > 0) {
- let h = [];
+ const h = [];
for (let c = 0; c < this._columnCount!; c++) {
h.push(this._getField(0, c));
}
@@ -245,7 +245,7 @@ export class DSVModel extends DataModel implements IDisposable {
// Parse the data up to and including the requested row, starting from the
// last row offset we have.
- let { nrows, offsets } = PARSERS[this._parser]({
+ const { nrows, offsets } = PARSERS[this._parser]({
data: this._data,
startIndex: this._rowOffsets[this._rowCount! - 1],
delimiter: this._delimiter,
@@ -266,7 +266,7 @@ export class DSVModel extends DataModel implements IDisposable {
this._startedParsing = true;
// Update the row count.
- let oldRowCount = this._rowCount!;
+ const oldRowCount = this._rowCount!;
this._rowCount = oldRowCount + nrows - 1;
// If we didn't reach the requested row, we must be done.
@@ -276,7 +276,7 @@ export class DSVModel extends DataModel implements IDisposable {
}
// Copy the new offsets into a new row offset array.
- let oldRowOffsets = this._rowOffsets;
+ const oldRowOffsets = this._rowOffsets;
this._rowOffsets = new Uint32Array(this._rowCount);
this._rowOffsets.set(oldRowOffsets);
this._rowOffsets.set(offsets, oldRowCount - 1);
@@ -286,7 +286,7 @@ export class DSVModel extends DataModel implements IDisposable {
// If the full column offsets array is small enough, build a cache big
// enough for all column offsets. We allocate up to 128 megabytes:
// 128*(2**20 bytes/M)/(4 bytes/entry) = 33554432 entries.
- let maxColumnOffsetsRows = Math.floor(33554432 / this._columnCount);
+ const maxColumnOffsetsRows = Math.floor(33554432 / this._columnCount);
// We need to expand the column offset array if we were storing all column
// offsets before. Check to see if the previous size was small enough that
@@ -296,7 +296,7 @@ export class DSVModel extends DataModel implements IDisposable {
// store, or if we should cut over to a small cache.
if (this._rowCount <= maxColumnOffsetsRows) {
// Expand the existing column offset array for new column offsets.
- let oldColumnOffsets = this._columnOffsets;
+ const oldColumnOffsets = this._columnOffsets;
this._columnOffsets = new Uint32Array(
this._rowCount * this._columnCount
);
@@ -305,7 +305,7 @@ export class DSVModel extends DataModel implements IDisposable {
} else {
// If not, then our cache size is at most the maximum number of rows we
// fill in the cache at a time.
- let oldColumnOffsets = this._columnOffsets;
+ const oldColumnOffsets = this._columnOffsets;
this._columnOffsets = new Uint32Array(
Math.min(this._maxCacheGet, maxColumnOffsetsRows) * this._columnCount
);
@@ -347,7 +347,7 @@ export class DSVModel extends DataModel implements IDisposable {
let nextIndex;
// Find the index for the first character in the field.
- let index = this._getOffsetIndex(row, column);
+ const index = this._getOffsetIndex(row, column);
// Initialize the trim adjustments.
let trimRight = 0;
@@ -441,7 +441,7 @@ export class DSVModel extends DataModel implements IDisposable {
}
// Parse the data to get the column offsets.
- let { offsets } = PARSERS[this._parser]({
+ const { offsets } = PARSERS[this._parser]({
data: this._data,
delimiter: this._delimiter,
rowDelimiter: this._rowDelimiter,
@@ -479,10 +479,10 @@ export class DSVModel extends DataModel implements IDisposable {
let chunkRows = Math.pow(2, 32) - 1;
// We give the UI a chance to draw by delaying the chunk parsing.
- let delay = 30; // milliseconds
+ const delay = 30; // milliseconds
// Define a function to parse a chunk up to and including endRow.
- let parseChunk = (endRow: number) => {
+ const parseChunk = (endRow: number) => {
try {
this._computeRowOffsets(endRow);
} catch (e) {
@@ -505,7 +505,7 @@ export class DSVModel extends DataModel implements IDisposable {
this._resetParser();
// Parse the first rows to give us the start of the data right away.
- let done = parseChunk(currentRows);
+ const done = parseChunk(currentRows);
// If we are done, return early.
if (done) {
@@ -513,9 +513,9 @@ export class DSVModel extends DataModel implements IDisposable {
}
// Define a function to recursively parse the next chunk after a delay.
- let delayedParse = () => {
+ const delayedParse = () => {
// Parse up to the new end row.
- let done = parseChunk(currentRows + chunkRows);
+ const done = parseChunk(currentRows + chunkRows);
currentRows += chunkRows;
// Gradually double the chunk size until we reach a million rows, if we
diff --git a/packages/csvviewer/src/parse.ts b/packages/csvviewer/src/parse.ts
index 1c010f1aa5e5..fafcfe719f15 100644
--- a/packages/csvviewer/src/parse.ts
+++ b/packages/csvviewer/src/parse.ts
@@ -171,7 +171,7 @@ export function parseDSV(options: IParser.IOptions): IParser.IResults {
let nrows = 0;
// The row or column offsets we return.
- let offsets = [];
+ const offsets = [];
// Set up some useful local variables.
const CH_DELIMITER = delimiter.charCodeAt(0);
@@ -500,13 +500,13 @@ export function parseDSVNoQuotes(options: IParser.IOptions): IParser.IResults {
let ncols = options.ncols;
// Set up our return variables.
- let offsets: number[] = [];
+ const offsets: number[] = [];
let nrows = 0;
// Set up various state variables.
- let rowDelimiterLength = rowDelimiter.length;
+ const rowDelimiterLength = rowDelimiter.length;
let currRow = startIndex;
- let len = data.length;
+ const len = data.length;
let nextRow: number;
let col: number;
let rowString: string;
diff --git a/packages/csvviewer/src/toolbar.ts b/packages/csvviewer/src/toolbar.ts
index df0e220290ed..11351f8ce74f 100644
--- a/packages/csvviewer/src/toolbar.ts
+++ b/packages/csvviewer/src/toolbar.ts
@@ -119,13 +119,13 @@ namespace Private {
* Create the node for the delimiter switcher.
*/
export function createNode(selected: string): HTMLElement {
- let div = document.createElement('div');
- let label = document.createElement('span');
- let select = document.createElement('select');
+ const div = document.createElement('div');
+ const label = document.createElement('span');
+ const select = document.createElement('select');
label.textContent = 'Delimiter: ';
label.className = CSV_DELIMITER_LABEL_CLASS;
each(zip(DELIMITERS, LABELS), ([delimiter, label]) => {
- let option = document.createElement('option');
+ const option = document.createElement('option');
option.value = delimiter;
option.textContent = label;
if (delimiter === selected) {
@@ -134,7 +134,7 @@ namespace Private {
select.appendChild(option);
});
div.appendChild(label);
- let node = Styling.wrapSelect(select);
+ const node = Styling.wrapSelect(select);
node.classList.add(CSV_DELIMITER_DROPDOWN_CLASS);
div.appendChild(node);
return div;
diff --git a/packages/csvviewer/src/widget.ts b/packages/csvviewer/src/widget.ts
index bd9540d0c6db..286739432376 100644
--- a/packages/csvviewer/src/widget.ts
+++ b/packages/csvviewer/src/widget.ts
@@ -242,8 +242,8 @@ export class CSVViewer extends Widget {
constructor(options: CSVViewer.IOptions) {
super();
- let context = (this._context = options.context);
- let layout = (this.layout = new PanelLayout());
+ const context = (this._context = options.context);
+ const layout = (this.layout = new PanelLayout());
this.addClass(CSV_CLASS);
@@ -365,9 +365,9 @@ export class CSVViewer extends Widget {
* Create the model for the grid.
*/
private _updateGrid(): void {
- let data: string = this._context.model.toString();
- let delimiter = this._delimiter;
- let oldModel = this._grid.dataModel as DSVModel;
+ const data: string = this._context.model.toString();
+ const delimiter = this._delimiter;
+ const oldModel = this._grid.dataModel as DSVModel;
const dataModel = (this._grid.dataModel = new DSVModel({
data,
delimiter
@@ -454,7 +454,7 @@ export class CSVDocumentWidget extends DocumentWidget {
* Set URI fragment identifier for rows
*/
setFragment(fragment: string): void {
- let parseFragments = fragment.split('=');
+ const parseFragments = fragment.split('=');
// TODO: expand to allow columns and cells to be selected
// reference: https://tools.ietf.org/html/rfc7111#section-3
diff --git a/packages/docmanager-extension/src/index.ts b/packages/docmanager-extension/src/index.ts
index cfa34c99a1d2..f471e2a66bb7 100644
--- a/packages/docmanager-extension/src/index.ts
+++ b/packages/docmanager-extension/src/index.ts
@@ -120,7 +120,7 @@ const docManagerPlugin: JupyterFrontEndPlugin = {
shell.activateById(widget.id);
// Handle dirty state for open documents.
- let context = docManager.contextForWidget(widget);
+ const context = docManager.contextForWidget(widget);
if (context && !contexts.has(context)) {
if (status) {
handleContext(status, context);
@@ -412,7 +412,7 @@ function addCommands(
const errorTitle = (args['error'] as string) || 'Error';
const path =
typeof args['path'] === 'undefined' ? '' : (args['path'] as string);
- let options: Partial = {
+ const options: Partial = {
type: args['type'] as Contents.ContentType,
path
};
@@ -565,7 +565,7 @@ function addCommands(
execute: () => {
// Checks that shell.currentWidget is valid:
if (isEnabled()) {
- let context = docManager.contextForWidget(shell.currentWidget!);
+ const context = docManager.contextForWidget(shell.currentWidget!);
if (!context) {
return showDialog({
title: 'Cannot Save',
@@ -624,7 +624,7 @@ function addCommands(
execute: () => {
// Checks that shell.currentWidget is valid:
if (isEnabled()) {
- let context = docManager.contextForWidget(shell.currentWidget!);
+ const context = docManager.contextForWidget(shell.currentWidget!);
if (!context) {
return showDialog({
title: 'Cannot Save',
@@ -644,7 +644,7 @@ function addCommands(
execute: () => {
// Checks that shell.currentWidget is valid:
if (isEnabled()) {
- let context = docManager.contextForWidget(shell.currentWidget!);
+ const context = docManager.contextForWidget(shell.currentWidget!);
if (!context) {
return showDialog({
title: 'Cannot Download',
@@ -740,7 +740,7 @@ function addLabCommands(
return;
}
// Clone the widget.
- let child = docManager.cloneWidget(widget);
+ const child = docManager.cloneWidget(widget);
if (child) {
opener.open(child, options);
}
@@ -753,7 +753,7 @@ function addLabCommands(
execute: () => {
// Implies contextMenuWidget() !== null
if (isEnabled()) {
- let context = docManager.contextForWidget(contextMenuWidget()!);
+ const context = docManager.contextForWidget(contextMenuWidget()!);
return renameDialog(docManager, context!.path);
}
}
@@ -763,8 +763,8 @@ function addLabCommands(
label: () => `Show in File Browser`,
isEnabled,
execute: async () => {
- let widget = contextMenuWidget();
- let context = widget && docManager.contextForWidget(widget);
+ const widget = contextMenuWidget();
+ const context = widget && docManager.contextForWidget(widget);
if (!context) {
return;
}
@@ -800,7 +800,7 @@ function handleContext(
context: DocumentRegistry.Context
): void {
let disposable: IDisposable | null = null;
- let onStateChanged = (sender: any, args: IChangedArgs) => {
+ const onStateChanged = (sender: any, args: IChangedArgs) => {
if (args.name === 'dirty') {
if (args.newValue === true) {
if (!disposable) {
@@ -838,22 +838,22 @@ namespace Private {
checkpoint: Contents.ICheckpointModel,
fileType: string
): HTMLElement {
- let body = document.createElement('div');
- let confirmMessage = document.createElement('p');
- let confirmText = document.createTextNode(`Are you sure you want to revert
+ const body = document.createElement('div');
+ const confirmMessage = document.createElement('p');
+ const confirmText = document.createTextNode(`Are you sure you want to revert
the ${fileType} to the latest checkpoint? `);
- let cannotUndoText = document.createElement('strong');
+ const cannotUndoText = document.createElement('strong');
cannotUndoText.textContent = 'This cannot be undone.';
confirmMessage.appendChild(confirmText);
confirmMessage.appendChild(cannotUndoText);
- let lastCheckpointMessage = document.createElement('p');
- let lastCheckpointText = document.createTextNode(
+ const lastCheckpointMessage = document.createElement('p');
+ const lastCheckpointText = document.createTextNode(
'The checkpoint was last updated at: '
);
- let lastCheckpointDate = document.createElement('p');
- let date = new Date(checkpoint.last_modified);
+ const lastCheckpointDate = document.createElement('p');
+ const date = new Date(checkpoint.last_modified);
lastCheckpointDate.style.textAlign = 'center';
lastCheckpointDate.textContent =
Time.format(date, 'dddd, MMMM Do YYYY, h:mm:ss a') +
diff --git a/packages/docmanager/src/dialogs.ts b/packages/docmanager/src/dialogs.ts
index 0f03950fb129..6adae27de5d3 100644
--- a/packages/docmanager/src/dialogs.ts
+++ b/packages/docmanager/src/dialogs.ts
@@ -64,8 +64,8 @@ export function renameDialog(
);
return null;
}
- let basePath = PathExt.dirname(oldPath);
- let newPath = PathExt.join(basePath, result.value);
+ const basePath = PathExt.dirname(oldPath);
+ const newPath = PathExt.join(basePath, result.value);
return renameFile(manager, oldPath, newPath);
});
}
@@ -95,7 +95,7 @@ export function renameFile(
* Ask the user whether to overwrite a file.
*/
export function shouldOverwrite(path: string): Promise {
- let options = {
+ const options = {
title: 'Overwrite file?',
body: `"${path}" already exists, overwrite?`,
buttons: [Dialog.cancelButton(), Dialog.warnButton({ label: 'Overwrite' })]
@@ -125,8 +125,8 @@ class RenameHandler extends Widget {
constructor(oldPath: string) {
super({ node: Private.createRenameNode(oldPath) });
this.addClass(FILE_DIALOG_CLASS);
- let ext = PathExt.extname(oldPath);
- let value = (this.inputNode.value = PathExt.basename(oldPath));
+ const ext = PathExt.extname(oldPath);
+ const value = (this.inputNode.value = PathExt.basename(oldPath));
this.inputNode.setSelectionRange(0, value.length - ext.length);
}
@@ -153,16 +153,16 @@ namespace Private {
* Create the node for a rename handler.
*/
export function createRenameNode(oldPath: string): HTMLElement {
- let body = document.createElement('div');
- let existingLabel = document.createElement('label');
+ const body = document.createElement('div');
+ const existingLabel = document.createElement('label');
existingLabel.textContent = 'File Path';
- let existingPath = document.createElement('span');
+ const existingPath = document.createElement('span');
existingPath.textContent = oldPath;
- let nameTitle = document.createElement('label');
+ const nameTitle = document.createElement('label');
nameTitle.textContent = 'New Name';
nameTitle.className = RENAME_NEWNAME_TITLE_CLASS;
- let name = document.createElement('input');
+ const name = document.createElement('input');
body.appendChild(existingLabel);
body.appendChild(existingPath);
diff --git a/packages/docmanager/src/manager.ts b/packages/docmanager/src/manager.ts
index 0819822adf5b..a360c30de26f 100644
--- a/packages/docmanager/src/manager.ts
+++ b/packages/docmanager/src/manager.ts
@@ -53,7 +53,9 @@ export class DocumentManager implements IDocumentManager {
this._opener = options.opener;
this._when = options.when || options.manager.ready;
- let widgetManager = new DocumentWidgetManager({ registry: this.registry });
+ const widgetManager = new DocumentWidgetManager({
+ registry: this.registry
+ });
widgetManager.activateRequested.connect(this._onActivateRequested, this);
this._widgetManager = widgetManager;
this._setBusy = options.setBusy;
@@ -279,10 +281,10 @@ export class DocumentManager implements IDocumentManager {
path: string,
widgetName: string | null = 'default'
): IDocumentWidget | undefined {
- let newPath = PathExt.normalize(path);
+ const newPath = PathExt.normalize(path);
let widgetNames = [widgetName];
if (widgetName === 'default') {
- let factory = this.registry.defaultWidgetFactory(newPath);
+ const factory = this.registry.defaultWidgetFactory(newPath);
if (!factory) {
return undefined;
}
@@ -293,10 +295,10 @@ export class DocumentManager implements IDocumentManager {
.map(f => f.name);
}
- for (let context of this._contextsForPath(newPath)) {
+ for (const context of this._contextsForPath(newPath)) {
for (const widgetName of widgetNames) {
if (widgetName !== null) {
- let widget = this._widgetManager.findWidget(context, widgetName);
+ const widget = this._widgetManager.findWidget(context, widgetName);
if (widget) {
return widget;
}
@@ -370,7 +372,7 @@ export class DocumentManager implements IDocumentManager {
kernel?: Partial,
options?: DocumentRegistry.IOpenOptions
): IDocumentWidget | undefined {
- let widget = this.findWidget(path, widgetName);
+ const widget = this.findWidget(path, widgetName);
if (widget) {
this._opener.open(widget, options || {});
return widget;
@@ -458,16 +460,16 @@ export class DocumentManager implements IDocumentManager {
// widgets that have different models.
// Allow options to be passed when adding a sibling.
- let adopter = (
+ const adopter = (
widget: IDocumentWidget,
options?: DocumentRegistry.IOpenOptions
) => {
this._widgetManager.adoptWidget(context, widget);
this._opener.open(widget, options);
};
- let modelDBFactory =
+ const modelDBFactory =
this.services.contents.getModelDBFactory(path) || undefined;
- let context = new Context({
+ const context = new Context({
opener: adopter,
manager: this.services,
factory,
@@ -477,7 +479,7 @@ export class DocumentManager implements IDocumentManager {
setBusy: this._setBusy,
sessionDialogs: this._dialogs
});
- let handler = new SaveHandler({
+ const handler = new SaveHandler({
context,
saveInterval: this.autosaveInterval
});
@@ -506,9 +508,9 @@ export class DocumentManager implements IDocumentManager {
path: string,
widgetName: string
): DocumentRegistry.WidgetFactory | undefined {
- let { registry } = this;
+ const { registry } = this;
if (widgetName === 'default') {
- let factory = registry.defaultWidgetFactory(path);
+ const factory = registry.defaultWidgetFactory(path);
if (!factory) {
return undefined;
}
@@ -532,18 +534,18 @@ export class DocumentManager implements IDocumentManager {
kernel?: Partial,
options?: DocumentRegistry.IOpenOptions
): IDocumentWidget | undefined {
- let widgetFactory = this._widgetFactoryFor(path, widgetName);
+ const widgetFactory = this._widgetFactoryFor(path, widgetName);
if (!widgetFactory) {
return undefined;
}
- let modelName = widgetFactory.modelName || 'text';
- let factory = this.registry.getModelFactory(modelName);
+ const modelName = widgetFactory.modelName || 'text';
+ const factory = this.registry.getModelFactory(modelName);
if (!factory) {
return undefined;
}
// Handle the kernel pereference.
- let preference = this.registry.getKernelPreference(
+ const preference = this.registry.getKernelPreference(
path,
widgetFactory.name,
kernel
@@ -570,7 +572,7 @@ export class DocumentManager implements IDocumentManager {
throw new Error(`Invalid argument 'which': ${which}`);
}
- let widget = this._widgetManager.createWidget(widgetFactory, context);
+ const widget = this._widgetManager.createWidget(widgetFactory, context);
this._opener.open(widget, options || {});
// If the initial opening of the context fails, dispose of the widget.
diff --git a/packages/docmanager/src/savehandler.ts b/packages/docmanager/src/savehandler.ts
index b577996407fe..7ae0d5f45234 100644
--- a/packages/docmanager/src/savehandler.ts
+++ b/packages/docmanager/src/savehandler.ts
@@ -19,7 +19,7 @@ export class SaveHandler implements IDisposable {
*/
constructor(options: SaveHandler.IOptions) {
this._context = options.context;
- let interval = options.saveInterval || 120;
+ const interval = options.saveInterval || 120;
this._minInterval = interval * 1000;
this._interval = this._minInterval;
// Restart the timer when the contents model is updated.
@@ -99,7 +99,7 @@ export class SaveHandler implements IDisposable {
* Handle an autosave timeout.
*/
private _save(): void {
- let context = this._context;
+ const context = this._context;
// Trigger the next update.
this._setTimer();
@@ -110,19 +110,19 @@ export class SaveHandler implements IDisposable {
// Bail if the model is not dirty or the file is not writable, or the dialog
// is already showing.
- let writable = context.contentsModel && context.contentsModel.writable;
+ const writable = context.contentsModel && context.contentsModel.writable;
if (!writable || !context.model.dirty || this._inDialog) {
return;
}
- let start = new Date().getTime();
+ const start = new Date().getTime();
context
.save()
.then(() => {
if (this.isDisposed) {
return;
}
- let duration = new Date().getTime() - start;
+ const duration = new Date().getTime() - start;
// New save interval: higher of 10x save duration or min interval.
this._interval = Math.max(
this._multiplier * duration,
diff --git a/packages/docmanager/src/widgetmanager.ts b/packages/docmanager/src/widgetmanager.ts
index 3124123effab..7bd8fcacaadc 100644
--- a/packages/docmanager/src/widgetmanager.ts
+++ b/packages/docmanager/src/widgetmanager.ts
@@ -77,7 +77,7 @@ export class DocumentWidgetManager implements IDisposable {
factory: DocumentRegistry.WidgetFactory,
context: DocumentRegistry.Context
): IDocumentWidget {
- let widget = factory.createNew(context);
+ const widget = factory.createNew(context);
this._initializeWidget(widget, factory, context);
return widget;
}
@@ -95,7 +95,7 @@ export class DocumentWidgetManager implements IDisposable {
) {
Private.factoryProperty.set(widget, factory);
// Handle widget extensions.
- let disposables = new DisposableSet();
+ const disposables = new DisposableSet();
each(this._registry.widgetExtensions(factory.name), extender => {
disposables.add(extender.createNew(widget, context));
});
@@ -122,7 +122,7 @@ export class DocumentWidgetManager implements IDisposable {
context: DocumentRegistry.Context,
widget: IDocumentWidget
): void {
- let widgets = Private.widgetsProperty.get(context);
+ const widgets = Private.widgetsProperty.get(context);
widgets.push(widget);
MessageLoop.installMessageHook(widget, this);
widget.addClass(DOCUMENT_CLASS);
@@ -146,12 +146,12 @@ export class DocumentWidgetManager implements IDisposable {
context: DocumentRegistry.Context,
widgetName: string
): IDocumentWidget | undefined {
- let widgets = Private.widgetsProperty.get(context);
+ const widgets = Private.widgetsProperty.get(context);
if (!widgets) {
return undefined;
}
return find(widgets, widget => {
- let factory = Private.factoryProperty.get(widget);
+ const factory = Private.factoryProperty.get(widget);
if (!factory) {
return false;
}
@@ -182,15 +182,15 @@ export class DocumentWidgetManager implements IDisposable {
* if the source widget is not managed by this manager.
*/
cloneWidget(widget: Widget): IDocumentWidget | undefined {
- let context = Private.contextProperty.get(widget);
+ const context = Private.contextProperty.get(widget);
if (!context) {
return undefined;
}
- let factory = Private.factoryProperty.get(widget);
+ const factory = Private.factoryProperty.get(widget);
if (!factory) {
return undefined;
}
- let newWidget = factory.createNew(context, widget as IDocumentWidget);
+ const newWidget = factory.createNew(context, widget as IDocumentWidget);
this._initializeWidget(newWidget, factory, context);
return newWidget;
}
@@ -201,7 +201,7 @@ export class DocumentWidgetManager implements IDisposable {
* @param context - The document context object.
*/
closeWidgets(context: DocumentRegistry.Context): Promise {
- let widgets = Private.widgetsProperty.get(context);
+ const widgets = Private.widgetsProperty.get(context);
return Promise.all(
toArray(map(widgets, widget => this.onClose(widget)))
).then(() => undefined);
@@ -214,7 +214,7 @@ export class DocumentWidgetManager implements IDisposable {
* @param context - The document context object.
*/
deleteWidgets(context: DocumentRegistry.Context): Promise {
- let widgets = Private.widgetsProperty.get(context);
+ const widgets = Private.widgetsProperty.get(context);
return Promise.all(
toArray(map(widgets, widget => this.onDelete(widget)))
).then(() => undefined);
@@ -236,7 +236,7 @@ export class DocumentWidgetManager implements IDisposable {
void this.onClose(handler as Widget);
return false;
case 'activate-request':
- let context = this.contextForWidget(handler as Widget);
+ const context = this.contextForWidget(handler as Widget);
if (context) {
this._activateRequested.emit(context.path);
}
@@ -253,11 +253,11 @@ export class DocumentWidgetManager implements IDisposable {
* @param widget - The target widget.
*/
protected async setCaption(widget: Widget): Promise {
- let context = Private.contextProperty.get(widget);
+ const context = Private.contextProperty.get(widget);
if (!context) {
return;
}
- let model = context.contentsModel;
+ const model = context.contentsModel;
if (!model) {
widget.title.caption = '';
return;
@@ -268,8 +268,8 @@ export class DocumentWidgetManager implements IDisposable {
if (widget.isDisposed) {
return;
}
- let last = checkpoints[checkpoints.length - 1];
- let checkpoint = last ? Time.format(last.last_modified) : 'None';
+ const last = checkpoints[checkpoints.length - 1];
+ const checkpoint = last ? Time.format(last.last_modified) : 'None';
let caption = `Name: ${model!.name}\nPath: ${model!.path}\n`;
if (context!.model.readOnly) {
caption += 'Read-only';
@@ -322,7 +322,7 @@ export class DocumentWidgetManager implements IDisposable {
*/
private _maybeClose(widget: Widget): Promise {
// Bail if the model is not dirty or other widgets are using the model.)
- let context = Private.contextProperty.get(widget);
+ const context = Private.contextProperty.get(widget);
if (!context) {
return Promise.resolve(true);
}
@@ -333,22 +333,22 @@ export class DocumentWidgetManager implements IDisposable {
// Filter by whether the factories are read only.
widgets = toArray(
filter(widgets, widget => {
- let factory = Private.factoryProperty.get(widget);
+ const factory = Private.factoryProperty.get(widget);
if (!factory) {
return false;
}
return factory.readOnly === false;
})
);
- let factory = Private.factoryProperty.get(widget);
+ const factory = Private.factoryProperty.get(widget);
if (!factory) {
return Promise.resolve(true);
}
- let model = context.model;
+ const model = context.model;
if (!model.dirty || widgets.length > 1 || factory.readOnly) {
return Promise.resolve(true);
}
- let fileName = widget.title.label;
+ const fileName = widget.title.label;
return showDialog({
title: 'Close without saving?',
body: `File "${fileName}" has unsaved changes, close without saving?`,
@@ -362,11 +362,11 @@ export class DocumentWidgetManager implements IDisposable {
* Handle the disposal of a widget.
*/
private _widgetDisposed(widget: Widget): void {
- let context = Private.contextProperty.get(widget);
+ const context = Private.contextProperty.get(widget);
if (!context) {
return;
}
- let widgets = Private.widgetsProperty.get(context);
+ const widgets = Private.widgetsProperty.get(context);
if (!widgets) {
return;
}
@@ -382,7 +382,7 @@ export class DocumentWidgetManager implements IDisposable {
* Handle the disposal of a widget.
*/
private _onWidgetDisposed(widget: Widget): void {
- let disposables = Private.disposablesProperty.get(widget);
+ const disposables = Private.disposablesProperty.get(widget);
disposables.dispose();
}
@@ -390,7 +390,7 @@ export class DocumentWidgetManager implements IDisposable {
* Handle a file changed signal for a context.
*/
private _onFileChanged(context: DocumentRegistry.Context): void {
- let widgets = Private.widgetsProperty.get(context);
+ const widgets = Private.widgetsProperty.get(context);
each(widgets, widget => {
void this.setCaption(widget);
});
@@ -400,7 +400,7 @@ export class DocumentWidgetManager implements IDisposable {
* Handle a path changed signal for a context.
*/
private _onPathChanged(context: DocumentRegistry.Context): void {
- let widgets = Private.widgetsProperty.get(context);
+ const widgets = Private.widgetsProperty.get(context);
each(widgets, widget => {
void this.setCaption(widget);
});
diff --git a/packages/docregistry/src/context.ts b/packages/docregistry/src/context.ts
index ec4005755089..bd687b899bce 100644
--- a/packages/docregistry/src/context.ts
+++ b/packages/docregistry/src/context.ts
@@ -45,15 +45,15 @@ export class Context
* Construct a new document context.
*/
constructor(options: Context.IOptions) {
- let manager = (this._manager = options.manager);
+ const manager = (this._manager = options.manager);
this._factory = options.factory;
this._dialogs = options.sessionDialogs || sessionContextDialogs;
this._opener = options.opener || Private.noOp;
this._path = this._manager.contents.normalize(options.path);
const localPath = this._manager.contents.localPath(this._path);
- let lang = this._factory.preferredLanguage(PathExt.basename(localPath));
+ const lang = this._factory.preferredLanguage(PathExt.basename(localPath));
- let dbFactory = options.modelDBFactory;
+ const dbFactory = options.modelDBFactory;
if (dbFactory) {
const localPath = manager.contents.localPath(this._path);
this._modelDB = dbFactory.createNew(localPath);
@@ -66,7 +66,7 @@ export class Context
return this._populatedPromise.promise;
});
- let ext = PathExt.extname(this._path);
+ const ext = PathExt.extname(this._path);
this.sessionContext = new SessionContext({
sessionManager: manager.sessions,
specsManager: manager.kernelspecs,
@@ -286,7 +286,7 @@ export class Context
*/
async download(): Promise {
const url = await this._manager.contents.getDownloadUrl(this._path);
- let element = document.createElement('a');
+ const element = document.createElement('a');
element.href = url;
element.download = '';
document.body.appendChild(element);
@@ -308,7 +308,7 @@ export class Context
* Create a checkpoint for the file.
*/
createCheckpoint(): Promise {
- let contents = this._manager.contents;
+ const contents = this._manager.contents;
return this._manager.ready.then(() => {
return contents.createCheckpoint(this._path);
});
@@ -318,7 +318,7 @@ export class Context
* Delete a checkpoint for the file.
*/
deleteCheckpoint(checkpointId: string): Promise {
- let contents = this._manager.contents;
+ const contents = this._manager.contents;
return this._manager.ready.then(() => {
return contents.deleteCheckpoint(this._path, checkpointId);
});
@@ -328,8 +328,8 @@ export class Context
* Restore the file to a known checkpoint state.
*/
restoreCheckpoint(checkpointId?: string): Promise {
- let contents = this._manager.contents;
- let path = this._path;
+ const contents = this._manager.contents;
+ const path = this._path;
return this._manager.ready.then(() => {
if (checkpointId) {
return contents.restoreCheckpoint(path, checkpointId);
@@ -348,7 +348,7 @@ export class Context
* List available checkpoints for a file.
*/
listCheckpoints(): Promise {
- let contents = this._manager.contents;
+ const contents = this._manager.contents;
return this._manager.ready.then(() => {
return contents.listCheckpoints(this._path);
});
@@ -371,7 +371,7 @@ export class Context
widget: Widget,
options: DocumentRegistry.IOpenOptions = {}
): IDisposable {
- let opener = this._opener;
+ const opener = this._opener;
if (opener) {
opener(widget, options);
}
@@ -428,7 +428,7 @@ export class Context
if (type !== 'path') {
return;
}
- let path = this.sessionContext.session!.path;
+ const path = this.sessionContext.session!.path;
if (path !== this._path) {
this._path = path;
this._pathChanged.emit(path);
@@ -439,7 +439,7 @@ export class Context
* Update our contents model, without the content.
*/
private _updateContentsModel(model: Contents.IModel): void {
- let newModel: Contents.IModel = {
+ const newModel: Contents.IModel = {
path: model.path,
name: model.name,
type: model.type,
@@ -450,7 +450,7 @@ export class Context
mimetype: model.mimetype,
format: model.format
};
- let mod = this._contentsModel ? this._contentsModel.last_modified : null;
+ const mod = this._contentsModel ? this._contentsModel.last_modified : null;
this._contentsModel = newModel;
if (!mod || newModel.last_modified !== mod) {
this._fileChanged.emit(newModel);
@@ -471,7 +471,7 @@ export class Context
return;
}
// Update the kernel preference.
- let name =
+ const name =
this._model.defaultKernelName ||
this.sessionContext.kernelPreference.name;
this.sessionContext.kernelPreference = {
@@ -495,7 +495,7 @@ export class Context
*/
private _save(): Promise {
this._saveState.emit('started');
- let model = this._model;
+ const model = this._model;
let content: PartialJSONValue;
if (this._factory.fileFormat === 'json') {
content = model.toJSON();
@@ -506,7 +506,7 @@ export class Context
}
}
- let options = {
+ const options = {
type: this._factory.contentType,
format: this._factory.fileFormat,
content
@@ -569,13 +569,13 @@ export class Context
* deserializing the content.
*/
private _revert(initializeModel: boolean = false): Promise {
- let opts: Contents.IFetchOptions = {
+ const opts: Contents.IFetchOptions = {
format: this._factory.fileFormat,
type: this._factory.contentType,
content: true
};
- let path = this._path;
- let model = this._model;
+ const path = this._path;
+ const model = this._model;
return this._manager.ready
.then(() => {
return this._manager.contents.get(path, opts);
@@ -584,7 +584,7 @@ export class Context
if (this.isDisposed) {
return;
}
- let dirty = false;
+ const dirty = false;
if (contents.format === 'json') {
model.fromJSON(contents.content);
if (initializeModel) {
@@ -629,9 +629,9 @@ export class Context
private _maybeSave(
options: Partial
): Promise {
- let path = this._path;
+ const path = this._path;
// Make sure the file has not changed on disk.
- let promise = this._manager.contents.get(path, { content: false });
+ const promise = this._manager.contents.get(path, { content: false });
return promise.then(
model => {
if (this.isDisposed) {
@@ -641,9 +641,9 @@ export class Context
// (our last save)
// In some cases the filesystem reports an inconsistent time,
// so we allow 0.5 seconds difference before complaining.
- let modified = this.contentsModel?.last_modified;
- let tClient = modified ? new Date(modified) : new Date();
- let tDisk = new Date(model.last_modified);
+ const modified = this.contentsModel?.last_modified;
+ const tClient = modified ? new Date(modified) : new Date();
+ const tDisk = new Date(model.last_modified);
if (modified && tDisk.getTime() - tClient.getTime() > 500) {
// 500 ms
return this._timeConflict(tClient, model, options);
@@ -667,7 +667,7 @@ export class Context
title: string
): Promise {
// Check for a more specific error message.
- let error = { message: '' };
+ const error = { message: '' };
if (err instanceof ServerConnection.ResponseError) {
const text = await err.response.text();
let body = '';
@@ -719,19 +719,19 @@ export class Context
model: Contents.IModel,
options: Partial
): Promise {
- let tDisk = new Date(model.last_modified);
+ const tDisk = new Date(model.last_modified);
console.warn(
`Last saving performed ${tClient} ` +
`while the current file seems to have been saved ` +
`${tDisk}`
);
- let body =
+ const body =
`"${this.path}" has changed on disk since the last time it ` +
`was opened or saved. ` +
`Do you want to overwrite the file on disk with the version ` +
` open here, or load the version on disk (revert)?`;
- let revertBtn = Dialog.okButton({ label: 'Revert' });
- let overwriteBtn = Dialog.warnButton({ label: 'Overwrite' });
+ const revertBtn = Dialog.okButton({ label: 'Revert' });
+ const overwriteBtn = Dialog.warnButton({ label: 'Overwrite' });
return showDialog({
title: 'File Changed',
body,
@@ -756,8 +756,8 @@ export class Context
* Handle a time conflict.
*/
private _maybeOverWrite(path: string): Promise {
- let body = `"${path}" already exists. Do you want to replace it?`;
- let overwriteBtn = Dialog.warnButton({ label: 'Overwrite' });
+ const body = `"${path}" already exists. Do you want to replace it?`;
+ const overwriteBtn = Dialog.warnButton({ label: 'Overwrite' });
return showDialog({
title: 'File Overwrite?',
body,
@@ -872,7 +872,7 @@ namespace Private {
* Get a new file path from the user.
*/
export function getSavePath(path: string): Promise {
- let saveBtn = Dialog.okButton({ label: 'Save' });
+ const saveBtn = Dialog.okButton({ label: 'Save' });
return showDialog({
title: 'Save File As..',
body: new SaveWidget(path),
@@ -915,7 +915,7 @@ namespace Private {
* Create the node for a save widget.
*/
function createSaveNode(path: string): HTMLElement {
- let input = document.createElement('input');
+ const input = document.createElement('input');
input.value = path;
return input;
}
diff --git a/packages/docregistry/src/default.ts b/packages/docregistry/src/default.ts
index 503c80a526b2..35650ba47380 100644
--- a/packages/docregistry/src/default.ts
+++ b/packages/docregistry/src/default.ts
@@ -59,7 +59,7 @@ export class DocumentModel extends CodeEditor.Model
if (newValue === this._dirty) {
return;
}
- let oldValue = this._dirty;
+ const oldValue = this._dirty;
this._dirty = newValue;
this.triggerStateChange({ name: 'dirty', oldValue, newValue });
}
@@ -74,7 +74,7 @@ export class DocumentModel extends CodeEditor.Model
if (newValue === this._readOnly) {
return;
}
- let oldValue = this._readOnly;
+ const oldValue = this._readOnly;
this._readOnly = newValue;
this.triggerStateChange({ name: 'readOnly', oldValue, newValue });
}
@@ -227,7 +227,7 @@ export class TextModelFactory implements DocumentRegistry.CodeModelFactory {
* Get the preferred kernel language given a file path.
*/
preferredLanguage(path: string): string {
- let mode = Mode.findByFileName(path);
+ const mode = Mode.findByFileName(path);
return mode && mode.mode;
}
diff --git a/packages/docregistry/src/mimedocument.ts b/packages/docregistry/src/mimedocument.ts
index 4a828c0390e1..b39965b6f95a 100644
--- a/packages/docregistry/src/mimedocument.ts
+++ b/packages/docregistry/src/mimedocument.ts
@@ -141,15 +141,15 @@ export class MimeContent extends Widget {
// Set up for this rendering pass.
this._renderRequested = false;
- let context = this._context;
- let model = context.model;
- let data: PartialJSONObject = {};
+ const context = this._context;
+ const model = context.model;
+ const data: PartialJSONObject = {};
if (this._dataType === 'string') {
data[this.mimeType] = model.toString();
} else {
data[this.mimeType] = model.toJSON();
}
- let mimeModel = new MimeModel({
+ const mimeModel = new MimeModel({
data,
callback: this._changeCallback,
metadata: { fragment: this._fragment }
@@ -183,7 +183,7 @@ export class MimeContent extends Widget {
if (!options.data || !options.data[this.mimeType]) {
return;
}
- let data = options.data[this.mimeType];
+ const data = options.data[this.mimeType];
if (typeof data === 'string') {
if (data !== this._context.model.toString()) {
this._context.model.fromString(data);
diff --git a/packages/docregistry/src/registry.ts b/packages/docregistry/src/registry.ts
index e53acb0f9793..1fb485b2dc42 100644
--- a/packages/docregistry/src/registry.ts
+++ b/packages/docregistry/src/registry.ts
@@ -58,15 +58,15 @@ export class DocumentRegistry implements IDisposable {
* Construct a new document registry.
*/
constructor(options: DocumentRegistry.IOptions = {}) {
- let factory = options.textModelFactory;
+ const factory = options.textModelFactory;
if (factory && factory.name !== 'text') {
throw new Error('Text model factory must have the name `text`');
}
this._modelFactories['text'] = factory || new TextModelFactory();
- let fts = options.initialFileTypes || DocumentRegistry.defaultFileTypes;
+ const fts = options.initialFileTypes || DocumentRegistry.defaultFileTypes;
fts.forEach(ft => {
- let value: DocumentRegistry.IFileType = {
+ const value: DocumentRegistry.IFileType = {
...DocumentRegistry.fileTypeDefaults,
...ft
};
@@ -96,13 +96,13 @@ export class DocumentRegistry implements IDisposable {
return;
}
this._isDisposed = true;
- for (let modelName in this._modelFactories) {
+ for (const modelName in this._modelFactories) {
this._modelFactories[modelName].dispose();
}
- for (let widgetName in this._widgetFactories) {
+ for (const widgetName in this._widgetFactories) {
this._widgetFactories[widgetName].dispose();
}
- for (let widgetName in this._extenders) {
+ for (const widgetName in this._extenders) {
this._extenders[widgetName].length = 0;
}
@@ -127,7 +127,7 @@ export class DocumentRegistry implements IDisposable {
* The factory cannot be named an empty string or the string `'default'`.
*/
addWidgetFactory(factory: DocumentRegistry.WidgetFactory): IDisposable {
- let name = factory.name.toLowerCase();
+ const name = factory.name.toLowerCase();
if (!name || name === 'default') {
throw Error('Invalid factory name');
}
@@ -136,7 +136,7 @@ export class DocumentRegistry implements IDisposable {
return new DisposableDelegate(Private.noOp);
}
this._widgetFactories[name] = factory;
- for (let ft of factory.defaultFor || []) {
+ for (const ft of factory.defaultFor || []) {
if (factory.fileTypes.indexOf(ft) === -1) {
continue;
}
@@ -146,14 +146,14 @@ export class DocumentRegistry implements IDisposable {
this._defaultWidgetFactories[ft] = name;
}
}
- for (let ft of factory.defaultRendered || []) {
+ for (const ft of factory.defaultRendered || []) {
if (factory.fileTypes.indexOf(ft) === -1) {
continue;
}
this._defaultRenderedWidgetFactories[ft] = name;
}
// For convenience, store a mapping of file type name -> name
- for (let ft of factory.fileTypes) {
+ for (const ft of factory.fileTypes) {
if (!this._widgetFactoriesForFileType[ft]) {
this._widgetFactoriesForFileType[ft] = [];
}
@@ -169,23 +169,23 @@ export class DocumentRegistry implements IDisposable {
if (this._defaultWidgetFactory === name) {
this._defaultWidgetFactory = '';
}
- for (let ext of Object.keys(this._defaultWidgetFactories)) {
+ for (const ext of Object.keys(this._defaultWidgetFactories)) {
if (this._defaultWidgetFactories[ext] === name) {
delete this._defaultWidgetFactories[ext];
}
}
- for (let ext of Object.keys(this._defaultRenderedWidgetFactories)) {
+ for (const ext of Object.keys(this._defaultRenderedWidgetFactories)) {
if (this._defaultRenderedWidgetFactories[ext] === name) {
delete this._defaultRenderedWidgetFactories[ext];
}
}
- for (let ext of Object.keys(this._widgetFactoriesForFileType)) {
+ for (const ext of Object.keys(this._widgetFactoriesForFileType)) {
ArrayExt.removeFirstOf(this._widgetFactoriesForFileType[ext], name);
if (this._widgetFactoriesForFileType[ext].length === 0) {
delete this._widgetFactoriesForFileType[ext];
}
}
- for (let ext of Object.keys(this._defaultWidgetFactoryOverrides)) {
+ for (const ext of Object.keys(this._defaultWidgetFactoryOverrides)) {
if (this._defaultWidgetFactoryOverrides[ext] === name) {
delete this._defaultWidgetFactoryOverrides[ext];
}
@@ -211,7 +211,7 @@ export class DocumentRegistry implements IDisposable {
* and this will be a no-op.
*/
addModelFactory(factory: DocumentRegistry.ModelFactory): IDisposable {
- let name = factory.name.toLowerCase();
+ const name = factory.name.toLowerCase();
if (this._modelFactories[name]) {
console.warn(`Duplicate registered factory ${name}`);
return new DisposableDelegate(Private.noOp);
@@ -253,8 +253,8 @@ export class DocumentRegistry implements IDisposable {
if (!(widgetName in this._extenders)) {
this._extenders[widgetName] = [];
}
- let extenders = this._extenders[widgetName];
- let index = ArrayExt.firstIndexOf(extenders, extension);
+ const extenders = this._extenders[widgetName];
+ const index = ArrayExt.firstIndexOf(extenders, extension);
if (index !== -1) {
console.warn(`Duplicate registered extension for ${widgetName}`);
return new DisposableDelegate(Private.noOp);
@@ -286,7 +286,7 @@ export class DocumentRegistry implements IDisposable {
* These are used to populate the "Create New" dialog.
*/
addFileType(fileType: Partial): IDisposable {
- let value: DocumentRegistry.IFileType = {
+ const value: DocumentRegistry.IFileType = {
...DocumentRegistry.fileTypeDefaults,
...fileType,
// fall back to fileIcon if needed
@@ -328,10 +328,10 @@ export class DocumentRegistry implements IDisposable {
* - all other global factories
*/
preferredWidgetFactories(path: string): DocumentRegistry.WidgetFactory[] {
- let factories = new Set();
+ const factories = new Set();
// Get the ordered matching file types.
- let fts = this.getFileTypesForPath(PathExt.basename(path));
+ const fts = this.getFileTypesForPath(PathExt.basename(path));
// Start with any user overrides for the defaults.
fts.forEach(ft => {
@@ -377,13 +377,13 @@ export class DocumentRegistry implements IDisposable {
// Construct the return list, checking to make sure the corresponding
// model factories are registered.
- let factoryList: DocumentRegistry.WidgetFactory[] = [];
+ const factoryList: DocumentRegistry.WidgetFactory[] = [];
factories.forEach(name => {
- let factory = this._widgetFactories[name];
+ const factory = this._widgetFactories[name];
if (!factory) {
return;
}
- let modelName = factory.modelName || 'text';
+ const modelName = factory.modelName || 'text';
if (modelName in this._modelFactories) {
factoryList.push(factory);
}
@@ -407,11 +407,11 @@ export class DocumentRegistry implements IDisposable {
*/
defaultRenderedWidgetFactory(path: string): DocumentRegistry.WidgetFactory {
// Get the matching file types.
- let fts = this.getFileTypesForPath(PathExt.basename(path));
+ const fts = this.getFileTypesForPath(PathExt.basename(path));
let factory: DocumentRegistry.WidgetFactory | undefined = undefined;
// Find if a there is a default rendered factory for this type.
- for (let ft of fts) {
+ for (const ft of fts) {
if (ft.name in this._defaultRenderedWidgetFactories) {
factory = this._widgetFactories[
this._defaultRenderedWidgetFactories[ft.name]
@@ -583,17 +583,19 @@ export class DocumentRegistry implements IDisposable {
kernel?: Partial
): ISessionContext.IKernelPreference | undefined {
widgetName = widgetName.toLowerCase();
- let widgetFactory = this._widgetFactories[widgetName];
+ const widgetFactory = this._widgetFactories[widgetName];
if (!widgetFactory) {
return void 0;
}
- let modelFactory = this.getModelFactory(widgetFactory.modelName || 'text');
+ const modelFactory = this.getModelFactory(
+ widgetFactory.modelName || 'text'
+ );
if (!modelFactory) {
return void 0;
}
- let language = modelFactory.preferredLanguage(PathExt.basename(path));
- let name = kernel && kernel.name;
- let id = kernel && kernel.id;
+ const language = modelFactory.preferredLanguage(PathExt.basename(path));
+ const name = kernel && kernel.name;
+ const id = kernel && kernel.id;
return {
id,
name,
@@ -628,8 +630,8 @@ export class DocumentRegistry implements IDisposable {
default:
// Find the best matching extension.
if (model.name || model.path) {
- let name = model.name || PathExt.basename(model.path!);
- let fts = this.getFileTypesForPath(name);
+ const name = model.name || PathExt.basename(model.path!);
+ const fts = this.getFileTypesForPath(name);
if (fts.length > 0) {
return fts[0];
}
@@ -646,8 +648,8 @@ export class DocumentRegistry implements IDisposable {
* @returns An ordered list of matching file types.
*/
getFileTypesForPath(path: string): DocumentRegistry.IFileType[] {
- let fts: DocumentRegistry.IFileType[] = [];
- let name = PathExt.basename(path);
+ const fts: DocumentRegistry.IFileType[] = [];
+ const name = PathExt.basename(path);
// Look for a pattern match first.
let ft = find(this._fileTypes, ft => {
@@ -1428,9 +1430,9 @@ namespace Private {
* Dotted filenames (e.g. `".table.json"` are allowed).
*/
export function extname(path: string): string {
- let parts = PathExt.basename(path).split('.');
+ const parts = PathExt.basename(path).split('.');
parts.shift();
- let ext = '.' + parts.join('.');
+ const ext = '.' + parts.join('.');
return ext.toLowerCase();
}
/**
diff --git a/packages/documentsearch/src/providers/codemirrorsearchprovider.ts b/packages/documentsearch/src/providers/codemirrorsearchprovider.ts
index 7887be7a1290..1bdadcd6c1fb 100644
--- a/packages/documentsearch/src/providers/codemirrorsearchprovider.ts
+++ b/packages/documentsearch/src/providers/codemirrorsearchprovider.ts
@@ -348,7 +348,7 @@ export class CodeMirrorSearchProvider
const end = CodeMirror.Pos(this._cm.doc.lastLine());
const content = this._cm.doc.getRange(start, end);
const lines = content.split('\n');
- let totalMatchIndex = 0;
+ const totalMatchIndex = 0;
lines.forEach((line, lineNumber) => {
query.lastIndex = 0;
let match = query.exec(line);
diff --git a/packages/documentsearch/src/providers/genericsearchprovider.ts b/packages/documentsearch/src/providers/genericsearchprovider.ts
index a176c8e41a56..89982db92eae 100644
--- a/packages/documentsearch/src/providers/genericsearchprovider.ts
+++ b/packages/documentsearch/src/providers/genericsearchprovider.ts
@@ -85,7 +85,7 @@ export class GenericSearchProvider implements ISearchProvider {
searchTarget: Widget,
filters = {}
): Promise {
- const that = this;
+ const that = this; // eslint-disable-line
// No point in removing overlay in the middle of the search
await this.endQuery(false);
@@ -152,7 +152,7 @@ export class GenericSearchProvider implements ISearchProvider {
const originalLength = node!.textContent!.length; // Node length will change below
let lastNodeAdded = null;
// Go backwards as index may change if we go forwards
- let newMatches = [];
+ const newMatches = [];
for (let idx = subsections.length - 1; idx >= 0; --idx) {
const { start, end, text } = subsections[idx];
// TODO: support tspan for svg when svg support is added
diff --git a/packages/documentsearch/src/providers/notebooksearchprovider.ts b/packages/documentsearch/src/providers/notebooksearchprovider.ts
index fe2e0144a32b..909ead447f7a 100644
--- a/packages/documentsearch/src/providers/notebooksearchprovider.ts
+++ b/packages/documentsearch/src/providers/notebooksearchprovider.ts
@@ -72,7 +72,7 @@ export class NotebookSearchProvider implements ISearchProvider {
const allMatches: ISearchMatch[] = [];
// For each cell, create a search provider and collect the matches
- for (let cell of cells) {
+ for (const cell of cells) {
const cmEditor = cell.editor as CodeMirrorEditor;
const cmSearchProvider = new CodeMirrorSearchProvider();
cmSearchProvider.isSubProvider = true;
@@ -131,7 +131,7 @@ export class NotebookSearchProvider implements ISearchProvider {
if (cell instanceof CodeCell && this._filters.output) {
const outputProivder = new GenericSearchProvider();
outputProivder.isSubProvider = true;
- let matchesFromOutput = await outputProivder.startQuery(
+ const matchesFromOutput = await outputProivder.startQuery(
query,
cell.outputArea
);
@@ -172,7 +172,7 @@ export class NotebookSearchProvider implements ISearchProvider {
private _refreshCellsEditorsInBackground(cells: Cell[], n: number = 5) {
let i = 0;
- let refreshNextNCells = () => {
+ const refreshNextNCells = () => {
for (let stop = i + n; i < stop && i < cells.length; i++) {
cells[i].editor.refresh();
}
@@ -327,7 +327,7 @@ export class NotebookSearchProvider implements ISearchProvider {
*/
async replaceAllMatches(newText: string): Promise {
let replaceOccurred = false;
- for (let index in this._searchProviders) {
+ for (const index in this._searchProviders) {
const { provider } = this._searchProviders[index];
const singleReplaceOccurred = await provider.replaceAllMatches(newText);
replaceOccurred = singleReplaceOccurred ? true : replaceOccurred;
diff --git a/packages/documentsearch/src/searchoverlay.tsx b/packages/documentsearch/src/searchoverlay.tsx
index 825195f766c7..4447e4854f62 100644
--- a/packages/documentsearch/src/searchoverlay.tsx
+++ b/packages/documentsearch/src/searchoverlay.tsx
@@ -75,6 +75,7 @@ interface IReplaceEntryProps {
class SearchEntry extends React.Component {
constructor(props: ISearchEntryProps) {
super(props);
+ this.searchInputRef = React.createRef();
}
/**
@@ -85,7 +86,7 @@ class SearchEntry extends React.Component {
// This makes typing in the box starts a new query (the common case),
// while arrow keys can be used to move cursor in preparation for
// modifying previous query.
- (this.refs.searchInputNode as HTMLInputElement).select();
+ this.searchInputRef.current?.select();
}
componentDidUpdate() {
@@ -119,7 +120,7 @@ class SearchEntry extends React.Component {
tabIndex={2}
onFocus={e => this.props.onInputFocus()}
onBlur={e => this.props.onInputBlur()}
- ref="searchInputNode"
+ ref={this.searchInputRef}
/>
{
);
}
+
+ private searchInputRef: React.RefObject;
}
class ReplaceEntry extends React.Component {
constructor(props: any) {
super(props);
+ this.replaceInputRef = React.createRef();
}
render() {
@@ -158,7 +162,7 @@ class ReplaceEntry extends React.Component {
onKeyDown={e => this.props.onReplaceKeydown(e)}
onChange={e => this.props.onChange(e)}
tabIndex={3}
- ref="replaceInputNode"
+ ref={this.replaceInputRef}
/>
{
);
}
+
+ private replaceInputRef: React.RefObject;
}
interface IUpDownProps {
@@ -324,7 +330,7 @@ class SearchOverlay extends React.Component<
constructor(props: ISearchOverlayProps) {
super(props);
this.state = props.overlayState;
-
+ this.replaceEntryRef = React.createRef();
this._toggleSearchOutput = this._toggleSearchOutput.bind(this);
}
@@ -532,7 +538,7 @@ class SearchOverlay extends React.Component<
this.props.onReplaceAll(this.state.replaceText)
}
replaceText={this.state.replaceText}
- ref="replaceEntry"
+ ref={this.replaceEntryRef}
/>
{filterToggle}
@@ -552,6 +558,8 @@ class SearchOverlay extends React.Component<
];
}
+ private replaceEntryRef: React.RefObject;
+
private _debouncedStartSearch = new Debouncer(() => {
this._executeSearch(true, this.state.searchText);
}, 500);
diff --git a/packages/documentsearch/src/searchproviderregistry.ts b/packages/documentsearch/src/searchproviderregistry.ts
index 73a3bb4887db..11c561cc435b 100644
--- a/packages/documentsearch/src/searchproviderregistry.ts
+++ b/packages/documentsearch/src/searchproviderregistry.ts
@@ -53,7 +53,7 @@ export class SearchProviderRegistry implements ISearchProviderRegistry {
): ISearchProvider | undefined {
// iterate through all providers and ask each one if it can search on the
// widget.
- for (let P of providerMap.values()) {
+ for (const P of providerMap.values()) {
if (P.canSearchOn(widget)) {
return new P();
}
diff --git a/packages/extensionmanager/src/companions.tsx b/packages/extensionmanager/src/companions.tsx
index a60731175533..3ddb700c0263 100644
--- a/packages/extensionmanager/src/companions.tsx
+++ b/packages/extensionmanager/src/companions.tsx
@@ -103,7 +103,7 @@ const managerCommand: { [key: string]: (name: string) => string } = {
};
function getInstallCommands(info: IInstallInfo) {
- let commands = Array();
+ const commands = Array();
for (const manager of info.managers) {
const name = info.overrides?.[manager]?.name ?? info.base.name;
if (!name) {
@@ -128,7 +128,7 @@ export function presentCompanions(
kernelCompanions: KernelCompanion[],
serverCompanion: IInstallInfo | undefined
): Promise {
- let entries = [];
+ const entries = [];
if (serverCompanion) {
entries.push(
@@ -137,7 +137,7 @@ export function presentCompanions(
one of the following commands:
{getInstallCommands(serverCompanion).map(command => {
return (
-
+
{command}
);
@@ -152,7 +152,7 @@ export function presentCompanions(
kernel.
);
- for (let [index, entry] of kernelCompanions.entries()) {
+ for (const [index, entry] of kernelCompanions.entries()) {
entries.push(
The package
@@ -160,8 +160,8 @@ export function presentCompanions(
following kernels:
);
- let kernelEntries = [];
- for (let [index, kernel] of entry.kernels.entries()) {
+ const kernelEntries = [];
+ for (const [index, kernel] of entry.kernels.entries()) {
kernelEntries.push(
{kernel.display_name}
@@ -176,7 +176,7 @@ export function presentCompanions(
one of the following commands:
{getInstallCommands(entry.kernelInfo).map(command => {
return (
-
+
{command}
);
@@ -185,7 +185,7 @@ export function presentCompanions(
);
}
}
- let body = (
+ const body = (
{entries}
diff --git a/packages/extensionmanager/src/dialog.tsx b/packages/extensionmanager/src/dialog.tsx
index ff65d1ea6796..727653e217bb 100644
--- a/packages/extensionmanager/src/dialog.tsx
+++ b/packages/extensionmanager/src/dialog.tsx
@@ -12,7 +12,7 @@ import * as React from 'react';
* @param errorMessage Any error message giving details about the failure.
*/
export function reportInstallError(name: string, errorMessage?: string) {
- let entries = [];
+ const entries = [];
entries.push(
An error occurred installing {name}
.
@@ -28,7 +28,7 @@ export function reportInstallError(name: string, errorMessage?: string) {
{errorMessage.trim()}
);
}
- let body =
{entries}
;
+ const body =
{entries}
;
void showDialog({
title: 'Extension Installation Error',
body,
diff --git a/packages/extensionmanager/src/listings.ts b/packages/extensionmanager/src/listings.ts
index 2bafcf758e48..2a58a4dc1d43 100644
--- a/packages/extensionmanager/src/listings.ts
+++ b/packages/extensionmanager/src/listings.ts
@@ -7,7 +7,7 @@ import { URLExt } from '@jupyterlab/coreutils';
import { ServerConnection } from '@jupyterlab/services';
-/***
+/** *
* Information about a listed entry.
*/
export interface IListEntry {
diff --git a/packages/extensionmanager/src/model.ts b/packages/extensionmanager/src/model.ts
index a6f2e6ab270d..2b3c8f1336c3 100644
--- a/packages/extensionmanager/src/model.ts
+++ b/packages/extensionmanager/src/model.ts
@@ -387,12 +387,12 @@ export class ListModel extends VDomModel {
if (!data || !data.jupyterlab || !data.jupyterlab.discovery) {
return true;
}
- let discovery = data.jupyterlab.discovery;
- let kernelCompanions: KernelCompanion[] = [];
+ const discovery = data.jupyterlab.discovery;
+ const kernelCompanions: KernelCompanion[] = [];
if (discovery.kernel) {
// match specs
- for (let kernelInfo of discovery.kernel) {
- let matches = Private.matchSpecs(
+ for (const kernelInfo of discovery.kernel) {
+ const matches = Private.matchSpecs(
kernelInfo,
this.serviceManager.kernelspecs.specs
);
@@ -410,7 +410,7 @@ export class ListModel extends VDomModel {
* Trigger a build check to incorporate actions taken.
*/
triggerBuildCheck(): void {
- let builder = this.serviceManager.builder;
+ const builder = this.serviceManager.builder;
if (builder.isAvailable && !this.promptBuild) {
const completed = builder.getStatus().then(response => {
if (response.status === 'building') {
@@ -469,12 +469,12 @@ export class ListModel extends VDomModel {
protected async translateSearchResult(
res: Promise
): Promise<{ [key: string]: IEntry }> {
- let entries: { [key: string]: IEntry } = {};
+ const entries: { [key: string]: IEntry } = {};
this._totalBlacklistedFound = 0;
this._totalWhitelistedFound = 0;
this._totalEntries = 0;
- for (let obj of (await res).objects) {
- let pkg = obj.package;
+ for (const obj of (await res).objects) {
+ const pkg = obj.package;
if (pkg.keywords.indexOf('deprecated') >= 0) {
continue;
}
@@ -518,7 +518,7 @@ export class ListModel extends VDomModel {
): Promise<{ [key: string]: IEntry }> {
const promises = [];
const entries: { [key: string]: IEntry } = {};
- for (let pkg of await res) {
+ for (const pkg of await res) {
promises.push(
res.then(info => {
entries[pkg.name] = {
@@ -599,12 +599,12 @@ export class ListModel extends VDomModel {
}
// Start the search without waiting for it:
- let search = this.searcher.searchExtensions(
+ const search = this.searcher.searchExtensions(
this.query,
this.page,
this.pagination
);
- let searchMapPromise = this.translateSearchResult(search);
+ const searchMapPromise = this.translateSearchResult(search);
let searchMap: { [key: string]: IEntry };
try {
@@ -659,14 +659,14 @@ export class ListModel extends VDomModel {
const installedMap = await installedMapPromise;
// Map results to attributes:
- let installed: IEntry[] = [];
- for (let key of Object.keys(installedMap)) {
+ const installed: IEntry[] = [];
+ for (const key of Object.keys(installedMap)) {
installed.push(installedMap[key]);
}
this._installed = installed.sort(Private.comparator);
- let searchResult: IEntry[] = [];
- for (let key of Object.keys(searchMap)) {
+ const searchResult: IEntry[] = [];
+ for (const key of Object.keys(searchMap)) {
// Filter out installed entries from search results:
if (installedMap[key] === undefined) {
searchResult.push(searchMap[key]);
@@ -694,7 +694,7 @@ export class ListModel extends VDomModel {
EXTENSION_API_PATH,
this.serverConnectionSettings.baseUrl
);
- let request: RequestInit = {
+ const request: RequestInit = {
method: 'POST',
body: JSON.stringify({
cmd: action,
@@ -851,8 +851,8 @@ namespace Private {
return 0;
}
- let testA = isJupyterOrg(a.name);
- let testB = isJupyterOrg(b.name);
+ const testA = isJupyterOrg(a.name);
+ const testB = isJupyterOrg(b.name);
if (testA === testB) {
// Retain sort-order from API
@@ -877,7 +877,7 @@ namespace Private {
if (!specs) {
return [];
}
- let matches: KernelSpec.ISpecModel[] = [];
+ const matches: KernelSpec.ISpecModel[] = [];
let reLang: RegExp | null = null;
let reName: RegExp | null = null;
if (kernelInfo.kernel_spec.language) {
@@ -886,8 +886,8 @@ namespace Private {
if (kernelInfo.kernel_spec.display_name) {
reName = new RegExp(kernelInfo.kernel_spec.display_name);
}
- for (let key of Object.keys(specs.kernelspecs)) {
- let spec = specs.kernelspecs[key]!;
+ for (const key of Object.keys(specs.kernelspecs)) {
+ const spec = specs.kernelspecs[key]!;
let match = false;
if (reLang) {
match = reLang.test(spec.language);
diff --git a/packages/extensionmanager/src/npm.ts b/packages/extensionmanager/src/npm.ts
index fbc4f8ed8f81..42677e55b865 100644
--- a/packages/extensionmanager/src/npm.ts
+++ b/packages/extensionmanager/src/npm.ts
@@ -241,7 +241,7 @@ export class Searcher {
): Promise {
const uri = new URL('/-/v1/search', this.repoUri);
// Note: Spaces are encoded to '+' signs!
- let text = `${query} keywords:"jupyterlab-extension"`;
+ const text = `${query} keywords:"jupyterlab-extension"`;
uri.searchParams.append('text', text);
uri.searchParams.append('size', pageination.toString());
uri.searchParams.append('from', (pageination * page).toString());
diff --git a/packages/extensionmanager/src/widget.tsx b/packages/extensionmanager/src/widget.tsx
index 0cb7bb7b9f1d..c8268291f58d 100644
--- a/packages/extensionmanager/src/widget.tsx
+++ b/packages/extensionmanager/src/widget.tsx
@@ -76,7 +76,7 @@ export class SearchBar extends React.Component<
* Handler for search input changes.
*/
handleChange = (e: React.FormEvent) => {
- let target = e.target as HTMLInputElement;
+ const target = e.target as HTMLInputElement;
this.setState({
value: target.value
});
@@ -215,7 +215,7 @@ function ListEntry(props: ListEntry.IProperties): React.ReactElement {
@@ -347,7 +347,7 @@ export namespace ListEntry {
*/
export function ListView(props: ListView.IProperties): React.ReactElement
{
const entryViews = [];
- for (let entry of props.entries) {
+ for (const entry of props.entries) {
entryViews.push(
{
Read more in the JupyterLab documentation.
@@ -622,8 +623,8 @@ export class ExtensionView extends VDomRenderer {
];
}
- let pages = Math.ceil(model.totalEntries / model.pagination);
- let elements = [
+ const pages = Math.ceil(model.totalEntries / model.pagination);
+ const elements = [
{
} else {
// List installed and discovery sections
- let installedContent = [];
+ const installedContent = [];
if (model.installedError !== null) {
installedContent.push(
@@ -781,7 +782,7 @@ export class ExtensionView extends VDomRenderer {
);
- let searchContent = [];
+ const searchContent = [];
if (model.searchError !== null) {
searchContent.push(
@@ -925,7 +926,7 @@ export class ExtensionView extends VDomRenderer {
*/
protected onActivateRequest(msg: Message): void {
if (this.isAttached) {
- let input = this.inputNode;
+ const input = this.inputNode;
if (input) {
input.focus();
input.select();
@@ -937,7 +938,7 @@ export class ExtensionView extends VDomRenderer {
* Toggle the focused modifier based on the input node focus state.
*/
private _toggleFocused(): void {
- let focused = document.activeElement === this.inputNode;
+ const focused = document.activeElement === this.inputNode;
this.toggleClass('lm-mod-focused', focused);
}
}
diff --git a/packages/filebrowser-extension/src/index.ts b/packages/filebrowser-extension/src/index.ts
index e084987b27ac..ed8476104c70 100644
--- a/packages/filebrowser-extension/src/index.ts
+++ b/packages/filebrowser-extension/src/index.ts
@@ -249,7 +249,7 @@ async function activateFactory(
const widget = new FileBrowser({ id, model, restore });
// Add a launcher toolbar item.
- let launcher = new ToolbarButton({
+ const launcher = new ToolbarButton({
icon: addIcon,
onClick: () => {
return Private.createLauncher(commands, widget);
@@ -541,7 +541,7 @@ function addCommands(
return;
}
try {
- let trailingSlash = path !== '/' && path.endsWith('/');
+ const trailingSlash = path !== '/' && path.endsWith('/');
if (trailingSlash) {
// The normal contents service errors on paths ending in slash
path = path.slice(0, path.length - 1);
@@ -761,7 +761,7 @@ function addCommands(
return;
} else {
const areas: ILabShell.Area[] = ['left', 'right'];
- for (let area of areas) {
+ for (const area of areas) {
const it = labShell.widgets(area);
let widget = it.next();
while (widget) {
@@ -842,7 +842,7 @@ function addCommands(
// get the widget factories that could be used to open all of the items
// in the current filebrowser selection
- let factories = tracker.currentWidget
+ const factories = tracker.currentWidget
? OpenWithMenu._intersection(
map(tracker.currentWidget.selectedItems(), i => {
return OpenWithMenu._getFactories(i);
@@ -864,7 +864,7 @@ function addCommands(
}
static _getFactories(item: Contents.IModel): Array {
- let factories = registry
+ const factories = registry
.preferredWidgetFactories(item.path)
.map(f => f.name);
const notebookFactory = registry.getWidgetFactory('notebook')?.name;
@@ -881,14 +881,14 @@ function addCommands(
static _intersection(iter: IIterator>): Set | void {
// pop the first element of iter
- let first = iter.next();
+ const first = iter.next();
// first will be undefined if iter is empty
if (!first) {
return;
}
// "initialize" the intersection from first
- let isect = new Set(first);
+ const isect = new Set(first);
// reduce over the remaining elements of iter
return reduce(
iter,
@@ -1047,7 +1047,7 @@ namespace Private {
const driveName = browser.model.manager.services.contents.driveName(path);
if (driveName) {
- let browserForPath = tracker.find(
+ const browserForPath = tracker.find(
_path => _path.model.driveName === driveName
);
@@ -1081,7 +1081,7 @@ namespace Private {
const localPath = services.contents.localPath(path);
await services.ready;
- let item = await services.contents.get(path, { content: false });
+ const item = await services.contents.get(path, { content: false });
const { model } = browserForPath;
await model.restored;
if (item.type === 'directory') {
diff --git a/packages/filebrowser/src/crumbs.ts b/packages/filebrowser/src/crumbs.ts
index 7c070f3e4967..23a245928c82 100644
--- a/packages/filebrowser/src/crumbs.ts
+++ b/packages/filebrowser/src/crumbs.ts
@@ -108,7 +108,7 @@ export class BreadCrumbs extends Widget {
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
this.update();
- let node = this.node;
+ const node = this.node;
node.addEventListener('click', this);
node.addEventListener('lm-dragenter', this);
node.addEventListener('lm-dragleave', this);
@@ -121,7 +121,7 @@ export class BreadCrumbs extends Widget {
*/
protected onBeforeDetach(msg: Message): void {
super.onBeforeDetach(msg);
- let node = this.node;
+ const node = this.node;
node.removeEventListener('click', this);
node.removeEventListener('lm-dragenter', this);
node.removeEventListener('lm-dragleave', this);
@@ -155,7 +155,7 @@ export class BreadCrumbs extends Widget {
node.classList.contains(BREADCRUMB_ITEM_CLASS) ||
node.classList.contains(BREADCRUMB_HOME_CLASS)
) {
- let index = ArrayExt.findFirstIndex(
+ const index = ArrayExt.findFirstIndex(
this._crumbs,
value => value === node
);
@@ -177,7 +177,7 @@ export class BreadCrumbs extends Widget {
*/
private _evtDragEnter(event: IDragEvent): void {
if (event.mimeData.hasData(CONTENTS_MIME)) {
- let index = ArrayExt.findFirstIndex(this._crumbs, node =>
+ const index = ArrayExt.findFirstIndex(this._crumbs, node =>
ElementExt.hitTest(node, event.clientX, event.clientY)
);
if (index !== -1) {
@@ -196,7 +196,7 @@ export class BreadCrumbs extends Widget {
private _evtDragLeave(event: IDragEvent): void {
event.preventDefault();
event.stopPropagation();
- let dropTarget = DOMUtils.findElement(this.node, DROP_TARGET_CLASS);
+ const dropTarget = DOMUtils.findElement(this.node, DROP_TARGET_CLASS);
if (dropTarget) {
dropTarget.classList.remove(DROP_TARGET_CLASS);
}
@@ -209,11 +209,11 @@ export class BreadCrumbs extends Widget {
event.preventDefault();
event.stopPropagation();
event.dropAction = event.proposedAction;
- let dropTarget = DOMUtils.findElement(this.node, DROP_TARGET_CLASS);
+ const dropTarget = DOMUtils.findElement(this.node, DROP_TARGET_CLASS);
if (dropTarget) {
dropTarget.classList.remove(DROP_TARGET_CLASS);
}
- let index = ArrayExt.findFirstIndex(this._crumbs, node =>
+ const index = ArrayExt.findFirstIndex(this._crumbs, node =>
ElementExt.hitTest(node, event.clientX, event.clientY)
);
if (index !== -1) {
@@ -246,7 +246,10 @@ export class BreadCrumbs extends Widget {
}
// Get the path based on the target node.
- let index = ArrayExt.findFirstIndex(this._crumbs, node => node === target);
+ const index = ArrayExt.findFirstIndex(
+ this._crumbs,
+ node => node === target
+ );
if (index === -1) {
return;
}
@@ -256,12 +259,12 @@ export class BreadCrumbs extends Widget {
const manager = model.manager;
// Move all of the items.
- let promises: Promise[] = [];
- let oldPaths = event.mimeData.getData(CONTENTS_MIME) as string[];
- for (let oldPath of oldPaths) {
- let localOldPath = manager.services.contents.localPath(oldPath);
- let name = PathExt.basename(localOldPath);
- let newPath = PathExt.join(path, name);
+ const promises: Promise[] = [];
+ const oldPaths = event.mimeData.getData(CONTENTS_MIME) as string[];
+ for (const oldPath of oldPaths) {
+ const localOldPath = manager.services.contents.localPath(oldPath);
+ const name = PathExt.basename(localOldPath);
+ const newPath = PathExt.join(path, name);
promises.push(renameFile(manager, oldPath, newPath));
}
void Promise.all(promises).catch(err => {
@@ -311,19 +314,19 @@ namespace Private {
separators: ReadonlyArray,
path: string
) {
- let node = breadcrumbs[0].parentNode as HTMLElement;
+ const node = breadcrumbs[0].parentNode as HTMLElement;
// Remove all but the home node.
- let firstChild = node.firstChild as HTMLElement;
+ const firstChild = node.firstChild as HTMLElement;
while (firstChild && firstChild.nextSibling) {
node.removeChild(firstChild.nextSibling);
}
node.appendChild(separators[0]);
- let parts = path.split('/');
+ const parts = path.split('/');
if (parts.length > 2) {
node.appendChild(breadcrumbs[Crumb.Ellipsis]);
- let grandParent = parts.slice(0, parts.length - 2).join('/');
+ const grandParent = parts.slice(0, parts.length - 2).join('/');
breadcrumbs[Crumb.Ellipsis].title = grandParent;
node.appendChild(separators[1]);
}
@@ -332,7 +335,7 @@ namespace Private {
if (parts.length >= 2) {
breadcrumbs[Crumb.Parent].textContent = parts[parts.length - 2];
node.appendChild(breadcrumbs[Crumb.Parent]);
- let parent = parts.slice(0, parts.length - 1).join('/');
+ const parent = parts.slice(0, parts.length - 1).join('/');
breadcrumbs[Crumb.Parent].title = parent;
node.appendChild(separators[2]);
}
@@ -347,20 +350,20 @@ namespace Private {
* Create the breadcrumb nodes.
*/
export function createCrumbs(): ReadonlyArray {
- let home = folderIcon.element({
+ const home = folderIcon.element({
className: BREADCRUMB_HOME_CLASS,
tag: 'span',
title: PageConfig.getOption('serverRoot') || 'Jupyter Server Root',
stylesheet: 'breadCrumb'
});
- let ellipsis = ellipsesIcon.element({
+ const ellipsis = ellipsesIcon.element({
className: BREADCRUMB_ITEM_CLASS,
tag: 'span',
stylesheet: 'breadCrumb'
});
- let parent = document.createElement('span');
+ const parent = document.createElement('span');
parent.className = BREADCRUMB_ITEM_CLASS;
- let current = document.createElement('span');
+ const current = document.createElement('span');
current.className = BREADCRUMB_ITEM_CLASS;
return [home, ellipsis, parent, current];
}
@@ -369,14 +372,14 @@ namespace Private {
* Create the breadcrumb separator nodes.
*/
export function createCrumbSeparators(): ReadonlyArray {
- let items: HTMLElement[] = [];
+ const items: HTMLElement[] = [];
// The maximum number of directories that will be shown in the crumbs
const MAX_DIRECTORIES = 2;
// Make separators for after each directory, one at the beginning, and one
// after a possible ellipsis.
for (let i = 0; i < MAX_DIRECTORIES + 2; i++) {
- let item = document.createElement('span');
+ const item = document.createElement('span');
item.textContent = '/';
items.push(item);
}
diff --git a/packages/filebrowser/src/listing.ts b/packages/filebrowser/src/listing.ts
index bab3ab3c478c..9bdb43c4ddab 100644
--- a/packages/filebrowser/src/listing.ts
+++ b/packages/filebrowser/src/listing.ts
@@ -283,7 +283,7 @@ export class DirListing extends Widget {
* @returns A new iterator over the listing's selected items.
*/
selectedItems(): IIterator {
- let items = this._sortedItems;
+ const items = this._sortedItems;
return filter(items, item => this._selection[item.name]);
}
@@ -342,7 +342,7 @@ export class DirListing extends Widget {
}
const basePath = this._model.path;
- let promises: Promise[] = [];
+ const promises: Promise[] = [];
each(this._clipboard, path => {
if (this._isCut) {
@@ -407,11 +407,11 @@ export class DirListing extends Widget {
*/
duplicate(): Promise {
const basePath = this._model.path;
- let promises: Promise[] = [];
+ const promises: Promise[] = [];
each(this.selectedItems(), item => {
if (item.type !== 'directory') {
- let oldPath = PathExt.join(basePath, item.name);
+ const oldPath = PathExt.join(basePath, item.name);
promises.push(this._model.manager.copy(oldPath, basePath));
}
});
@@ -447,7 +447,7 @@ export class DirListing extends Widget {
const promises = toArray(this._model.sessions())
.filter(session => {
- let index = ArrayExt.firstIndexOf(paths, session.path);
+ const index = ArrayExt.firstIndexOf(paths, session.path);
return this._selection[items[index].name];
})
.map(session => model.manager.services.sessions.shutdown(session.id));
@@ -468,11 +468,11 @@ export class DirListing extends Widget {
*/
selectNext(keepExisting = false): void {
let index = -1;
- let selected = Object.keys(this._selection);
- let items = this._sortedItems;
+ const selected = Object.keys(this._selection);
+ const items = this._sortedItems;
if (selected.length === 1 || keepExisting) {
// Select the next item.
- let name = selected[selected.length - 1];
+ const name = selected[selected.length - 1];
index = ArrayExt.findFirstIndex(items, value => value.name === name);
index += 1;
if (index === this._items.length) {
@@ -483,7 +483,7 @@ export class DirListing extends Widget {
index = 0;
} else {
// Select the last selected item.
- let name = selected[selected.length - 1];
+ const name = selected[selected.length - 1];
index = ArrayExt.findFirstIndex(items, value => value.name === name);
}
if (index !== -1) {
@@ -499,11 +499,11 @@ export class DirListing extends Widget {
*/
selectPrevious(keepExisting = false): void {
let index = -1;
- let selected = Object.keys(this._selection);
- let items = this._sortedItems;
+ const selected = Object.keys(this._selection);
+ const items = this._sortedItems;
if (selected.length === 1 || keepExisting) {
// Select the previous item.
- let name = selected[0];
+ const name = selected[0];
index = ArrayExt.findFirstIndex(items, value => value.name === name);
index -= 1;
if (index === -1) {
@@ -514,7 +514,7 @@ export class DirListing extends Widget {
index = this._items.length - 1;
} else {
// Select the first selected item.
- let name = selected[0];
+ const name = selected[0];
index = ArrayExt.findFirstIndex(items, value => value.name === name);
}
if (index !== -1) {
@@ -528,9 +528,9 @@ export class DirListing extends Widget {
*/
selectByPrefix(): void {
const prefix = this._searchPrefix.toLowerCase();
- let items = this._sortedItems;
+ const items = this._sortedItems;
- let index = ArrayExt.findFirstIndex(items, value => {
+ const index = ArrayExt.findFirstIndex(items, value => {
return value.name.toLowerCase().substr(0, prefix.length) === prefix;
});
@@ -559,8 +559,12 @@ export class DirListing extends Widget {
* @returns The model for the selected file.
*/
modelForClick(event: MouseEvent): Contents.IModel | undefined {
- let items = this._sortedItems;
- let index = Private.hitTestNodes(this._items, event.clientX, event.clientY);
+ const items = this._sortedItems;
+ const index = Private.hitTestNodes(
+ this._items,
+ event.clientX,
+ event.clientY
+ );
if (index !== -1) {
return items[index];
}
@@ -588,8 +592,8 @@ export class DirListing extends Widget {
if (this.isDisposed) {
throw new Error('File browser is disposed.');
}
- let items = this._sortedItems;
- let index = ArrayExt.findFirstIndex(items, value => value.name === name);
+ const items = this._sortedItems;
+ const index = ArrayExt.findFirstIndex(items, value => value.name === name);
if (index === -1) {
throw new Error('Item does not exist.');
}
@@ -666,8 +670,8 @@ export class DirListing extends Widget {
*/
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
- let node = this.node;
- let content = DOMUtils.findElement(node, CONTENT_CLASS);
+ const node = this.node;
+ const content = DOMUtils.findElement(node, CONTENT_CLASS);
node.addEventListener('mousedown', this);
node.addEventListener('keydown', this);
node.addEventListener('click', this);
@@ -689,8 +693,8 @@ export class DirListing extends Widget {
*/
protected onBeforeDetach(msg: Message): void {
super.onBeforeDetach(msg);
- let node = this.node;
- let content = DOMUtils.findElement(node, CONTENT_CLASS);
+ const node = this.node;
+ const content = DOMUtils.findElement(node, CONTENT_CLASS);
node.removeEventListener('mousedown', this);
node.removeEventListener('keydown', this);
node.removeEventListener('click', this);
@@ -727,10 +731,10 @@ export class DirListing extends Widget {
this._isDirty = false;
// Fetch common variables.
- let items = this._sortedItems;
- let nodes = this._items;
- let content = DOMUtils.findElement(this.node, CONTENT_CLASS);
- let renderer = this._renderer;
+ const items = this._sortedItems;
+ const nodes = this._items;
+ const content = DOMUtils.findElement(this.node, CONTENT_CLASS);
+ const renderer = this._renderer;
this.removeClass(MULTI_SELECTED_CLASS);
this.removeClass(SELECTED_CLASS);
@@ -742,7 +746,7 @@ export class DirListing extends Widget {
// Add any missing item nodes.
while (nodes.length < items.length) {
- let node = renderer.createItemNode();
+ const node = renderer.createItemNode();
node.classList.add(ITEM_CLASS);
nodes.push(node);
content.appendChild(node);
@@ -757,8 +761,8 @@ export class DirListing extends Widget {
// Add extra classes to item nodes based on widget state.
items.forEach((item, i) => {
- let node = nodes[i];
- let ft = this._manager.registry.getFileTypeForModel(item);
+ const node = nodes[i];
+ const ft = this._manager.registry.getFileTypeForModel(item);
renderer.updateItemNode(node, item, ft);
if (this._selection[item.name]) {
node.classList.add(SELECTED_CLASS);
@@ -775,7 +779,7 @@ export class DirListing extends Widget {
});
// Handle the selectors on the widget node.
- let selected = Object.keys(this._selection).length;
+ const selected = Object.keys(this._selection).length;
if (selected) {
this.addClass(SELECTED_CLASS);
if (selected > 1) {
@@ -784,12 +788,12 @@ export class DirListing extends Widget {
}
// Handle file session statuses.
- let paths = items.map(item => item.path);
+ const paths = items.map(item => item.path);
each(this._model.sessions(), session => {
- let index = ArrayExt.firstIndexOf(paths, session.path);
- let node = nodes[index];
+ const index = ArrayExt.firstIndexOf(paths, session.path);
+ const node = nodes[index];
let name = session.kernel?.name;
- let specs = this._model.specs;
+ const specs = this._model.specs;
node.classList.add(RUNNING_CLASS);
if (specs && name) {
@@ -812,11 +816,11 @@ export class DirListing extends Widget {
* Handle the `'click'` event for the widget.
*/
private _evtClick(event: MouseEvent) {
- let target = event.target as HTMLElement;
+ const target = event.target as HTMLElement;
- let header = this.headerNode;
+ const header = this.headerNode;
if (header.contains(target)) {
- let state = this.renderer.handleHeaderClick(header, event);
+ const state = this.renderer.handleHeaderClick(header, event);
if (state) {
this.sort(state);
}
@@ -851,7 +855,11 @@ export class DirListing extends Widget {
}
}
- let index = Private.hitTestNodes(this._items, event.clientX, event.clientY);
+ const index = Private.hitTestNodes(
+ this._items,
+ event.clientX,
+ event.clientY
+ );
if (index === -1) {
return;
}
@@ -862,7 +870,7 @@ export class DirListing extends Widget {
}
// Check for clearing a context menu.
- let newContext = (IS_MAC && event.ctrlKey) || event.button === 2;
+ const newContext = (IS_MAC && event.ctrlKey) || event.button === 2;
if (newContext) {
return;
}
@@ -885,7 +893,7 @@ export class DirListing extends Widget {
private _evtMouseup(event: MouseEvent): void {
// Handle any soft selection from the previous mouse down.
if (this._softSelection) {
- let altered = event.metaKey || event.shiftKey || event.ctrlKey;
+ const altered = event.metaKey || event.shiftKey || event.ctrlKey;
// See if we need to clear the other selection.
if (!altered && event.button === 0) {
this.clearSelectedItems();
@@ -917,9 +925,9 @@ export class DirListing extends Widget {
}
// Check for a drag initialization.
- let data = this._dragData;
- let dx = Math.abs(event.clientX - data.pressX);
- let dy = Math.abs(event.clientY - data.pressY);
+ const data = this._dragData;
+ const dx = Math.abs(event.clientX - data.pressX);
+ const dy = Math.abs(event.clientY - data.pressY);
if (dx < DRAG_THRESHOLD && dy < DRAG_THRESHOLD) {
return;
}
@@ -938,7 +946,7 @@ export class DirListing extends Widget {
.cd(`/${localPath}`)
.catch(error => showErrorMessage('Open directory', error));
} else {
- let path = item.path;
+ const path = item.path;
this._manager.openOrReveal(path);
}
}
@@ -955,15 +963,15 @@ export class DirListing extends Widget {
event.preventDefault();
event.stopPropagation();
- let selected = Object.keys(this._selection);
- let name = selected[0];
- let items = this._sortedItems;
- let i = ArrayExt.findFirstIndex(items, value => value.name === name);
+ const selected = Object.keys(this._selection);
+ const name = selected[0];
+ const items = this._sortedItems;
+ const i = ArrayExt.findFirstIndex(items, value => value.name === name);
if (i === -1) {
return;
}
- let item = this._sortedItems[i];
+ const item = this._sortedItems[i];
this._handleOpen(item);
break;
case 38: // Up arrow
@@ -1019,13 +1027,15 @@ export class DirListing extends Widget {
this._editNode.blur();
// Find a valid double click target.
- let target = event.target as HTMLElement;
- let i = ArrayExt.findFirstIndex(this._items, node => node.contains(target));
+ const target = event.target as HTMLElement;
+ const i = ArrayExt.findFirstIndex(this._items, node =>
+ node.contains(target)
+ );
if (i === -1) {
return;
}
- let item = this._sortedItems[i];
+ const item = this._sortedItems[i];
this._handleOpen(item);
}
@@ -1033,7 +1043,7 @@ export class DirListing extends Widget {
* Handle the `drop` event for the widget.
*/
private _evtNativeDrop(event: DragEvent): void {
- let files = event.dataTransfer?.files;
+ const files = event.dataTransfer?.files;
if (!files || files.length === 0) {
return;
}
@@ -1048,7 +1058,7 @@ export class DirListing extends Widget {
*/
private _evtDragEnter(event: IDragEvent): void {
if (event.mimeData.hasData(CONTENTS_MIME)) {
- let index = Private.hitTestNodes(
+ const index = Private.hitTestNodes(
this._items,
event.clientX,
event.clientY
@@ -1056,11 +1066,11 @@ export class DirListing extends Widget {
if (index === -1) {
return;
}
- let item = this._sortedItems[index];
+ const item = this._sortedItems[index];
if (item.type !== 'directory' || this._selection[item.name]) {
return;
}
- let target = event.target as HTMLElement;
+ const target = event.target as HTMLElement;
target.classList.add(DROP_TARGET_CLASS);
event.preventDefault();
event.stopPropagation();
@@ -1073,7 +1083,7 @@ export class DirListing extends Widget {
private _evtDragLeave(event: IDragEvent): void {
event.preventDefault();
event.stopPropagation();
- let dropTarget = DOMUtils.findElement(this.node, DROP_TARGET_CLASS);
+ const dropTarget = DOMUtils.findElement(this.node, DROP_TARGET_CLASS);
if (dropTarget) {
dropTarget.classList.remove(DROP_TARGET_CLASS);
}
@@ -1086,11 +1096,15 @@ export class DirListing extends Widget {
event.preventDefault();
event.stopPropagation();
event.dropAction = event.proposedAction;
- let dropTarget = DOMUtils.findElement(this.node, DROP_TARGET_CLASS);
+ const dropTarget = DOMUtils.findElement(this.node, DROP_TARGET_CLASS);
if (dropTarget) {
dropTarget.classList.remove(DROP_TARGET_CLASS);
}
- let index = Private.hitTestNodes(this._items, event.clientX, event.clientY);
+ const index = Private.hitTestNodes(
+ this._items,
+ event.clientX,
+ event.clientY
+ );
this._items[index].classList.add(DROP_TARGET_CLASS);
}
@@ -1136,10 +1150,10 @@ export class DirListing extends Widget {
} else {
event.dropAction = event.proposedAction;
}
- for (let path of paths) {
- let localPath = manager.services.contents.localPath(path);
- let name = PathExt.basename(localPath);
- let newPath = PathExt.join(basePath, name);
+ for (const path of paths) {
+ const localPath = manager.services.contents.localPath(path);
+ const name = PathExt.basename(localPath);
+ const newPath = PathExt.join(basePath, name);
// Skip files that are not moving.
if (newPath === path) {
continue;
@@ -1161,8 +1175,8 @@ export class DirListing extends Widget {
*/
private _startDrag(index: number, clientX: number, clientY: number): void {
let selectedNames = Object.keys(this._selection);
- let source = this._items[index];
- let items = this._sortedItems;
+ const source = this._items[index];
+ const items = this._sortedItems;
let selectedItems: Contents.IModel[];
let item: Contents.IModel | undefined;
@@ -1172,7 +1186,7 @@ export class DirListing extends Widget {
selectedNames = [item.name];
selectedItems = [item];
} else {
- let name = selectedNames[0];
+ const name = selectedNames[0];
item = find(items, value => value.name === name);
selectedItems = toArray(this.selectedItems());
}
@@ -1182,8 +1196,8 @@ export class DirListing extends Widget {
}
// Create the drag image.
- let ft = this._manager.registry.getFileTypeForModel(item);
- let dragImage = this.renderer.createDragImage(
+ const ft = this._manager.registry.getFileTypeForModel(item);
+ const dragImage = this.renderer.createDragImage(
source,
selectedNames.length,
ft
@@ -1196,9 +1210,9 @@ export class DirListing extends Widget {
supportedActions: 'move',
proposedAction: 'move'
});
- let basePath = this._model.path;
+ const basePath = this._model.path;
- let paths = toArray(
+ const paths = toArray(
map(selectedNames, name => {
return PathExt.join(basePath, name);
})
@@ -1209,7 +1223,7 @@ export class DirListing extends Widget {
// We thunk the content so we don't try to make a network call
// when it's not needed. E.g. just moving files around
// in a filebrowser
- let services = this.model.manager.services;
+ const services = this.model.manager.services;
for (const item of selectedItems) {
this._drag.mimeData.setData(CONTENTS_MIME_RICH, {
model: item,
@@ -1225,7 +1239,7 @@ export class DirListing extends Widget {
if (!item) {
return;
}
- let path = item.path;
+ const path = item.path;
let widget = this._manager.findWidget(path);
if (!widget) {
widget = this._manager.open(item.path);
@@ -1269,8 +1283,12 @@ export class DirListing extends Widget {
*/
private _handleFileSelect(event: MouseEvent): void {
// Fetch common variables.
- let items = this._sortedItems;
- let index = Private.hitTestNodes(this._items, event.clientX, event.clientY);
+ const items = this._sortedItems;
+ const index = Private.hitTestNodes(
+ this._items,
+ event.clientX,
+ event.clientY
+ );
clearTimeout(this._selectTimer);
@@ -1281,8 +1299,8 @@ export class DirListing extends Widget {
// Clear any existing soft selection.
this._softSelection = '';
- let name = items[index].name;
- let selected = Object.keys(this._selection);
+ const name = items[index].name;
+ const selected = Object.keys(this._selection);
// Handle toggling.
if ((IS_MAC && event.metaKey) || (!IS_MAC && event.ctrlKey)) {
@@ -1314,13 +1332,13 @@ export class DirListing extends Widget {
*/
private _handleMultiSelect(selected: string[], index: number): void {
// Find the "nearest selected".
- let items = this._sortedItems;
+ const items = this._sortedItems;
let nearestIndex = -1;
for (let i = 0; i < this._items.length; i++) {
if (i === index) {
continue;
}
- let name = items[i].name;
+ const name = items[i].name;
if (selected.indexOf(name) !== -1) {
if (nearestIndex === -1) {
nearestIndex = i;
@@ -1376,13 +1394,13 @@ export class DirListing extends Widget {
*/
private _doRename(): Promise {
this._inRename = true;
- let items = this._sortedItems;
- let name = Object.keys(this._selection)[0];
- let index = ArrayExt.findFirstIndex(items, value => value.name === name);
- let row = this._items[index];
- let item = items[index];
- let nameNode = this.renderer.getNameNode(row);
- let original = item.name;
+ const items = this._sortedItems;
+ const name = Object.keys(this._selection)[0];
+ const index = ArrayExt.findFirstIndex(items, value => value.name === name);
+ const row = this._items[index];
+ const item = items[index];
+ const nameNode = this.renderer.getNameNode(row);
+ const original = item.name;
this._editNode.value = original;
this._selectItem(index, false);
@@ -1442,11 +1460,11 @@ export class DirListing extends Widget {
*/
private _selectItem(index: number, keepExisting: boolean) {
// Selected the given row(s)
- let items = this._sortedItems;
+ const items = this._sortedItems;
if (!keepExisting) {
this.clearSelectedItems();
}
- let name = items[index].name;
+ const name = items[index].name;
this._selection[name] = true;
this.update();
}
@@ -1456,10 +1474,10 @@ export class DirListing extends Widget {
*/
private _onModelRefreshed(): void {
// Update the selection.
- let existing = Object.keys(this._selection);
+ const existing = Object.keys(this._selection);
this.clearSelectedItems();
each(this._model.items(), item => {
- let name = item.name;
+ const name = item.name;
if (existing.indexOf(name) !== -1) {
this._selection[name] = true;
}
@@ -1489,12 +1507,12 @@ export class DirListing extends Widget {
sender: FileBrowserModel,
args: Contents.IChangedArgs
) {
- let newValue = args.newValue;
+ const newValue = args.newValue;
if (!newValue) {
return;
}
- let name = newValue.name;
+ const name = newValue.name;
if (args.type !== 'new' || !name) {
return;
}
@@ -1514,11 +1532,11 @@ export class DirListing extends Widget {
* Handle an `activateRequested` signal from the manager.
*/
private _onActivateRequested(sender: IDocumentManager, args: string): void {
- let dirname = PathExt.dirname(args);
+ const dirname = PathExt.dirname(args);
if (dirname !== this._model.path) {
return;
}
- let basename = PathExt.basename(args);
+ const basename = PathExt.basename(args);
this.selectItemByName(basename).catch(() => {
/* Ignore if file does not exist. */
});
@@ -1692,9 +1710,9 @@ export namespace DirListing {
* Create the DOM node for a dir listing.
*/
createNode(): HTMLElement {
- let node = document.createElement('div');
- let header = document.createElement('div');
- let content = document.createElement('ul');
+ const node = document.createElement('div');
+ const header = document.createElement('div');
+ const content = document.createElement('ul');
content.className = CONTENT_CLASS;
header.className = HEADER_CLASS;
node.appendChild(header);
@@ -1709,8 +1727,8 @@ export namespace DirListing {
* @param node - The header node to populate.
*/
populateHeaderNode(node: HTMLElement): void {
- let name = this._createHeaderItemNode('Name');
- let modified = this._createHeaderItemNode('Last Modified');
+ const name = this._createHeaderItemNode('Name');
+ const modified = this._createHeaderItemNode('Last Modified');
name.classList.add(NAME_ID_CLASS);
name.classList.add(SELECTED_CLASS);
modified.classList.add(MODIFIED_ID_CLASS);
@@ -1735,10 +1753,10 @@ export namespace DirListing {
* @returns The sort state of the header after the click event.
*/
handleHeaderClick(node: HTMLElement, event: MouseEvent): ISortState {
- let name = DOMUtils.findElement(node, NAME_ID_CLASS);
- let modified = DOMUtils.findElement(node, MODIFIED_ID_CLASS);
- let state: ISortState = { direction: 'ascending', key: 'name' };
- let target = event.target as HTMLElement;
+ const name = DOMUtils.findElement(node, NAME_ID_CLASS);
+ const modified = DOMUtils.findElement(node, MODIFIED_ID_CLASS);
+ const state: ISortState = { direction: 'ascending', key: 'name' };
+ const target = event.target as HTMLElement;
if (name.contains(target)) {
const modifiedIcon = DOMUtils.findElement(
modified,
@@ -1801,10 +1819,10 @@ export namespace DirListing {
* @returns A new DOM node to use as a content item.
*/
createItemNode(): HTMLElement {
- let node = document.createElement('li');
- let icon = document.createElement('span');
- let text = document.createElement('span');
- let modified = document.createElement('span');
+ const node = document.createElement('li');
+ const icon = document.createElement('span');
+ const text = document.createElement('span');
+ const modified = document.createElement('span');
icon.className = ITEM_ICON_CLASS;
text.className = ITEM_TEXT_CLASS;
modified.className = ITEM_MODIFIED_CLASS;
@@ -1850,7 +1868,7 @@ export namespace DirListing {
hoverText += '\nSize: ' + Private.formatFileSize(model.size, 1, 1024);
}
if (model.path) {
- let dirname = PathExt.dirname(model.path);
+ const dirname = PathExt.dirname(model.path);
if (dirname) {
hoverText += '\nPath: ' + dirname.substr(0, 50);
if (dirname.length > 50) {
@@ -1913,9 +1931,9 @@ export namespace DirListing {
count: number,
fileType?: DocumentRegistry.IFileType
): HTMLElement {
- let dragImage = node.cloneNode(true) as HTMLElement;
- let modified = DOMUtils.findElement(dragImage, ITEM_MODIFIED_CLASS);
- let icon = DOMUtils.findElement(dragImage, ITEM_ICON_CLASS);
+ const dragImage = node.cloneNode(true) as HTMLElement;
+ const modified = DOMUtils.findElement(dragImage, ITEM_MODIFIED_CLASS);
+ const icon = DOMUtils.findElement(dragImage, ITEM_ICON_CLASS);
dragImage.removeChild(modified as HTMLElement);
if (!fileType) {
@@ -1928,7 +1946,7 @@ export namespace DirListing {
icon.classList.add(DRAG_ICON_CLASS);
if (count > 1) {
- let nameNode = DOMUtils.findElement(dragImage, ITEM_TEXT_CLASS);
+ const nameNode = DOMUtils.findElement(dragImage, ITEM_TEXT_CLASS);
nameNode.textContent = count + ' Items';
}
return dragImage;
@@ -1938,9 +1956,9 @@ export namespace DirListing {
* Create a node for a header item.
*/
private _createHeaderItemNode(label: string): HTMLElement {
- let node = document.createElement('div');
- let text = document.createElement('span');
- let icon = document.createElement('span');
+ const node = document.createElement('div');
+ const text = document.createElement('span');
+ const icon = document.createElement('span');
node.className = HEADER_ITEM_CLASS;
text.className = HEADER_ITEM_TEXT_CLASS;
icon.className = HEADER_ITEM_ICON_CLASS;
@@ -1970,10 +1988,10 @@ namespace Private {
text: HTMLElement,
edit: HTMLInputElement
): Promise {
- let parent = text.parentElement as HTMLElement;
+ const parent = text.parentElement as HTMLElement;
parent.replaceChild(edit, text);
edit.focus();
- let index = edit.value.lastIndexOf('.');
+ const index = edit.value.lastIndexOf('.');
if (index === -1) {
edit.setSelectionRange(0, edit.value.length);
} else {
@@ -2025,25 +2043,25 @@ namespace Private {
items: IIterator,
state: DirListing.ISortState
): Contents.IModel[] {
- let copy = toArray(items);
- let reverse = state.direction === 'descending' ? 1 : -1;
+ const copy = toArray(items);
+ const reverse = state.direction === 'descending' ? 1 : -1;
if (state.key === 'last_modified') {
// Sort by last modified (grouping directories first)
copy.sort((a, b) => {
- let t1 = a.type === 'directory' ? 0 : 1;
- let t2 = b.type === 'directory' ? 0 : 1;
+ const t1 = a.type === 'directory' ? 0 : 1;
+ const t2 = b.type === 'directory' ? 0 : 1;
- let valA = new Date(a.last_modified).getTime();
- let valB = new Date(b.last_modified).getTime();
+ const valA = new Date(a.last_modified).getTime();
+ const valB = new Date(b.last_modified).getTime();
return t1 - t2 || (valA - valB) * reverse;
});
} else {
// Sort by name (grouping directories first)
copy.sort((a, b) => {
- let t1 = a.type === 'directory' ? 0 : 1;
- let t2 = b.type === 'directory' ? 0 : 1;
+ const t1 = a.type === 'directory' ? 0 : 1;
+ const t2 = b.type === 'directory' ? 0 : 1;
return t1 - t2 || b.name.localeCompare(a.name) * reverse;
});
diff --git a/packages/filebrowser/src/model.ts b/packages/filebrowser/src/model.ts
index 403d220dc04c..5787c77ec156 100644
--- a/packages/filebrowser/src/model.ts
+++ b/packages/filebrowser/src/model.ts
@@ -69,7 +69,7 @@ export class FileBrowserModel implements IDisposable {
constructor(options: FileBrowserModel.IOptions) {
this.manager = options.manager;
this._driveName = options.driveName || '';
- let rootPath = this._driveName ? this._driveName + ':' : '';
+ const rootPath = this._driveName ? this._driveName + ':' : '';
this._model = {
path: rootPath,
name: PathExt.basename(rootPath),
@@ -258,13 +258,13 @@ export class FileBrowserModel implements IDisposable {
// Otherwise wait for the pending request to complete before continuing.
await this._pending;
}
- let oldValue = this.path;
- let options: Contents.IFetchOptions = { content: true };
+ const oldValue = this.path;
+ const options: Contents.IFetchOptions = { content: true };
this._pendingPath = newValue;
if (oldValue !== newValue) {
this._sessions.length = 0;
}
- let services = this.manager.services;
+ const services = this.manager.services;
this._pending = services.contents
.get(newValue, options)
.then(contents => {
@@ -315,7 +315,7 @@ export class FileBrowserModel implements IDisposable {
*/
async download(path: string): Promise {
const url = await this.manager.services.contents.getDownloadUrl(path);
- let element = document.createElement('a');
+ const element = document.createElement('a');
element.href = url;
element.download = '';
document.body.appendChild(element);
@@ -395,9 +395,8 @@ export class FileBrowserModel implements IDisposable {
const largeFile = file.size > LARGE_FILE_SIZE;
if (largeFile && !supportsChunked) {
- let msg = `Cannot upload file (>${LARGE_FILE_SIZE / (1024 * 1024)} MB). ${
- file.name
- }`;
+ const msg = `Cannot upload file (>${LARGE_FILE_SIZE /
+ (1024 * 1024)} MB). ${file.name}`;
console.warn(msg);
throw msg;
}
@@ -441,16 +440,16 @@ export class FileBrowserModel implements IDisposable {
// Gather the file model parameters.
let path = this._model.path;
path = path ? path + '/' + file.name : file.name;
- let name = file.name;
- let type: Contents.ContentType = 'file';
- let format: Contents.FileFormat = 'base64';
+ const name = file.name;
+ const type: Contents.ContentType = 'file';
+ const format: Contents.FileFormat = 'base64';
const uploadInner = async (
blob: Blob,
chunk?: number
): Promise => {
await this._uploadCheckDisposed();
- let reader = new FileReader();
+ const reader = new FileReader();
reader.readAsDataURL(blob);
await new Promise((resolve, reject) => {
reader.onload = resolve;
@@ -462,7 +461,7 @@ export class FileBrowserModel implements IDisposable {
// remove header https://stackoverflow.com/a/24289420/907060
const content = (reader.result as string).split(',')[1];
- let model: Partial = {
+ const model: Partial = {
type,
format,
name,
@@ -587,10 +586,10 @@ export class FileBrowserModel implements IDisposable {
sender: Contents.IManager,
change: Contents.IChangedArgs
): void {
- let path = this._model.path;
- let { sessions } = this.manager.services;
- let { oldValue, newValue } = change;
- let value =
+ const path = this._model.path;
+ const { sessions } = this.manager.services;
+ const { oldValue, newValue } = change;
+ const value =
oldValue && oldValue.path && PathExt.dirname(oldValue.path) === path
? oldValue
: newValue && newValue.path && PathExt.dirname(newValue.path) === path
diff --git a/packages/filebrowser/src/opendialog.ts b/packages/filebrowser/src/opendialog.ts
index 2cf0f802ffab..de9f84d3253c 100644
--- a/packages/filebrowser/src/opendialog.ts
+++ b/packages/filebrowser/src/opendialog.ts
@@ -64,7 +64,7 @@ export namespace FileDialog {
export function getOpenFiles(
options: IFileOptions
): Promise> {
- let dialogOptions: Partial> = {
+ const dialogOptions: Partial> = {
title: options.title,
buttons: [
Dialog.cancelButton(),
@@ -77,7 +77,7 @@ export namespace FileDialog {
renderer: options.renderer,
body: new OpenDialog(options.manager, options.filter)
};
- let dialog = new Dialog(dialogOptions);
+ const dialog = new Dialog(dialogOptions);
return dialog.launch();
}
@@ -120,7 +120,7 @@ class OpenDialog extends Widget
);
// Build the sub widgets
- let layout = new PanelLayout();
+ const layout = new PanelLayout();
layout.addWidget(this._browser);
// Set Widget content
diff --git a/packages/filebrowser/src/upload.ts b/packages/filebrowser/src/upload.ts
index 6d5f312b976f..d97d568371eb 100644
--- a/packages/filebrowser/src/upload.ts
+++ b/packages/filebrowser/src/upload.ts
@@ -38,8 +38,8 @@ export class Uploader extends ToolbarButton {
* The 'change' handler for the input field.
*/
private _onInputChanged = () => {
- let files = Array.prototype.slice.call(this._input.files) as File[];
- let pending = files.map(file => this.fileBrowserModel.upload(file));
+ const files = Array.prototype.slice.call(this._input.files) as File[];
+ const pending = files.map(file => this.fileBrowserModel.upload(file));
void Promise.all(pending).catch(error => {
void showErrorMessage('Upload Error', error);
});
@@ -80,7 +80,7 @@ namespace Private {
* Create the upload input node for a file buttons widget.
*/
export function createUploadInput(): HTMLInputElement {
- let input = document.createElement('input');
+ const input = document.createElement('input');
input.type = 'file';
input.multiple = true;
return input;
diff --git a/packages/fileeditor-extension/src/commands.ts b/packages/fileeditor-extension/src/commands.ts
index d2dd7d1ea82f..5886a1902ade 100644
--- a/packages/fileeditor-extension/src/commands.ts
+++ b/packages/fileeditor-extension/src/commands.ts
@@ -368,7 +368,7 @@ export namespace Commands {
commands.addCommand(CommandIDs.replaceSelection, {
execute: args => {
const text: string = (args['text'] as string) || '';
- let widget = tracker.currentWidget;
+ const widget = tracker.currentWidget;
if (!widget) {
return;
}
@@ -437,7 +437,7 @@ export namespace Commands {
const { text } = editor.model.value;
const blocks = MarkdownCodeBlocks.findMarkdownCodeBlocks(text);
- for (let block of blocks) {
+ for (const block of blocks) {
if (block.startLine <= start.line && start.line <= block.endLine) {
code = block.code;
selected = true;
@@ -451,7 +451,7 @@ export namespace Commands {
code = editor.getLine(selection.start.line);
const cursor = editor.getCursorPosition();
if (cursor.line + 1 === editor.lineCount) {
- let text = editor.model.value.text;
+ const text = editor.model.value.text;
editor.model.value.text = text + '\n';
}
editor.setCursorPosition({
@@ -482,22 +482,22 @@ export namespace Commands {
) {
commands.addCommand(CommandIDs.runAllCode, {
execute: () => {
- let widget = tracker.currentWidget?.content;
+ const widget = tracker.currentWidget?.content;
if (!widget) {
return;
}
let code = '';
- let editor = widget.editor;
- let text = editor.model.value.text;
- let path = widget.context.path;
- let extension = PathExt.extname(path);
+ const editor = widget.editor;
+ const text = editor.model.value.text;
+ const path = widget.context.path;
+ const extension = PathExt.extname(path);
if (MarkdownCodeBlocks.isMarkdown(extension)) {
// For Markdown files, run only code blocks.
const blocks = MarkdownCodeBlocks.findMarkdownCodeBlocks(text);
- for (let block of blocks) {
+ for (const block of blocks) {
code += block.code;
}
} else {
@@ -525,11 +525,11 @@ export namespace Commands {
) {
commands.addCommand(CommandIDs.markdownPreview, {
execute: () => {
- let widget = tracker.currentWidget;
+ const widget = tracker.currentWidget;
if (!widget) {
return;
}
- let path = widget.context.path;
+ const path = widget.context.path;
return commands.execute('markdownviewer:open', {
path,
options: {
@@ -538,7 +538,7 @@ export namespace Commands {
});
},
isVisible: () => {
- let widget = tracker.currentWidget;
+ const widget = tracker.currentWidget;
return (
(widget && PathExt.extname(widget.context.path) === '.md') || false
);
@@ -581,7 +581,7 @@ export namespace Commands {
caption: 'Create a new text file',
icon: args => (args['isPalette'] ? undefined : textEditorIcon),
execute: args => {
- let cwd = args['cwd'] || browserFactory.defaultBrowser.model.path;
+ const cwd = args['cwd'] || browserFactory.defaultBrowser.model.path;
return createNew(commands, cwd as string);
}
});
@@ -600,7 +600,7 @@ export namespace Commands {
caption: 'Create a new markdown file',
icon: args => (args['isPalette'] ? undefined : markdownIcon),
execute: args => {
- let cwd = args['cwd'] || browserFactory.defaultBrowser.model.path;
+ const cwd = args['cwd'] || browserFactory.defaultBrowser.model.path;
return createNew(commands, cwd as string, 'md');
}
});
@@ -659,16 +659,16 @@ export namespace Commands {
* Add commands to change the tab indentation to the File Editor palette
*/
export function addChangeTabsCommandsToPalette(palette: ICommandPalette) {
- let args: JSONObject = {
+ const args: JSONObject = {
insertSpaces: false,
size: 4,
name: 'Indent with Tab'
};
- let command = 'fileeditor:change-tabs';
+ const command = 'fileeditor:change-tabs';
palette.addItem({ command, args, category: paletteCategory });
- for (let size of [1, 2, 4, 8]) {
- let args: JSONObject = {
+ for (const size of [1, 2, 4, 8]) {
+ const args: JSONObject = {
insertSpaces: true,
size,
name: `Spaces: ${size} `
@@ -705,7 +705,7 @@ export namespace Commands {
* Add commands to change the font size to the File Editor palette
*/
export function addChangeFontSizeCommandsToPalette(palette: ICommandPalette) {
- let command = CommandIDs.changeFontSize;
+ const command = CommandIDs.changeFontSize;
let args = { name: 'Increase Font Size', delta: 1 };
palette.addItem({ command, args, category: paletteCategory });
@@ -762,16 +762,16 @@ export namespace Commands {
) {
const tabMenu = new Menu({ commands });
tabMenu.title.label = 'Text Editor Indentation';
- let args: JSONObject = {
+ const args: JSONObject = {
insertSpaces: false,
size: 4,
name: 'Indent with Tab'
};
- let command = 'fileeditor:change-tabs';
+ const command = 'fileeditor:change-tabs';
tabMenu.addItem({ command, args });
- for (let size of [1, 2, 4, 8]) {
- let args: JSONObject = {
+ for (const size of [1, 2, 4, 8]) {
+ const args: JSONObject = {
insertSpaces: true,
size,
name: `Spaces: ${size} `
@@ -870,7 +870,7 @@ export namespace Commands {
commands: CommandRegistry,
tracker: WidgetTracker>
) {
- let createConsole: (
+ const createConsole: (
widget: IDocumentWidget
) => Promise = getCreateConsoleFunction(commands);
menu.fileMenu.consoleCreators.add({
diff --git a/packages/fileeditor-extension/src/index.ts b/packages/fileeditor-extension/src/index.ts
index 3f81148ccb6b..e545c9ed9baa 100644
--- a/packages/fileeditor-extension/src/index.ts
+++ b/packages/fileeditor-extension/src/index.ts
@@ -96,8 +96,8 @@ export const tabSpaceStatus: JupyterFrontEndPlugin = {
name: 'Indent with Tab'
};
menu.addItem({ command, args });
- for (let size of [1, 2, 4, 8]) {
- let args: JSONObject = {
+ for (const size of [1, 2, 4, 8]) {
+ const args: JSONObject = {
insertSpaces: true,
size,
name: `Spaces: ${size} `
diff --git a/packages/fileeditor/src/widget.ts b/packages/fileeditor/src/widget.ts
index a028003687fc..932193301bf7 100644
--- a/packages/fileeditor/src/widget.ts
+++ b/packages/fileeditor/src/widget.ts
@@ -59,15 +59,15 @@ export class FileEditorCodeWrapper extends CodeEditorWrapper {
});
if (context.model.modelDB.isCollaborative) {
- let modelDB = context.model.modelDB;
+ const modelDB = context.model.modelDB;
void modelDB.connected.then(() => {
- let collaborators = modelDB.collaborators;
+ const collaborators = modelDB.collaborators;
if (!collaborators) {
return;
}
// Setup the selection style for collaborators
- let localCollaborator = collaborators.localCollaborator;
+ const localCollaborator = collaborators.localCollaborator;
this.editor.uuid = localCollaborator.sessionId;
this.editor.selectionStyle = {
@@ -140,11 +140,11 @@ export class FileEditorCodeWrapper extends CodeEditorWrapper {
private _onCollaboratorsChanged(): void {
// If there are selections corresponding to non-collaborators,
// they are stale and should be removed.
- let collaborators = this._context.model.modelDB.collaborators;
+ const collaborators = this._context.model.modelDB.collaborators;
if (!collaborators) {
return;
}
- for (let key of this.editor.model.selections.keys()) {
+ for (const key of this.editor.model.selections.keys()) {
if (!collaborators.has(key)) {
this.editor.model.selections.delete(key);
}
@@ -169,7 +169,9 @@ export class FileEditor extends Widget {
const context = (this._context = options.context);
this._mimeTypeService = options.mimeTypeService;
- let editorWidget = (this.editorWidget = new FileEditorCodeWrapper(options));
+ const editorWidget = (this.editorWidget = new FileEditorCodeWrapper(
+ options
+ ));
this.editor = editorWidget.editor;
this.model = editorWidget.model;
@@ -177,7 +179,7 @@ export class FileEditor extends Widget {
context.pathChanged.connect(this._onPathChanged, this);
this._onPathChanged();
- let layout = (this.layout = new StackedLayout());
+ const layout = (this.layout = new StackedLayout());
layout.addWidget(editorWidget);
}
@@ -223,7 +225,7 @@ export class FileEditor extends Widget {
*/
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
- let node = this.node;
+ const node = this.node;
node.addEventListener('mousedown', this);
}
@@ -231,7 +233,7 @@ export class FileEditor extends Widget {
* Handle `before-detach` messages for the widget.
*/
protected onBeforeDetach(msg: Message): void {
- let node = this.node;
+ const node = this.node;
node.removeEventListener('mousedown', this);
}
@@ -316,8 +318,8 @@ export class FileEditorFactory extends ABCWidgetFactory<
protected createNewWidget(
context: DocumentRegistry.CodeContext
): IDocumentWidget {
- let func = this._services.factoryService.newDocumentEditor;
- let factory: CodeEditor.Factory = options => {
+ const func = this._services.factoryService.newDocumentEditor;
+ const factory: CodeEditor.Factory = options => {
return func(options);
};
const content = new FileEditor({
diff --git a/packages/help-extension/src/index.tsx b/packages/help-extension/src/index.tsx
index 58e3efe5f32f..efebe68f851e 100644
--- a/packages/help-extension/src/index.tsx
+++ b/packages/help-extension/src/index.tsx
@@ -144,14 +144,14 @@ function activate(
// We *don't* allow same origin requests, which
// can prevent some content from being loaded onto the
// help pages.
- let content = new IFrame({
+ const content = new IFrame({
sandbox: ['allow-scripts', 'allow-forms']
});
content.url = url;
content.addClass(HELP_CLASS);
content.title.label = text;
content.id = `${namespace}-${++counter}`;
- let widget = new MainAreaWidget({ content });
+ const widget = new MainAreaWidget({ content });
widget.addClass('jp-Help');
return widget;
}
@@ -233,7 +233,7 @@ function activate(
const kernelName = spec.display_name;
let kernelIconUrl = spec.resources['logo-64x64'];
if (kernelIconUrl) {
- let index = kernelIconUrl.indexOf('kernelspecs');
+ const index = kernelIconUrl.indexOf('kernelspecs');
kernelIconUrl = baseUrl + kernelIconUrl.slice(index);
}
commands.addCommand(bannerCommand, {
@@ -242,15 +242,15 @@ function activate(
isEnabled: usesKernel,
execute: () => {
// Create the header of the about dialog
- let headerLogo = ;
- let title = (
+ const headerLogo = ;
+ const title = (
{headerLogo}
{kernelName}
);
const banner = {kernelInfo.banner} ;
- let body = {banner}
;
+ const body = {banner}
;
return showDialog({
title,
@@ -291,13 +291,13 @@ function activate(
label: `About ${app.name}`,
execute: () => {
// Create the header of the about dialog
- let versionNumber = `Version ${app.version}`;
- let versionInfo = (
+ const versionNumber = `Version ${app.version}`;
+ const versionInfo = (
{versionNumber}
);
- let title = (
+ const title = (
@@ -308,15 +308,15 @@ function activate(
);
// Create the body of the about dialog
- let jupyterURL = 'https://jupyter.org/about.html';
- let contributorsURL =
+ const jupyterURL = 'https://jupyter.org/about.html';
+ const contributorsURL =
'https://github.com/jupyterlab/jupyterlab/graphs/contributors';
- let externalLinks = (
+ const externalLinks = (
CONTRIBUTOR LIST
@@ -324,19 +324,19 @@ function activate(
ABOUT PROJECT JUPYTER
);
- let copyright = (
+ const copyright = (
© 2015-2020 Project Jupyter Contributors
);
- let body = (
+ const body = (
{externalLinks}
{copyright}
@@ -372,7 +372,7 @@ function activate(
return;
}
- let widget = newHelpWidget(url, text);
+ const widget = newHelpWidget(url, text);
void tracker.add(widget);
shell.add(widget, 'main');
return widget;
diff --git a/packages/htmlviewer-extension/src/index.tsx b/packages/htmlviewer-extension/src/index.tsx
index 21e5b6c72064..92f06f982395 100644
--- a/packages/htmlviewer-extension/src/index.tsx
+++ b/packages/htmlviewer-extension/src/index.tsx
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
diff --git a/packages/htmlviewer/src/index.tsx b/packages/htmlviewer/src/index.tsx
index aeca3141bfc8..bea4ba879c97 100644
--- a/packages/htmlviewer/src/index.tsx
+++ b/packages/htmlviewer/src/index.tsx
@@ -1,4 +1,4 @@
-/*-----------------------------------------------------------------------------
+/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
@@ -122,6 +122,7 @@ export class HTMLViewer extends DocumentWidget