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} />