From 1dba9f3a5860c0e38eb1b66f5970e1e42e21d10c Mon Sep 17 00:00:00 2001 From: Niklas Fiekas Date: Wed, 7 Apr 2021 20:26:38 +0200 Subject: [PATCH] fix trivial cases of no-var --- .eslintrc.json | 3 +- ui/@types/cash/index.d.ts | 2 +- ui/@types/lichess/index.d.ts | 2 +- ui/analyse/src/forecast/forecastCtrl.ts | 10 +- ui/analyse/src/forecast/forecastView.ts | 6 +- ui/analyse/src/nodeFinder.ts | 10 +- ui/analyse/src/pgnExport.ts | 8 +- ui/analyse/src/retrospect/retroCtrl.ts | 4 +- ui/analyse/src/socket.ts | 2 +- .../study/practice/studyPracticeSuccess.ts | 2 +- ui/analyse/src/study/studyMembers.ts | 2 +- ui/analyse/src/util.ts | 8 +- ui/challenge/src/ctrl.ts | 4 +- ui/cli/src/main.ts | 2 +- ui/dasher/src/background.ts | 2 +- ui/dgt/src/play.ts | 136 +++++++++--------- ui/lobby/src/setup.ts | 16 +-- ui/notify/src/renderers.ts | 2 +- ui/nvui/src/chess.ts | 2 +- ui/puzzle/src/view/side.ts | 2 +- ui/puzzle/src/view/tree.ts | 4 +- ui/round/src/plugins/sanWriter.ts | 38 ++--- ui/round/src/promotion.ts | 6 +- ui/site/src/checkout.ts | 16 +-- ui/site/src/coachForm.ts | 14 +- ui/site/src/coordinate.ts | 64 ++++----- ui/site/src/expandText.ts | 4 +- ui/site/src/forum.ts | 2 +- ui/site/src/gameSearch.ts | 8 +- ui/site/src/passwordComplexity.ts | 2 +- ui/tournamentSchedule/src/view.ts | 2 +- ui/tree/src/tree.ts | 14 +- 32 files changed, 197 insertions(+), 202 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index b51915202c..d3ee9140cc 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -18,10 +18,9 @@ "@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/no-this-alias": "off", "@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }], + "@typescript-eslint/no-empty-interface": "off", "eqeqeq": "off", - "no-var": "off", - "@typescript-eslint/no-empty-interface": "off", "@typescript-eslint/explicit-module-boundary-types": "off", "prefer-spread": "off", "prefer-rest-params": "off", diff --git a/ui/@types/cash/index.d.ts b/ui/@types/cash/index.d.ts index e895c3e002..6641f0d97d 100644 --- a/ui/@types/cash/index.d.ts +++ b/ui/@types/cash/index.d.ts @@ -313,7 +313,7 @@ interface CashStatic { declare module 'cash' { export = $; } -declare var $: CashStatic; +declare const $: CashStatic; /* export default cash; */ /* export { Cash, CashStatic, Ele as Element, Selector, Comparator, Context }; */ /* end hacks */ diff --git a/ui/@types/lichess/index.d.ts b/ui/@types/lichess/index.d.ts index 499add5f98..0dc7810432 100644 --- a/ui/@types/lichess/index.d.ts +++ b/ui/@types/lichess/index.d.ts @@ -490,4 +490,4 @@ declare namespace PowerTip { declare module '@yaireo/tagify'; -declare var lichess: Lichess; +declare const lichess: Lichess; diff --git a/ui/analyse/src/forecast/forecastCtrl.ts b/ui/analyse/src/forecast/forecastCtrl.ts index f4eb494f02..a3745c3939 100644 --- a/ui/analyse/src/forecast/forecastCtrl.ts +++ b/ui/analyse/src/forecast/forecastCtrl.ts @@ -18,13 +18,11 @@ export function make(cfg: ForecastData, data: AnalyseData, redraw: () => void): } function findStartingWithNode(node: ForecastStep): ForecastStep[][] { - return forecasts.filter(function (fc) { - return contains(fc, [node]); - }); + return forecasts.filter(fc => contains(fc, [node])); } function collides(fc1: ForecastStep[], fc2: ForecastStep[]): boolean { - for (var i = 0, max = Math.min(fc1.length, fc2.length); i < max; i++) { + for (let i = 0, max = Math.min(fc1.length, fc2.length); i < max; i++) { if (fc1[i].uci !== fc2[i].uci) { if (cfg.onMyTurn) return i !== 0 && i % 2 === 0; return i % 2 === 1; @@ -74,9 +72,7 @@ export function make(cfg: ForecastData, data: AnalyseData, redraw: () => void): function isCandidate(fc: ForecastStep[]): boolean { fc = truncate(fc); if (!isLongEnough(fc)) return false; - var collisions = forecasts.filter(function (f) { - return contains(f, fc); - }); + const collisions = forecasts.filter(f => contains(f, fc)); if (collisions.length) return false; return true; } diff --git a/ui/analyse/src/forecast/forecastView.ts b/ui/analyse/src/forecast/forecastView.ts index c6c1563db6..db6db69966 100644 --- a/ui/analyse/src/forecast/forecastView.ts +++ b/ui/analyse/src/forecast/forecastView.ts @@ -6,11 +6,11 @@ import { bind, dataIcon, spinner } from '../util'; import { fixCrazySan } from 'chess'; function onMyTurn(ctrl: AnalyseCtrl, fctrl: ForecastCtrl, cNodes: ForecastStep[]): VNode | undefined { - var firstNode = cNodes[0]; + const firstNode = cNodes[0]; if (!firstNode) return; - var fcs = fctrl.findStartingWithNode(firstNode); + const fcs = fctrl.findStartingWithNode(firstNode); if (!fcs.length) return; - var lines = fcs.filter(function (fc) { + const lines = fcs.filter(function (fc) { return fc.length > 1; }); return h( diff --git a/ui/analyse/src/nodeFinder.ts b/ui/analyse/src/nodeFinder.ts index 609f5cbae1..fceffc48f1 100644 --- a/ui/analyse/src/nodeFinder.ts +++ b/ui/analyse/src/nodeFinder.ts @@ -16,7 +16,7 @@ export function nextGlyphSymbol( const len = mainline.length; if (!len) return; const fromIndex = fromPly - mainline[0].ply; - for (var i = 1; i < len; i++) { + for (let i = 1; i < len; i++) { const node = mainline[(fromIndex + i) % len]; const found = node.ply % 2 === (color === 'white' ? 1 : 0) && @@ -32,11 +32,11 @@ export function nextGlyphSymbol( export function evalSwings(mainline: Tree.Node[], nodeFilter: (node: Tree.Node) => boolean): Tree.Node[] { const found: Tree.Node[] = []; const threshold = 0.1; - for (var i = 1; i < mainline.length; i++) { - var node = mainline[i]; - var prev = mainline[i - 1]; + for (let i = 1; i < mainline.length; i++) { + const node = mainline[i]; + const prev = mainline[i - 1]; if (nodeFilter(node) && node.eval && prev.eval) { - var diff = Math.abs(winningChances.povDiff('white', prev.eval, node.eval)); + const diff = Math.abs(winningChances.povDiff('white', prev.eval, node.eval)); if (diff > threshold && hasCompChild(prev)) found.push(node); } } diff --git a/ui/analyse/src/pgnExport.ts b/ui/analyse/src/pgnExport.ts index b241ca3823..20dc5cb6c5 100644 --- a/ui/analyse/src/pgnExport.ts +++ b/ui/analyse/src/pgnExport.ts @@ -12,7 +12,7 @@ function renderNodesTxt(nodes: PgnNode[]): string { if (!nodes[0]) return ''; if (!nodes[0].san) nodes = nodes.slice(1); if (!nodes[0]) return ''; - var s = nodes[0].ply % 2 === 1 ? '' : Math.floor((nodes[0].ply + 1) / 2) + '... '; + let s = nodes[0].ply % 2 === 1 ? '' : Math.floor((nodes[0].ply + 1) / 2) + '... '; nodes.forEach(function (node, i) { if (node.ply === 0) return; if (node.ply % 2 === 1) s += (node.ply + 1) / 2 + '. '; @@ -23,9 +23,9 @@ function renderNodesTxt(nodes: PgnNode[]): string { } export function renderFullTxt(ctrl: AnalyseCtrl): string { - var g = ctrl.data.game; - var txt = renderNodesTxt(ctrl.tree.getNodeList(ctrl.path)); - var tags: Array<[string, string]> = []; + const g = ctrl.data.game; + let txt = renderNodesTxt(ctrl.tree.getNodeList(ctrl.path)); + const tags: Array<[string, string]> = []; if (g.variant.key !== 'standard') tags.push(['Variant', g.variant.name]); if (g.initialFen && g.initialFen !== initialFen) tags.push(['FEN', g.initialFen]); if (tags.length) diff --git a/ui/analyse/src/retrospect/retroCtrl.ts b/ui/analyse/src/retrospect/retroCtrl.ts index 4a2b8ef40e..d76a268ae5 100644 --- a/ui/analyse/src/retrospect/retroCtrl.ts +++ b/ui/analyse/src/retrospect/retroCtrl.ts @@ -116,11 +116,11 @@ export function make(root: AnalyseCtrl, color: Color): RetroCtrl { } function checkCeval(): void { - var node = root.node, + const node = root.node, cur = current(); if (!cur || feedback() !== 'eval' || cur.fault.node.ply !== node.ply) return; if (isCevalReady(node)) { - var diff = winningChances.povDiff(color, node.ceval!, cur.prev.node.eval); + const diff = winningChances.povDiff(color, node.ceval!, cur.prev.node.eval); if (diff > -0.035) onWin(); else onFail(); } diff --git a/ui/analyse/src/socket.ts b/ui/analyse/src/socket.ts index 1fc64ea255..a711b18d27 100644 --- a/ui/analyse/src/socket.ts +++ b/ui/analyse/src/socket.ts @@ -69,7 +69,7 @@ export function make(send: SocketSend, ctrl: AnalyseCtrl): Socket { } function addStudyData(req: Req, isWrite = false): void { - var c = currentChapterId(); + const c = currentChapterId(); if (c) { req.ch = c; if (isWrite) { diff --git a/ui/analyse/src/study/practice/studyPracticeSuccess.ts b/ui/analyse/src/study/practice/studyPracticeSuccess.ts index fdffdcc465..182e6ac758 100644 --- a/ui/analyse/src/study/practice/studyPracticeSuccess.ts +++ b/ui/analyse/src/study/practice/studyPracticeSuccess.ts @@ -17,7 +17,7 @@ function isWinning(node: Tree.Node, goalCp: number, color: Color): boolean | nul function myMateIn(node: Tree.Node, color: Color): number | boolean | null { if (!hasSolidEval(node)) return null; if (!node.ceval!.mate) return false; - var mateIn = node.ceval!.mate! * (color === 'white' ? 1 : -1); + const mateIn = node.ceval!.mate! * (color === 'white' ? 1 : -1); return mateIn > 0 ? mateIn : false; } diff --git a/ui/analyse/src/study/studyMembers.ts b/ui/analyse/src/study/studyMembers.ts index 6597ee3b16..e349709df2 100644 --- a/ui/analyse/src/study/studyMembers.ts +++ b/ui/analyse/src/study/studyMembers.ts @@ -161,7 +161,7 @@ export function view(ctrl: StudyCtrl): VNode { isOwner = members.isOwner(); function username(member: StudyMember) { - var u = member.user; + const u = member.user; return h( 'span.user-link.ulpt', { diff --git a/ui/analyse/src/util.ts b/ui/analyse/src/util.ts index 4526f9136f..81eea22584 100644 --- a/ui/analyse/src/util.ts +++ b/ui/analyse/src/util.ts @@ -152,13 +152,13 @@ export function toYouTubeEmbed(url: string): string | undefined { function toYouTubeEmbedUrl(url: string) { if (!url) return; - var m = url.match( + const m = url.match( /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch)?(?:\?v=)?([^"&?\/ ]{11})(?:\?|&|)(\S*)/i ); if (!m) return; - var start = 0; + let start = 0; m[2].split('&').forEach(function (p) { - var s = p.split('='); + const s = p.split('='); if (s[0] === 't' || s[0] === 'start') { if (s[1].match(/^\d+$/)) start = parseInt(s[1]); else { @@ -167,7 +167,7 @@ function toYouTubeEmbedUrl(url: string) { } } }); - var params = 'modestbranding=1&rel=0&controls=2&iv_load_policy=3' + (start ? '&start=' + start : ''); + const params = 'modestbranding=1&rel=0&controls=2&iv_load_policy=3' + (start ? '&start=' + start : ''); return 'https://www.youtube.com/embed/' + m[1] + '?' + params; } diff --git a/ui/challenge/src/ctrl.ts b/ui/challenge/src/ctrl.ts index b8890308d6..60b782378d 100644 --- a/ui/challenge/src/ctrl.ts +++ b/ui/challenge/src/ctrl.ts @@ -34,8 +34,8 @@ export default function (opts: ChallengeOpts, data: ChallengeData, redraw: () => } function showUser(user: ChallengeUser) { - var rating = user.rating + (user.provisional ? '?' : ''); - var fullName = (user.title ? user.title + ' ' : '') + user.name; + const rating = user.rating + (user.provisional ? '?' : ''); + const fullName = (user.title ? user.title + ' ' : '') + user.name; return fullName + ' (' + rating + ')'; } diff --git a/ui/cli/src/main.ts b/ui/cli/src/main.ts index 49090a26c9..89256113c1 100644 --- a/ui/cli/src/main.ts +++ b/ui/cli/src/main.ts @@ -24,7 +24,7 @@ function execute(q: string) { } function command(q: string) { - var parts = q.split(' '), + const parts = q.split(' '), exec = parts[0]; const is = function (commands: string) { diff --git a/ui/dasher/src/background.ts b/ui/dasher/src/background.ts index fa88346097..75e1c08305 100644 --- a/ui/dasher/src/background.ts +++ b/ui/dasher/src/background.ts @@ -131,7 +131,7 @@ function applyBackground(data: BackgroundData, list: Background[]) { sheet = key == 'darkBoard' ? 'dark' : key; $('body').data('theme', sheet); $('link[href*=".' + prev + '."]').each(function (this: HTMLLinkElement) { - var link = document.createElement('link') as HTMLLinkElement; + const link = document.createElement('link') as HTMLLinkElement; link.rel = 'stylesheet'; link.href = this.href.replace('.' + prev + '.', '.' + sheet + '.'); link.onload = () => setTimeout(() => this.remove(), 100); diff --git a/ui/dgt/src/play.ts b/ui/dgt/src/play.ts index f4c7b43227..bff5e18f0a 100644 --- a/ui/dgt/src/play.ts +++ b/ui/dgt/src/play.ts @@ -20,7 +20,7 @@ export default function (token: string) { : 'san'; const speechSynthesisOn = localStorage.getItem('dgt-speech-synthesis') == 'true'; const voice = localStorage.getItem('dgt-speech-voice'); - var keywords = { + let keywords = { K: 'King', Q: 'Queen', R: 'Rook', @@ -56,15 +56,15 @@ export default function (token: string) { /** * GLOBAL VARIABLES - Lichess Connectivity */ - var time = new Date(); //A Global time object - var currentGameId = ''; //Track which is the current Game, in case there are several open games - var currentGameColor = ''; //Track which color is being currently played by the player. 'white' or 'black' - var me: { id: string; username: string }; //Track my information - var gameInfoMap = new Map(); //A collection of key values to store game immutable information of all open games - var gameStateMap = new Map(); //A collection of key values to store the changing state of all open games - var gameConnectionMap = new Map(); //A collection of key values to store the network status of a game - var gameChessBoardMap = new Map(); //A collection of chessops Boards representing the current board of the games - var eventSteamStatus = { connected: false, lastEvent: time.getTime() }; //An object to store network status of the main eventStream + const time = new Date(); //A Global time object + let currentGameId = ''; //Track which is the current Game, in case there are several open games + let currentGameColor = ''; //Track which color is being currently played by the player. 'white' or 'black' + let me: { id: string; username: string }; //Track my information + const gameInfoMap = new Map(); //A collection of key values to store game immutable information of all open games + const gameStateMap = new Map(); //A collection of key values to store the changing state of all open games + const gameConnectionMap = new Map(); //A collection of key values to store the network status of a game + const gameChessBoardMap = new Map(); //A collection of chessops Boards representing the current board of the games + let eventSteamStatus = { connected: false, lastEvent: time.getTime() }; //An object to store network status of the main eventStream const keywordsBase = [ 'white', 'black', @@ -86,20 +86,20 @@ export default function (token: string) { 'illegal', 'move', ]; - var lastSanMove: { player: string; move: string; by: string }; //Track last move in SAN format. This is because there is no easy way to keep history of san moves + let lastSanMove: { player: string; move: string; by: string }; //Track last move in SAN format. This is because there is no easy way to keep history of san moves /** * Global Variables for DGT Board Connection (JACM) */ - var localBoard: Chess = startingPosition(); //Board with valid moves played on Lichess and DGT Board. May be half move behind Lichess or half move in advance - var DGTgameId = ''; //Used to track if DGT board was setup already with the lichess currentGameId - var boards = Array<{ serialnr: string; state: string }>(); //An array to store all the board recognized by DGT LiveChess - var liveChessConnection: WebSocket; //Connection Object to LiveChess through websocket - var isLiveChessConnected = false; //Used to track if a board there is a connection to DGT Live Chess - var currentSerialnr = '0'; //Public property to store the current serial number of the DGT Board in case there is more than one + let localBoard: Chess = startingPosition(); //Board with valid moves played on Lichess and DGT Board. May be half move behind Lichess or half move in advance + let DGTgameId = ''; //Used to track if DGT board was setup already with the lichess currentGameId + let boards = Array<{ serialnr: string; state: string }>(); //An array to store all the board recognized by DGT LiveChess + let liveChessConnection: WebSocket; //Connection Object to LiveChess through websocket + let isLiveChessConnected = false; //Used to track if a board there is a connection to DGT Live Chess + let currentSerialnr = '0'; //Public property to store the current serial number of the DGT Board in case there is more than one //subscription stores the information about the board being connected, most importantly the serialnr - var subscription = { id: 2, call: 'subscribe', param: { feed: 'eboardevent', id: 1, param: { serialnr: '' } } }; - var lastLegalParam: { board: string; san: string[] }; //This can help prevent duplicate moves from LiveChess being detected as move from the other side, like a duplicate O-O - var lastLiveChessBoard: string; //Store last Board received by LiveChess + const subscription = { id: 2, call: 'subscribe', param: { feed: 'eboardevent', id: 1, param: { serialnr: '' } } }; + let lastLegalParam: { board: string; san: string[] }; //This can help prevent duplicate moves from LiveChess being detected as move from the other side, like a duplicate O-O + let lastLiveChessBoard: string; //Store last Board received by LiveChess /*** * Bind console output to HTML pre Element */ @@ -121,7 +121,7 @@ export default function (token: string) { console[name] = function () { //Return a promise so execution is not delayed by string manipulation return new Promise(resolve => { - var output = ''; + let output = ''; for (let i = 0; i < arguments.length; i++) { const arg = arguments[i]; if (arg == '*' || arg == ':') { @@ -236,12 +236,12 @@ export default function (token: string) { //Update connection status eventSteamStatus = { connected: true, lastEvent: time.getTime() }; //Response may contain several JSON objects on the same chunk separated by \n . This may create an empty element at the end. - var jsonArray = value ? decoder.decode(value).split('\n') : []; + const jsonArray = value ? decoder.decode(value).split('\n') : []; for (let i = 0; i < jsonArray.length; i++) { //Skip empty elements that may have happened witht the .split('\n') if (jsonArray[i].length > 2) { try { - var data = JSON.parse(jsonArray[i]); + const data = JSON.parse(jsonArray[i]); //JSON data found, let's check if this is a game that started. field type is mandatory except on http 4xx if (data.type == 'gameStart') { if (verbose) console.log('connectToEventStream - gameStart event arrived. GameId: ' + data.game.id); @@ -333,12 +333,12 @@ export default function (token: string) { //Update connection status gameConnectionMap.set(gameId, { connected: true, lastEvent: time.getTime() }); //Response may contain several JSON objects on the same chunk separated by \n . This may create an empty element at the end. - var jsonArray = decoder.decode(value)!.split('\n'); + const jsonArray = decoder.decode(value)!.split('\n'); for (let i = 0; i < jsonArray.length; i++) { //Skip empty elements that may have happened witht the .split('\n') if (jsonArray[i].length > 2) { try { - var data = JSON.parse(jsonArray[i]); + const data = JSON.parse(jsonArray[i]); //The first line is always of type gameFull. if (data.type == 'gameFull') { if (!verbose) console.clear(); @@ -397,7 +397,7 @@ export default function (token: string) { */ function formattedTimer(timer: number): string { // Pad function to pad with 0 to 2 or 3 digits, default is 2 - var pad = (n: number, z = 2) => `00${n}`.slice(-z); + const pad = (n: number, z = 2) => `00${n}`.slice(-z); return pad((timer / 3.6e6) | 0) + ':' + pad(((timer % 3.6e6) / 6e4) | 0) + ':' + pad(((timer % 6e4) / 1000) | 0); //+ '.' + pad(timer % 1000, 3); } @@ -438,7 +438,7 @@ export default function (token: string) { async function chooseCurrentGame() { //Determine new value for currentGameId. First create an array with only the started games //So then there is none or more than one started game - var playableGames = playableGamesArray(); + const playableGames = playableGamesArray(); //If there is only one started game, then its easy /* if (playableGames.length == 1) { @@ -521,16 +521,16 @@ export default function (token: string) { */ function initializeChessBoard(gameId: string, data: { initialFen: string; state: { moves: string } }) { try { - var initialFen: string = INITIAL_FEN; + let initialFen: string = INITIAL_FEN; if (data.initialFen != 'startpos') initialFen = data.initialFen; - var setup = parseFen(initialFen).unwrap(); - var chess: Chess = Chess.fromSetup(setup).unwrap(); - var moves = data.state.moves.split(' '); + const setup = parseFen(initialFen).unwrap(); + const chess: Chess = Chess.fromSetup(setup).unwrap(); + const moves = data.state.moves.split(' '); for (let i = 0; i < moves.length; i++) { if (moves[i] != '') { //Make any move that may have been already played on the ChessBoard. Useful when reconnecting - var uciMove = parseUci(moves[i]); - var normalizedMove = chess.normalizeMove(uciMove); //This is because chessops uses UCI_960 + const uciMove = parseUci(moves[i]); + const normalizedMove = chess.normalizeMove(uciMove); //This is because chessops uses UCI_960 if (normalizedMove && chess.isLegal(normalizedMove)) chess.play(normalizedMove); } } @@ -553,9 +553,9 @@ export default function (token: string) { */ function updateChessBoard(gameId: string, currentState: { moves: string }, newState: { moves: string }) { try { - var chess = gameChessBoardMap.get(gameId); + const chess = gameChessBoardMap.get(gameId); if (chess) { - var pendingMoves: string; + let pendingMoves: string; if (!currentState.moves) { //No prior moves. Use the new moves pendingMoves = newState.moves; @@ -563,12 +563,12 @@ export default function (token: string) { //Get all the moves on the newState that are not present on the currentState pendingMoves = newState.moves.substring(currentState.moves.length, newState.moves.length); } - var moves = pendingMoves.split(' '); + const moves = pendingMoves.split(' '); for (let i = 0; i < moves.length; i++) { if (moves[i] != '') { //Make the new move - var uciMove = parseUci(moves[i]); - var normalizedMove = chess.normalizeMove(uciMove); //This is because chessops uses UCI_960 + const uciMove = parseUci(moves[i]); + const normalizedMove = chess.normalizeMove(uciMove); //This is because chessops uses UCI_960 if (normalizedMove && chess.isLegal(normalizedMove)) { //This is a good chance to get the move in SAN format if (chess.turn == 'black') @@ -622,7 +622,7 @@ export default function (token: string) { Timer: string; 'Last Move': string; }> { - var playableGames: Array<{ + const playableGames: Array<{ gameId: string; versus: string; 'vs rating': string; @@ -630,17 +630,17 @@ export default function (token: string) { Timer: string; 'Last Move': string; }> = []; - var keys = Array.from(gameConnectionMap.keys()); + const keys = Array.from(gameConnectionMap.keys()); //The for each iterator is not used since we don't want to continue execution. We want a synchronous result //for (let [gameId, networkState] of gameConnectionMap) { // if (gameConnectionMap.get(gameId).connected && gameStateMap.get(gameId).status == "started") { - for (var i = 0; i < keys.length; i++) { + for (let i = 0; i < keys.length; i++) { if (gameConnectionMap.get(keys[i])?.connected && gameStateMap.get(keys[i])?.status == 'started') { //Game is good for commands - var gameInfo = gameInfoMap.get(keys[i]); + const gameInfo = gameInfoMap.get(keys[i]); //var gameState = gameStateMap.get(keys[i]); - var lastMove = getLastUCIMove(keys[i]); - var versus = + const lastMove = getLastUCIMove(keys[i]); + const versus = gameInfo.black.id == me.id ? (gameInfo.white.title !== null ? gameInfo.white.title : '@') + ' ' + gameInfo.white.name : (gameInfo.black.title !== null ? gameInfo.black.title : '@') + ' ' + gameInfo.black.name; @@ -669,9 +669,9 @@ export default function (token: string) { */ function logGameState(gameId: string) { if (gameStateMap.has(gameId) && gameInfoMap.has(gameId)) { - var gameInfo = gameInfoMap.get(gameId); - var gameState = gameStateMap.get(gameId); - var lastMove = getLastUCIMove(gameId); + const gameInfo = gameInfoMap.get(gameId); + const gameState = gameStateMap.get(gameId); + const lastMove = getLastUCIMove(gameId); console.log(''); //process.stdout.write("\n"); Changed to support browser /* Log before migrating to browser if (verbose) console.table({ @@ -682,7 +682,7 @@ export default function (token: string) { 'Last Move': { white: (lastMove.player == 'white' ? lastMove.move : '?'), black: (lastMove.player == 'black' ? lastMove.move : '?'), game: lastMove.player }, }); */ - var innerTable = + const innerTable = `` + `
- TitleUsernameRatingTimerLast MovegameId: ${gameInfo.id}
White${gameInfo.white.title !== null ? gameInfo.white.title : '@'}${ gameInfo.white.name @@ -747,11 +747,11 @@ export default function (token: string) { */ function getLastUCIMove(gameId: string): { player: string; move: string; by: string } { if (gameStateMap.has(gameId) && gameInfoMap.has(gameId)) { - var gameInfo = gameInfoMap.get(gameId); - var gameState = gameStateMap.get(gameId); + const gameInfo = gameInfoMap.get(gameId); + const gameState = gameStateMap.get(gameId); //This is the original code that does not used chessops objects and can be used to get the UCI move but not SAN. if (String(gameState.moves).length > 1) { - var moves = gameState.moves.split(' '); + const moves = gameState.moves.split(' '); if (verbose) console.log(`getLastUCIMove - ${moves.length} moves detected. Last one: ${moves[moves.length - 1]}`); if (moves.length % 2 == 0) return { player: 'black', move: moves[moves.length - 1], by: gameInfo.black.id }; @@ -772,7 +772,7 @@ export default function (token: string) { function announcePlay(lastMove: { player: string; move: string; by: string }) { //ttsSay(lastMove.player); //Now play it using text to speech library - var moveText: string; + let moveText: string; if (announceMoveFormat && announceMoveFormat.toLowerCase() == 'san' && lastSanMove) { moveText = lastSanMove.move; ttsSay(replaceKeywords(padBeforeNumbers(lastSanMove.move))); @@ -810,7 +810,7 @@ export default function (token: string) { } async function connectToLiveChess() { - var SANMove: string; //a move in san format returned by liveChess + let SANMove: string; //a move in san format returned by liveChess //Open the WebSocket liveChessConnection = new WebSocket(liveChessURL ? liveChessURL : 'ws://localhost:1982/api/v1.0'); @@ -836,7 +836,7 @@ export default function (token: string) { liveChessConnection.onmessage = async e => { if (verbose) console.info('Websocket onmessage with data:' + e.data); - var message = JSON.parse(e.data); + const message = JSON.parse(e.data); //Store last board if received if (message.response == 'feed' && !!message.param.board) { lastLiveChessBoard = message.param.board; @@ -877,7 +877,7 @@ export default function (token: string) { //Received move from board if (verbose) console.info('onmessage - san: ' + message.param.san); //get last move known to lichess and avoid calling multiple times this function - var lastMove = getLastUCIMove(currentGameId); + const lastMove = getLastUCIMove(currentGameId); if (message.param.san.length == 0) { if (verbose) console.info('onmessage - san is empty'); } else if ( @@ -891,7 +891,7 @@ export default function (token: string) { //A move was received //Get all the moves on the param.san that are not present on lastLegalParam.san //it is possible to receive two new moves on the message. Don't assume only the last move is pending. - var movesToProcess = 1; + let movesToProcess = 1; if (lastLegalParam !== undefined) movesToProcess = message.param.san.length - lastLegalParam.san.length; //Check border case in which DGT Board LiveChess detects the wrong move while pieces are still on the air if (movesToProcess > 1) { @@ -900,7 +900,7 @@ export default function (token: string) { if (localBoard.turn == currentGameColor) { //If more than one move is received when its the DGT board player's turn this may be a invalid move //Move will be quarentined by 2.5 seconds - var quarentinedlastLegalParam = lastLegalParam; + const quarentinedlastLegalParam = lastLegalParam; await sleep(2500); //Check if a different move was recevied and processed during quarentine if (JSON.stringify(lastLegalParam.san) != JSON.stringify(quarentinedlastLegalParam.san)) { @@ -1027,8 +1027,8 @@ export default function (token: string) { * @param chess - The chessops Chess object with the position on Lichess */ async function sendBoardToLiveChess(chess: Chess) { - var fen = makeFen(chess.toSetup()); - var setupMessage = { + const fen = makeFen(chess.toSetup()); + const setupMessage = { id: 3, call: 'call', param: { @@ -1080,7 +1080,7 @@ export default function (token: string) { await chooseCurrentGame(); } //Now send the move - var command = makeUci(boardMove); + const command = makeUci(boardMove); sendMove(currentGameId, command); } @@ -1100,7 +1100,7 @@ export default function (token: string) { if (uciMove.length > 1) { //Log intention //Automatically decline draws when making a move - var url = `/api/board/game/${gameId}/move/${uciMove}?offeringDraw=false`; + const url = `/api/board/game/${gameId}/move/${uciMove}?offeringDraw=false`; if (verbose) console.log('sendMove - About to call ' + url); fetch(url, { method: 'POST', @@ -1133,7 +1133,7 @@ export default function (token: string) { * @returns {String} - The San move with words instead of letters */ function replaceKeywords(sanMove) { - var extendedSanMove = sanMove; + let extendedSanMove = sanMove; for (let i = 0; i < keywordsBase.length; i++) { try { extendedSanMove = extendedSanMove.replace(keywordsBase[i], ' ' + keywords[keywordsBase[i]].toLowerCase() + ' '); @@ -1151,7 +1151,7 @@ export default function (token: string) { * @returns {String} - The move with spaces before the numbers for better TTS */ function padBeforeNumbers(moveString: string) { - var paddedMoveString = ''; + let paddedMoveString = ''; for (const c of moveString) { Number.isInteger(+c) ? (paddedMoveString += ` ${c} `) : (paddedMoveString += c); } @@ -1165,9 +1165,9 @@ export default function (token: string) { //Check if Voice is disabled if (verbose) console.log('TTS - for text: ' + text); if (!speechSynthesisOn) return; - var utterThis = new SpeechSynthesisUtterance(text); - var selectedOption = voice; - var availableVoices = speechSynthesis.getVoices(); + const utterThis = new SpeechSynthesisUtterance(text); + const selectedOption = voice; + const availableVoices = speechSynthesis.getVoices(); for (let i = 0; i < availableVoices.length; i++) { if (availableVoices[i].name === selectedOption) { utterThis.voice = availableVoices[i]; @@ -1192,14 +1192,14 @@ export default function (token: string) { */ function compareMoves(lastMove: string, moveObject: NormalMove): boolean { try { - var uciMove = makeUci(moveObject); + const uciMove = makeUci(moveObject); if (verbose) console.log(`Comparing ${lastMove} with ${uciMove}`); if (lastMove == uciMove) { //it's the same move return true; } if (verbose) console.log('Moves look different. Check if this is a castling mismatch.'); - var castlingSide = localBoard.castlingSide(moveObject); + const castlingSide = localBoard.castlingSide(moveObject); if (lastMove.length > 2 && castlingSide) { //It was a castling so it still may be the same move if (lastMove.startsWith(uciMove.substring(0, 2))) { diff --git a/ui/lobby/src/setup.ts b/ui/lobby/src/setup.ts index 1abe629599..af66b3b9f4 100644 --- a/ui/lobby/src/setup.ts +++ b/ui/lobby/src/setup.ts @@ -315,7 +315,7 @@ export default class Setup { }); }); $daysInput.each(function (this: HTMLInputElement) { - var $input = $(this), + const $input = $(this), $value = $input.siblings('span'), $range = $input.siblings('.range'); $value.text($input.val() as string); @@ -370,7 +370,7 @@ export default class Setup { } $timeModeSelect .on('change', function (this: HTMLElement) { - var timeMode = $(this).val(); + const timeMode = $(this).val(); $form.find('.time_choice, .increment_choice').toggle(timeMode == '1'); $form.find('.days_choice').toggle(timeMode == '2'); toggleButtons(); @@ -378,11 +378,11 @@ export default class Setup { }) .trigger('change'); - var validateFen = debounce(() => { + const validateFen = debounce(() => { $fenInput.removeClass('success failure'); - var fen = $fenInput.val() as string; + const fen = $fenInput.val() as string; if (fen) { - var [path, params] = $fenInput.parent().data('validate-url').split('?'); // Separate "strict=1" for AI match + const [path, params] = $fenInput.parent().data('validate-url').split('?'); // Separate "strict=1" for AI match xhr.text(xhr.url(path, { fen }) + (params ? `&${params}` : '')).then( data => { $fenInput.addClass('success'); @@ -406,7 +406,7 @@ export default class Setup { if (forceFormPosition) $variantSelect.val('' + 3); $variantSelect .on('change', function (this: HTMLElement) { - var isFen = $(this).val() == '3'; + const isFen = $(this).val() == '3'; $fenPosition.toggle(isFen); $modeChoicesWrap.toggle(!isFen); if (isFen) { @@ -421,7 +421,7 @@ export default class Setup { $modeChoices.on('change', save); $form.find('div.level').each(function (this: HTMLElement) { - var $infos = $(this).find('.ai_info > div'); + const $infos = $(this).find('.ai_info > div'); $(this) .find('label') .on('mouseenter', function (this: HTMLElement) { @@ -433,7 +433,7 @@ export default class Setup { $(this) .find('#config_level') .on('mouseleave', function (this: HTMLElement) { - var level = $(this).find('input:checked').val(); + const level = $(this).find('input:checked').val(); $infos .hide() .filter('.sf_level_' + level) diff --git a/ui/notify/src/renderers.ts b/ui/notify/src/renderers.ts index 6b97717076..06eb4dbc64 100644 --- a/ui/notify/src/renderers.ts +++ b/ui/notify/src/renderers.ts @@ -167,7 +167,7 @@ function generic(n: Notification, url: string | undefined, icon: string, content } function drawTime(n: Notification) { - var date = new Date(n.date); + const date = new Date(n.date); return h( 'time.timeago', { diff --git a/ui/nvui/src/chess.ts b/ui/nvui/src/chess.ts index 3f925e8f08..dc3030a949 100644 --- a/ui/nvui/src/chess.ts +++ b/ui/nvui/src/chess.ts @@ -204,7 +204,7 @@ export function lastCaptured(movesGenerator: () => string[], pieceStyle: PieceSt } const oldSplitFen = oldFen.split(' ')[0]; const newSplitFen = newFen.split(' ')[0]; - for (var p of 'kKqQrRbBnNpP') { + for (const p of 'kKqQrRbBnNpP') { const diff = oldSplitFen.split(p).length - 1 - (newSplitFen.split(p).length - 1); const pcolor = p.toUpperCase() === p ? 'white' : 'black'; if (diff === 1) { diff --git a/ui/puzzle/src/view/side.ts b/ui/puzzle/src/view/side.ts index 972eda69c6..b1314afb33 100644 --- a/ui/puzzle/src/view/side.ts +++ b/ui/puzzle/src/view/side.ts @@ -5,7 +5,7 @@ import { numberFormat } from 'common/number'; import PuzzleStreak from '../streak'; export function puzzleBox(ctrl: Controller): VNode { - var data = ctrl.getData(); + const data = ctrl.getData(); return h('div.puzzle__side__metas', [puzzleInfos(ctrl, data.puzzle), gameInfos(ctrl, data.game, data.puzzle)]); } diff --git a/ui/puzzle/src/view/tree.ts b/ui/puzzle/src/view/tree.ts index 12457b5fd3..5e3a0fe7a7 100644 --- a/ui/puzzle/src/view/tree.ts +++ b/ui/puzzle/src/view/tree.ts @@ -21,8 +21,8 @@ interface Glyph { } const autoScroll = throttle(150, (ctrl: Controller, el) => { - var cont = el.parentNode; - var target = el.querySelector('.active'); + const cont = el.parentNode; + const target = el.querySelector('.active'); if (!target) { cont.scrollTop = ctrl.vm.path === treePath.root ? 0 : 99999; return; diff --git a/ui/round/src/plugins/sanWriter.ts b/ui/round/src/plugins/sanWriter.ts index 402c907e59..d381a5fd3c 100644 --- a/ui/round/src/plugins/sanWriter.ts +++ b/ui/round/src/plugins/sanWriter.ts @@ -14,9 +14,9 @@ function square(name: string) { } function squareDist(a: number, b: number) { - var x1 = a & 7, + const x1 = a & 7, x2 = b & 7; - var y1 = a >> 3, + const y1 = a >> 3, y2 = b >> 3; return Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)); } @@ -63,15 +63,15 @@ function knightMovesTo(s: number) { }); } -var ROOK_DELTAS = [8, 1, -8, -1]; -var BISHOP_DELTAS = [9, -9, 7, -7]; -var QUEEN_DELTAS = ROOK_DELTAS.concat(BISHOP_DELTAS); +const ROOK_DELTAS = [8, 1, -8, -1]; +const BISHOP_DELTAS = [9, -9, 7, -7]; +const QUEEN_DELTAS = ROOK_DELTAS.concat(BISHOP_DELTAS); function slidingMovesTo(s: number, deltas: number[], board: Board): number[] { - var result: number[] = []; + const result: number[] = []; deltas.forEach(function (delta) { for ( - var square = s + delta; + let square = s + delta; square >= 0 && square < 64 && squareDist(square, square - delta) === 1; square += delta ) { @@ -85,12 +85,12 @@ function slidingMovesTo(s: number, deltas: number[], board: Board): number[] { function sanOf(board: Board, uci: string) { if (uci.includes('@')) return fixCrazySan(uci); - var move = decomposeUci(uci); - var from = square(move[0]); - var to = square(move[1]); - var p = board.pieces[from]; - var d = board.pieces[to]; - var pt = board.pieces[from].toLowerCase(); + const move = decomposeUci(uci); + const from = square(move[0]); + const to = square(move[1]); + const p = board.pieces[from]; + const d = board.pieces[to]; + const pt = board.pieces[from].toLowerCase(); // pawn moves if (pt === 'p') { @@ -110,16 +110,16 @@ function sanOf(board: Board, uci: string) { var san = pt.toUpperCase(); // disambiguate normal moves - var candidates: number[] = []; + let candidates: number[] = []; if (pt == 'k') candidates = kingMovesTo(to); else if (pt == 'n') candidates = knightMovesTo(to); else if (pt == 'r') candidates = slidingMovesTo(to, ROOK_DELTAS, board); else if (pt == 'b') candidates = slidingMovesTo(to, BISHOP_DELTAS, board); else if (pt == 'q') candidates = slidingMovesTo(to, QUEEN_DELTAS, board); - var rank = false, + let rank = false, file = false; - for (var i = 0; i < candidates.length; i++) { + for (let i = 0; i < candidates.length; i++) { if (candidates[i] === from || board.pieces[candidates[i]] !== p) continue; if (from >> 3 === candidates[i] >> 3) file = true; if ((from & 7) === (candidates[i] & 7)) rank = true; @@ -135,10 +135,10 @@ function sanOf(board: Board, uci: string) { } export function sanWriter(fen: string, ucis: string[]): SanToUci { - var board = readFen(fen); - var sans: SanToUci = {}; + const board = readFen(fen); + const sans: SanToUci = {}; ucis.forEach(function (uci) { - var san = sanOf(board, uci); + const san = sanOf(board, uci); sans[san] = uci; if (san.includes('x')) sans[san.replace('x', '')] = uci; }); diff --git a/ui/round/src/promotion.ts b/ui/round/src/promotion.ts index 5622f50add..e5c58a4453 100644 --- a/ui/round/src/promotion.ts +++ b/ui/round/src/promotion.ts @@ -110,9 +110,9 @@ function renderPromotion( color: Color, orientation: Color ): MaybeVNode { - var left = (7 - key2pos(dest)[0]) * 12.5; + let left = (7 - key2pos(dest)[0]) * 12.5; if (orientation === 'white') left = 87.5 - left; - var vertical = color === orientation ? 'top' : 'bottom'; + const vertical = color === orientation ? 'top' : 'bottom'; return h( 'div#promotion-choice.' + vertical, @@ -126,7 +126,7 @@ function renderPromotion( }), }, roles.map((serverRole, i) => { - var top = (color === orientation ? i : 7 - i) * 12.5; + const top = (color === orientation ? i : 7 - i) * 12.5; return h( 'square', { diff --git a/ui/site/src/checkout.ts b/ui/site/src/checkout.ts index 2f47645054..b45a1b56c4 100644 --- a/ui/site/src/checkout.ts +++ b/ui/site/src/checkout.ts @@ -1,12 +1,12 @@ import * as xhr from 'common/xhr'; export default function (publicKey: string) { - var $checkout = $('div.plan_checkout'); - var lifetime = { + const $checkout = $('div.plan_checkout'); + const lifetime = { cents: parseInt($checkout.data('lifetime-cents')), usd: $checkout.data('lifetime-usd'), }; - var min = 100, + const min = 100, max = 100 * 100000; if (location.hash === '#onetime') $('#freq_onetime').trigger('click'); @@ -22,7 +22,7 @@ export default function (publicKey: string) { $checkout.find('#plan_monthly_1000').trigger('click'); const selectAmountGroup = function () { - var freq = getFreq(); + const freq = getFreq(); $checkout.find('.amount_fixed').toggleClass('none', freq != 'lifetime'); $checkout.find('.amount_choice').toggleClass('none', freq == 'lifetime'); }; @@ -38,7 +38,7 @@ export default function (publicKey: string) { } catch (e) { return false; } - var cents = Math.round(amount * 100); + let cents = Math.round(amount * 100); if (!cents) { $(this).text($(this).data('trans-other')); $checkout.find('#plan_monthly_1000').trigger('click'); @@ -46,7 +46,7 @@ export default function (publicKey: string) { } if (cents < min) cents = min; else if (cents > max) cents = max; - var usd = '$' + cents / 100; + const usd = '$' + cents / 100; $(this).text(usd); $(this).siblings('input').data('amount', cents).data('usd', usd); }); @@ -56,8 +56,8 @@ export default function (publicKey: string) { cents = freq == 'lifetime' ? lifetime.cents : parseInt($checkout.find('group.amount input:checked').data('amount')); if (!cents || cents < min || cents > max) return; - var amount = cents / 100; - var $form = $checkout.find('form.paypal_checkout.' + freq); + const amount = cents / 100; + const $form = $checkout.find('form.paypal_checkout.' + freq); $form.find('input.amount').val('' + amount); ($form[0] as HTMLFormElement).submit(); $checkout.find('.service').html(lichess.spinnerHtml); diff --git a/ui/site/src/coachForm.ts b/ui/site/src/coachForm.ts index afbeda1af7..f103a9ae31 100644 --- a/ui/site/src/coachForm.ts +++ b/ui/site/src/coachForm.ts @@ -5,14 +5,14 @@ import spinnerHtml from './component/spinner'; import Tagify from '@yaireo/tagify'; lichess.load.then(() => { - var $editor = $('.coach-edit'); + const $editor = $('.coach-edit'); - var todo = (function () { - var $overview = $editor.find('.overview'); - var $el = $overview.find('.todo'); - var $listed = $editor.find('#form3-listed'); + const todo = (function () { + const $overview = $editor.find('.overview'); + const $el = $overview.find('.todo'); + const $listed = $editor.find('#form3-listed'); - var must = [ + const must = [ { html: 'Complete your lichess profile', check() { @@ -50,7 +50,7 @@ lichess.load.then(() => { const points: Cash[] = must.filter(o => !o.check()).map(o => $('
  • ').html(o.html)); const $ul = $el.find('ul').empty(); points.forEach(p => $ul.append(p)); - var fail = !!points.length; + const fail = !!points.length; $overview.toggleClass('with-todo', fail); if (fail) $listed.prop('checked', false); $listed.prop('disabled', fail); diff --git a/ui/site/src/coordinate.ts b/ui/site/src/coordinate.ts index 605120d2ec..a0fc63ebae 100644 --- a/ui/site/src/coordinate.ts +++ b/ui/site/src/coordinate.ts @@ -3,24 +3,24 @@ import sparkline from '@fnando/sparkline'; lichess.load.then(() => { $('#trainer').each(function (this: HTMLElement) { - var $trainer = $(this); - var $board = $('.coord-trainer__board .cg-wrap'); - var ground; - var $side = $('.coord-trainer__side'); - var $right = $('.coord-trainer__table'); - var $bar = $trainer.find('.progress_bar'); - var $coords = [$('#next_coord0'), $('#next_coord1'), $('#next_coord2')]; - var $start = $right.find('.start'); - var $explanation = $right.find('.explanation'); - var $score = $('.coord-trainer__score'); - var scoreUrl = $trainer.data('score-url'); - var duration = 30 * 1000; - var tickDelay = 50; - var colorPref = $trainer.data('color-pref'); - var color; - var startAt, score; + const $trainer = $(this); + const $board = $('.coord-trainer__board .cg-wrap'); + let ground; + const $side = $('.coord-trainer__side'); + const $right = $('.coord-trainer__table'); + const $bar = $trainer.find('.progress_bar'); + const $coords = [$('#next_coord0'), $('#next_coord1'), $('#next_coord2')]; + const $start = $right.find('.start'); + const $explanation = $right.find('.explanation'); + const $score = $('.coord-trainer__score'); + const scoreUrl = $trainer.data('score-url'); + const duration = 30 * 1000; + const tickDelay = 50; + let colorPref = $trainer.data('color-pref'); + let color; + let startAt, score; - var showColor = function () { + const showColor = function () { color = colorPref == 'random' ? ['white', 'black'][Math.round(Math.random())] : colorPref; if (!ground) ground = window.Chessground($board[0], { @@ -42,8 +42,8 @@ lichess.load.then(() => { const form = this, $form = $(this); $form.find('input').on('change', function () { - var selected = $form.find('input:checked').val() as string; - var c = { + const selected = $form.find('input:checked').val() as string; + const c = { 1: 'white', 2: 'random', 3: 'black', @@ -85,25 +85,25 @@ lichess.load.then(() => { } requestAnimationFrame(showCharts); - var centerRight = function () { + const centerRight = function () { $right.css('top', 256 - $right.height() / 2 + 'px'); }; centerRight(); - var clearCoords = function () { + const clearCoords = function () { $.each($coords, function (_, e) { e.text(''); }); }; - var newCoord = function (prevCoord) { + const newCoord = function (prevCoord) { // disallow the previous coordinate's row or file from being selected - var files = 'abcdefgh'; - var fileIndex = files.indexOf(prevCoord[0]); + let files = 'abcdefgh'; + const fileIndex = files.indexOf(prevCoord[0]); files = files.slice(0, fileIndex) + files.slice(fileIndex + 1, 8); - var rows = '12345678'; - var rowIndex = rows.indexOf(prevCoord[1]); + let rows = '12345678'; + const rowIndex = rows.indexOf(prevCoord[1]); rows = rows.slice(0, rowIndex) + rows.slice(rowIndex + 1, 8); return ( @@ -111,9 +111,9 @@ lichess.load.then(() => { ); }; - var advanceCoords = function () { + const advanceCoords = function () { $('#next_coord0').removeClass('nope'); - var lastElement = $coords.shift()!; + const lastElement = $coords.shift()!; $.each($coords, function (i, e) { e.attr('id', 'next_coord' + i); }); @@ -122,7 +122,7 @@ lichess.load.then(() => { $coords.push(lastElement); }; - var stop = function () { + const stop = function () { clearCoords(); $trainer.removeClass('play'); centerRight(); @@ -145,7 +145,7 @@ lichess.load.then(() => { }; var tick = function () { - var spent = Math.min(duration, new Date().getTime() - startAt); + const spent = Math.min(duration, new Date().getTime() - startAt); $bar.css('width', (100 * spent) / duration + '%'); if (spent < duration) setTimeout(tick, tickDelay); else stop(); @@ -165,7 +165,7 @@ lichess.load.then(() => { ground.set({ events: { select(key) { - var hit = key == $coords[0].text(); + const hit = key == $coords[0].text(); if (hit) { score++; $score.text(score); @@ -181,7 +181,7 @@ lichess.load.then(() => { }, }); $coords[0].text(newCoord('a1')); - var i; + let i; for (i = 1; i < $coords.length; i++) $coords[i].text(newCoord($coords[i - 1].text())); tick(); }, 1000); diff --git a/ui/site/src/expandText.ts b/ui/site/src/expandText.ts index e9ef90937d..d96576cd93 100644 --- a/ui/site/src/expandText.ts +++ b/ui/site/src/expandText.ts @@ -60,7 +60,7 @@ lichess.load.then(() => { }; matches = a.href.match(gameRegex); if (matches && matches[1] && !notGames.includes(matches[1]) && a.text.match(gameRegex)) { - var src = '/embed/' + matches[1]; + let src = '/embed/' + matches[1]; if (matches[2]) src += '/' + matches[2]; // orientation if (matches[3]) src += matches[3]; // ply hash return { @@ -71,7 +71,7 @@ lichess.load.then(() => { } function expandYoutube(a: Candidate) { - var $iframe = $('
    '); + const $iframe = $('
    '); $(a.element).replaceWith($iframe); return $iframe; } diff --git a/ui/site/src/forum.ts b/ui/site/src/forum.ts index 83852c4914..7f510e15c8 100644 --- a/ui/site/src/forum.ts +++ b/ui/site/src/forum.ts @@ -53,7 +53,7 @@ lichess.load.then(() => { // Initially we only autocomplete by participants in the thread. As the user types more, // we can autocomplete against all users on the site. threadParticipants.then(function (participants) { - var forumParticipantCandidates = searchCandidates(term, participants); + const forumParticipantCandidates = searchCandidates(term, participants); if (forumParticipantCandidates.length != 0) { // We always prefer a match on the forum thread partcipants' usernames diff --git a/ui/site/src/gameSearch.ts b/ui/site/src/gameSearch.ts index 96eb58c16a..e19244feb6 100644 --- a/ui/site/src/gameSearch.ts +++ b/ui/site/src/gameSearch.ts @@ -15,9 +15,9 @@ lichess.load.then(() => { } function userChoices(row) { - var options = [""]; - var isSelected = function (row, rowClassName, user, dataKey) { - var player = $form.data(dataKey); + const options = [""]; + const isSelected = function (row, rowClassName, user, dataKey) { + const player = $form.data(dataKey); return row.classList.contains(rowClassName) && player.length && user == player ? 'selected' : ''; }; getUsernames().forEach(function (user) { @@ -42,7 +42,7 @@ lichess.load.then(() => { reloadUserChoices(); $usernames.on('input paste', reloadUserChoices); - var toggleAiLevel = function () { + const toggleAiLevel = function () { $form.find('.opponent select').each(function (this: HTMLSelectElement) { $form.find('.aiLevel').toggleClass('none', this.value != '1'); $form.find('.opponentName').toggleClass('none', this.value == '1'); diff --git a/ui/site/src/passwordComplexity.ts b/ui/site/src/passwordComplexity.ts index 44fea1c5f1..aa2b5f6456 100644 --- a/ui/site/src/passwordComplexity.ts +++ b/ui/site/src/passwordComplexity.ts @@ -21,7 +21,7 @@ function updateMeter(score: number): void { const meter = document.querySelector('.password-complexity-meter'); const children = meter?.children || []; - for (var i = 0; i < children.length; i++) { + for (let i = 0; i < children.length; i++) { (children[i] as HTMLElement).style.backgroundColor = i < score ? color : ''; } } diff --git a/ui/tournamentSchedule/src/view.ts b/ui/tournamentSchedule/src/view.ts index 9d8e9c6a45..6f15938afc 100644 --- a/ui/tournamentSchedule/src/view.ts +++ b/ui/tournamentSchedule/src/view.ts @@ -79,7 +79,7 @@ function splitOverlaping(lanes) { let ret: any[] = [], i: number; lanes.forEach(lane => { - var newLanes: any[] = [[]]; + const newLanes: any[] = [[]]; lane.forEach(tour => { let collision = true; for (i = 0; i < newLanes.length; i++) { diff --git a/ui/tree/src/tree.ts b/ui/tree/src/tree.ts index 3794eb6bb4..0e487f4159 100644 --- a/ui/tree/src/tree.ts +++ b/ui/tree/src/tree.ts @@ -60,13 +60,13 @@ export function build(root: Tree.Node): TreeWrapper { } function longestValidPathFrom(node: Tree.Node, path: Tree.Path): Tree.Path { - var id = treePath.head(path); + const id = treePath.head(path); const child = ops.childById(node, id); return child ? id + longestValidPathFrom(child, treePath.tail(path)) : ''; } function getCurrentNodesAfterPly(nodeList: Tree.Node[], mainline: Tree.Node[], ply: number): Tree.Node[] { - var node, + let node, nodes = []; for (const i in nodeList) { node = nodeList[i]; @@ -151,10 +151,10 @@ export function build(root: Tree.Node): TreeWrapper { } function promoteAt(path: Tree.Path, toMainline: boolean): void { - var nodes = getNodeList(path); - for (var i = nodes.length - 2; i >= 0; i--) { - var node = nodes[i + 1]; - var parent = nodes[i]; + const nodes = getNodeList(path); + for (let i = nodes.length - 2; i >= 0; i--) { + const node = nodes[i + 1]; + const parent = nodes[i]; if (parent.children[0].id !== node.id) { ops.removeChild(parent, node.id); parent.children.unshift(node); @@ -181,7 +181,7 @@ export function build(root: Tree.Node): TreeWrapper { function deleteCommentAt(id: string, path: Tree.Path) { return updateAt(path, function (node) { - var comments = (node.comments || []).filter(function (c) { + const comments = (node.comments || []).filter(function (c) { return c.id !== id; }); node.comments = comments.length ? comments : undefined;