Merge pull request from typerqeo/lint

Add ESLint for static analysis of code
This commit is contained in:
Jack 2020-11-08 23:27:06 +00:00 committed by GitHub
commit 36f4284bd6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 1287 additions and 546 deletions

View file

@ -2,6 +2,7 @@ const { task, src, dest, series, watch } = require("gulp");
const concat = require("gulp-concat");
const del = require("del");
const vinylPaths = require("vinyl-paths");
const eslint = require("gulp-eslint");
var sass = require("gulp-sass");
sass.compiler = require("dart-sass");
@ -19,8 +20,87 @@ const gulpSrc = [
"./src/js/script.js",
];
let eslintConfig = {
parser: "babel-eslint",
globals: [
"jQuery",
"$",
"firebase",
"moment",
"html2canvas",
"ClipboardItem",
"Chart",
],
envs: ["es6", "browser", "node"],
rules: {
"constructor-super": "error",
"for-direction": "error",
"getter-return": "error",
"no-async-promise-executor": "error",
"no-case-declarations": "error",
"no-class-assign": "error",
"no-compare-neg-zero": "error",
"no-cond-assign": "error",
"no-const-assign": "error",
"no-constant-condition": "error",
"no-control-regex": "error",
"no-debugger": "error",
"no-delete-var": "error",
"no-dupe-args": "error",
"no-dupe-class-members": "error",
"no-dupe-else-if": "warn",
"no-dupe-keys": "error",
"no-duplicate-case": "error",
"no-empty": "warn",
"no-empty-character-class": "error",
"no-empty-pattern": "error",
"no-ex-assign": "error",
"no-extra-boolean-cast": "error",
"no-extra-semi": "error",
"no-fallthrough": "error",
"no-func-assign": "error",
"no-global-assign": "error",
"no-import-assign": "error",
"no-inner-declarations": "error",
"no-invalid-regexp": "error",
"no-irregular-whitespace": "error",
"no-misleading-character-class": "error",
"no-mixed-spaces-and-tabs": "error",
"no-new-symbol": "error",
"no-obj-calls": "error",
"no-octal": "error",
"no-prototype-builtins": "error",
"no-redeclare": "error",
"no-regex-spaces": "error",
"no-self-assign": "error",
"no-setter-return": "error",
"no-shadow-restricted-names": "error",
"no-sparse-arrays": "error",
"no-this-before-super": "error",
"no-undef": "error",
"no-unexpected-multiline": "warn",
"no-unreachable": "error",
"no-unsafe-finally": "error",
"no-unsafe-negation": "error",
"no-unused-labels": "error",
"no-unused-vars": "warn",
"no-use-before-define": "warn",
"no-useless-catch": "error",
"no-useless-escape": "error",
"no-with": "error",
"require-yield": "error",
"use-isnan": "error",
"valid-typeof": "error",
},
};
task("cat", function () {
return src(gulpSrc).pipe(concat("monkeytype.js")).pipe(dest("./dist/js"));
return src(gulpSrc)
.pipe(concat("monkeytype.js"))
.pipe(eslint(eslintConfig))
.pipe(eslint.format())
.pipe(eslint.failAfterError())
.pipe(dest("./dist/js"));
});
task("sass", function () {

1509
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -15,11 +15,14 @@
"node": "10"
},
"devDependencies": {
"babel-eslint": "^10.1.0",
"concurrently": "^5.3.0",
"dart-sass": "^1.25.0",
"del": "^6.0.0",
"eslint": "^6.8.0",
"gulp": "^4.0.2",
"gulp-concat": "^2.6.1",
"gulp-eslint": "^6.0.0",
"gulp-sass": "^4.1.0",
"husky": "^4.3.0",
"prettier": "2.1.2",

View file

@ -200,13 +200,13 @@ function signUp() {
.catch(function (error) {
// An error happened.
$(".pageLogin .preloader").addClass("hidden");
console.error(error);
});
});
})
.catch(function (error) {
// Handle Errors here.
$(".pageLogin .register .button").removeClass("disabled");
var errorCode = error.code;
var errorMessage = error.message;
showNotification(errorMessage, 5000);
$(".pageLogin .preloader").addClass("hidden");
@ -681,7 +681,6 @@ let activityChart = new Chart($(".pageAccount #activityChart"), {
beginAtZero: true,
min: 0,
autoSkip: true,
stepSize: 1,
autoSkipPadding: 40,
stepSize: 10,
},
@ -699,7 +698,6 @@ let activityChart = new Chart($(".pageAccount #activityChart"), {
beginAtZero: true,
min: 0,
autoSkip: true,
stepSize: 1,
autoSkipPadding: 40,
stepSize: 10,
},
@ -1290,7 +1288,8 @@ function showActiveFilters() {
if (aboveChartDisplay[group].all) {
ret += "all";
} else {
allall = false;
//TODO: is this used?
//allall = false;
if (group === "tags") {
ret += aboveChartDisplay.tags.array
.map((id) => {
@ -1788,7 +1787,7 @@ let visibleTableLines = 0;
function loadMoreLines() {
if (filteredResults == [] || filteredResults.length == 0) return;
for (let i = visibleTableLines; i < visibleTableLines + 10; i++) {
result = filteredResults[i];
const result = filteredResults[i];
if (result == undefined) continue;
let withpunc = "";
// if (result.punctuation) {
@ -1936,7 +1935,7 @@ function refreshGlobalStats() {
let tm = Math.floor((dbSnapshot.globalStats.time % 3600) / 60);
let ts = Math.floor((dbSnapshot.globalStats.time % 3600) % 60);
$(".pageAccount .globalTimeTyping .val").text(`
${th < 10 ? "0" + th : th}:${tm < 10 ? "0" + tm : tm}:${
ts < 10 ? "0" + ts : ts
}
@ -1964,7 +1963,8 @@ function refreshAccountPage() {
let chartData = [];
let wpmChartData = [];
let rawChartData = [];
//TODO: is this used?
//let rawChartData = [];
let accChartData = [];
visibleTableLines = 0;
@ -1995,7 +1995,8 @@ function refreshAccountPage() {
let totalCons10 = 0;
let consCount = 0;
let dailyActivityDays = [];
//TODO: is this used?
//let dailyActivityDays = [];
let activityChartData = {};
filteredResults = [];
@ -2390,7 +2391,7 @@ function refreshAccountPage() {
let tm = Math.floor((totalSeconds % 3600) / 60);
let ts = Math.floor((totalSeconds % 3600) % 60);
$(".pageAccount .timeTotal .val").text(`
${th < 10 ? "0" + th : th}:${tm < 10 ? "0" + tm : tm}:${
ts < 10 ? "0" + ts : ts
}
@ -2402,7 +2403,7 @@ function refreshAccountPage() {
let tfm = Math.floor((totalSecondsFiltered % 3600) / 60);
let tfs = Math.floor((totalSecondsFiltered % 3600) % 60);
$(".pageAccount .timeTotalFiltered .val").text(`
${tfh < 10 ? "0" + tfh : tfh}:${tfm < 10 ? "0" + tfm : tfm}:${
tfs < 10 ? "0" + tfs : tfs
}
@ -2525,7 +2526,7 @@ function refreshAccountPage() {
// cont();
showActiveFilters();
} else {
setTimeout((f) => {
setTimeout(() => {
changePage("");
}, 500);
// console.log("something went wrong");

View file

@ -1,7 +1,3 @@
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function addChildCommands(
unifiedCommands,
commandItem,
@ -13,7 +9,7 @@ function addChildCommands(
if (commandItem.subgroup) {
try {
commandItem.exec();
currentCommandsIndex = currentCommands.length - 1;
const currentCommandsIndex = currentCommands.length - 1;
currentCommands[currentCommandsIndex].list.forEach((cmd) =>
addChildCommands(unifiedCommands, cmd, commandItemDisplay)
);
@ -27,8 +23,8 @@ function addChildCommands(
}
function generateSingleListOfCommands() {
allCommands = [];
oldShowCommandLine = showCommandLine;
const allCommands = [];
const oldShowCommandLine = showCommandLine;
showCommandLine = () => {};
commands.list.forEach((c) => addChildCommands(allCommands, c));
showCommandLine = oldShowCommandLine;
@ -1028,26 +1024,6 @@ let commandsHighlightMode = {
],
};
let commandsAlwaysShowCPM = {
title: "Toggle always show cpm...",
list: [
{
id: "setAlwaysShowCPMTrue",
display: true,
exec: () => {
setAlwaysShowCPM(true);
},
},
{
id: "setAlwaysShowCPMFalse",
display: false,
exec: () => {
setHighlightMode(false);
},
},
],
};
let commandsTimerStyle = {
title: "Change timer/progress style...",
list: [
@ -1762,7 +1738,8 @@ $("#commandInput input").keydown((e) => {
if (obj.id == command) {
obj.exec(value);
if (obj.subgroup !== null && obj.subgroup !== undefined) {
subgroup = obj.subgroup;
//TODO: what is this for?
// subgroup = obj.subgroup;
}
}
});
@ -1952,7 +1929,7 @@ function hideCommandLine() {
focusWords();
}
function showCommandLine() {
let showCommandLine = () => {
setFocus(false);
$("#commandLine").removeClass("hidden");
$("#commandInput").addClass("hidden");
@ -1971,7 +1948,7 @@ function showCommandLine() {
$("#commandLine input").val("");
updateSuggestedCommands();
$("#commandLine input").focus();
}
};
function showCommandInput(command, placeholder) {
$("#commandLineWrapper").removeClass("hidden");

View file

@ -70,28 +70,22 @@ async function db_getUserSnapshot() {
// console.log('getting data from db!');
let data = res.data();
if (data === undefined) return;
try {
if (data.personalBests !== undefined) {
snap.personalBests = data.personalBests;
}
snap.discordId = data.discordId;
snap.pairingCode =
data.discordPairingCode == null
? undefined
: data.discordPairingCode;
snap.config = data.config;
snap.favouriteThemes =
data.favouriteThemes === undefined ? [] : data.favouriteThemes;
snap.globalStats = {
time: data.timeTyping,
started: data.startedTests,
completed: data.completedTests,
};
if (data.lbMemory !== undefined) {
snap.lbMemory = data.lbMemory;
}
} catch (e) {
throw e;
if (data.personalBests !== undefined) {
snap.personalBests = data.personalBests;
}
snap.discordId = data.discordId;
snap.pairingCode =
data.discordPairingCode == null ? undefined : data.discordPairingCode;
snap.config = data.config;
snap.favouriteThemes =
data.favouriteThemes === undefined ? [] : data.favouriteThemes;
snap.globalStats = {
time: data.timeTyping,
started: data.startedTests,
completed: data.completedTests,
};
if (data.lbMemory !== undefined) {
snap.lbMemory = data.lbMemory;
}
})
.catch((e) => {
@ -119,7 +113,6 @@ async function db_getUserResults() {
.get()
.then((data) => {
dbSnapshot.results = [];
let len = data.docs.length;
data.docs.forEach((doc, index) => {
let result = doc.data();
result.id = doc.id;
@ -266,7 +259,6 @@ async function db_saveLocalPB(
}
}
let retval;
if (dbSnapshot == null) {
// await db_getUserResults().then(data => {
// retval = cont();

View file

@ -2,9 +2,9 @@ let themesList = null;
async function getThemesList() {
if (themesList == null) {
return $.getJSON("themes/list.json", function (data) {
list = data.sort(function (a, b) {
nameA = a.name.toLowerCase();
nameB = b.name.toLowerCase();
const list = data.sort(function (a, b) {
const nameA = a.name.toLowerCase();
const nameB = b.name.toLowerCase();
if (nameA < nameB) return -1;
if (nameA > nameB) return 1;
return 0;
@ -23,7 +23,7 @@ async function getSortedThemesList() {
if (themesList == null) {
await getThemesList();
}
sorted = themesList.sort((a, b) => {
const sorted = themesList.sort((a, b) => {
let b1 = hexToHSL(a.bgColor);
let b2 = hexToHSL(b.bgColor);
return b2.lgt - b1.lgt;
@ -40,7 +40,8 @@ async function getFunboxList() {
if (funboxList == null) {
return $.getJSON("funbox/list.json", function (data) {
funboxList = data.sort(function (a, b) {
(nameA = a.name.toLowerCase()), (nameB = b.name.toLowerCase());
const nameA = a.name.toLowerCase();
const nameB = b.name.toLowerCase();
if (nameA < nameB) return -1;
if (nameA > nameB) return 1;
return 0;
@ -57,7 +58,8 @@ async function getFontsList() {
if (fontsList == null) {
return $.getJSON("js/fonts.json", function (data) {
fontsList = data.sort(function (a, b) {
(nameA = a.name.toLowerCase()), (nameB = b.name.toLowerCase());
const nameA = a.name.toLowerCase();
const nameB = b.name.toLowerCase();
if (nameA < nameB) return -1;
if (nameA > nameB) return 1;
return 0;
@ -345,9 +347,9 @@ function getGibberish() {
}
function secondsToString(sec) {
hours = Math.floor(sec / 3600);
minutes = Math.floor((sec % 3600) / 60);
seconds = roundTo2((sec % 3600) % 60);
const hours = Math.floor(sec / 3600);
const minutes = Math.floor((sec % 3600) / 60);
const seconds = roundTo2((sec % 3600) % 60);
let hoursString;
let minutesString;
let secondsString;
@ -368,7 +370,7 @@ function getNumbers(len) {
let randLen = Math.floor(Math.random() * len) + 1;
let ret = "";
for (let i = 0; i < randLen; i++) {
randomNum = Math.floor(Math.random() * 10);
const randomNum = Math.floor(Math.random() * 10);
ret += randomNum.toString();
}
return ret;
@ -449,7 +451,7 @@ function findGetParameter(parameterName) {
function objectToQueryString(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
if (Object.prototype.hasOwnProperty.call(obj, p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");

View file

@ -9,6 +9,7 @@ let time = 0;
let timer = null;
let testActive = false;
let testStart, testEnd;
let testInvalid = false;
let wpmHistory = [];
let rawHistory = [];
let restartCount = 0;
@ -499,9 +500,9 @@ async function initWords() {
wordset = customText;
}
for (let i = 0; i < wordsBound; i++) {
randomWord = wordset[Math.floor(Math.random() * wordset.length)];
previousWord = wordsList[i - 1];
previousWord2 = wordsList[i - 2];
let randomWord = wordset[Math.floor(Math.random() * wordset.length)];
const previousWord = wordsList[i - 1];
const previousWord2 = wordsList[i - 2];
if (config.mode == "custom" && customTextIsRandom) {
randomWord = wordset[Math.floor(Math.random() * wordset.length)];
} else if (config.mode == "custom" && !customTextIsRandom) {
@ -558,7 +559,7 @@ async function initWords() {
group = Math.floor(Math.random() * quotes.groups.length);
}
rq =
let rq =
quotes.groups[group][
Math.floor(Math.random() * quotes.groups[group].length)
];
@ -771,9 +772,11 @@ function addWord() {
};
const wordset = language.words;
let randomWord = wordset[Math.floor(Math.random() * wordset.length)];
previousWord = wordsList[wordsList.length - 1];
previousWordStripped = previousWord.replace(/[.?!":\-,]/g, "").toLowerCase();
previousWord2Stripped = wordsList[wordsList.length - 2]
const previousWord = wordsList[wordsList.length - 1];
const previousWordStripped = previousWord
.replace(/[.?!":\-,]/g, "")
.toLowerCase();
const previousWord2Stripped = wordsList[wordsList.length - 2]
.replace(/[.?!":\-,]/g, "")
.toLowerCase();
@ -872,7 +875,7 @@ function showWords() {
if (activeFunBox === "memory") {
memoryFunboxInterval = clearInterval(memoryFunboxInterval);
memoryFunboxTimer = Math.round(Math.pow(wordsList.length, 1.2));
memoryFunboxInterval = setInterval((fn) => {
memoryFunboxInterval = setInterval(() => {
memoryFunboxTimer -= 1;
showNotification(memoryFunboxTimer);
if (memoryFunboxTimer < 0) {
@ -1303,12 +1306,13 @@ function flashPressedKeymapKey(key, correct) {
// border-color: var(--sub-color);
// }
let errorColor;
if (config.colorfulMode) {
errorColor = themeColors.colorfulError;
} else {
errorColor = themeColors.error;
}
// TODO: is this used?
// let errorColor;
// if (config.colorfulMode) {
// errorColor = themeColors.colorfulError;
// } else {
// errorColor = themeColors.error;
// }
switch (key) {
case "\\":
@ -1405,44 +1409,45 @@ function updateHighlightedKeymapKey() {
.toString()
.toUpperCase();
let highlightKey;
switch (currentKey) {
case "\\":
case "|":
var highlightKey = "#KeyBackslash";
highlightKey = "#KeyBackslash";
break;
case "}":
case "]":
var highlightKey = "#KeyRightBracket";
highlightKey = "#KeyRightBracket";
break;
case "{":
case "[":
var highlightKey = "#KeyLeftBracket";
highlightKey = "#KeyLeftBracket";
break;
case '"':
case "'":
var highlightKey = "#KeyQuote";
highlightKey = "#KeyQuote";
break;
case ":":
case ";":
var highlightKey = "#KeySemicolon";
highlightKey = "#KeySemicolon";
break;
case "<":
case ",":
var highlightKey = "#KeyComma";
highlightKey = "#KeyComma";
break;
case ">":
case ".":
var highlightKey = "#KeyPeriod";
highlightKey = "#KeyPeriod";
break;
case "?":
case "/":
var highlightKey = "#KeySlash";
highlightKey = "#KeySlash";
break;
case "":
var highlightKey = "#KeySpace";
highlightKey = "#KeySpace";
break;
default:
var highlightKey = `#Key${currentKey}`;
highlightKey = `#Key${currentKey}`;
}
$(highlightKey).addClass("active-key");
@ -1784,14 +1789,15 @@ function showResult(difficultyFailed = false) {
$("#result .stats .time .bottom .afk").text(afkSecondsPercent + "% afk");
}
let correctcharpercent = roundTo2(
((stats.correctChars + stats.correctSpaces) /
(stats.correctChars +
stats.correctSpaces +
stats.incorrectChars +
stats.extraChars)) *
100
);
// TODO: is this used?
// let correctcharpercent = roundTo2(
// ((stats.correctChars + stats.correctSpaces) /
// (stats.correctChars +
// stats.correctSpaces +
// stats.incorrectChars +
// stats.extraChars)) *
// 100
// );
$("#result .stats .key .bottom").text(testtime + "s");
// $("#result .stats .key .bottom").attr("aria-label", `Correct, incorrect, missed and extra \n ${correctcharpercent}%`);
$("#words").removeClass("blurred");
@ -3279,7 +3285,7 @@ async function loadWordsHistory() {
let input = inputHistory[i];
let wordEl = "";
try {
if (input === "") throw Exception;
if (input === "") throw new Error("empty input word");
if (correctedHistory[i] !== undefined && correctedHistory[i] !== "") {
wordEl = `<div class='word' input="${correctedHistory[i]
.replace(/"/g, "&quot;")
@ -3565,7 +3571,7 @@ function updateTestModesNotice() {
);
}
tagsString = "";
let tagsString = "";
// $.each($('.pageSettings .section.tags .tagsList .tag'), (index, tag) => {
// if($(tag).children('.active').attr('active') === 'true'){
// tagsString += $(tag).children('.title').text() + ', ';
@ -3688,7 +3694,8 @@ function tagsEdit() {
updateResultEditTagsPanelButtons();
updateSettingsPage();
updateFilterTags();
updateActiveTags();
//TODO: is this used?
//updateActiveTags();
} else if (status < -1) {
showNotification("Unknown error", 3000);
}
@ -4244,7 +4251,7 @@ $(document).on("click", "#top .logo", (e) => {
});
$(document).on("click", "#top .config .wordCount .text-button", (e) => {
wrd = $(e.currentTarget).attr("wordCount");
const wrd = $(e.currentTarget).attr("wordCount");
if (wrd == "custom") {
// let newWrd = prompt("Custom word amount");
// if (newWrd !== null && !isNaN(newWrd) && newWrd > 0 && newWrd <= 10000) {
@ -4326,8 +4333,8 @@ $("#wordsWrapper").on("click", (e) => {
$(document).on("click", "#top .config .mode .text-button", (e) => {
if ($(e.currentTarget).hasClass("active")) return;
mode = $(e.currentTarget).attr("mode");
setMode(mode);
const mode = $(e.currentTarget).attr("mode");
changeMode(mode);
manualRestart = true;
restartTest();
});
@ -4337,7 +4344,7 @@ $(document).on("click", "#top #menu .icon-button", (e) => {
if ($(e.currentTarget).hasClass("leaderboards")) {
showLeaderboards();
} else {
href = $(e.currentTarget).attr("href");
const href = $(e.currentTarget).attr("href");
manualRestart = true;
changePage(href.replace("/", ""));
}

View file

@ -561,7 +561,7 @@ function refreshTagsSettingsSection() {
dbSnapshot.tags.forEach((tag) => {
if (tag.active === true) {
tagsEl.append(`
<div class="tag" id="${tag.id}">
<div class="active" active="true">
<i class="fas fa-check-square"></i>
@ -570,11 +570,11 @@ function refreshTagsSettingsSection() {
<div class="editButton"><i class="fas fa-pen"></i></div>
<div class="removeButton"><i class="fas fa-trash"></i></div>
</div>
`);
} else {
tagsEl.append(`
<div class="tag" id="${tag.id}">
<div class="active" active="false">
<i class="fas fa-square"></i>
@ -583,7 +583,7 @@ function refreshTagsSettingsSection() {
<div class="editButton"><i class="fas fa-pen"></i></div>
<div class="removeButton"><i class="fas fa-trash"></i></div>
</div>
`);
}
});
@ -874,7 +874,7 @@ $(".pageSettings #loadCustomColorsFromPreset").click((e) => {
document.documentElement.style.setProperty(e, "");
});
setTimeout((fn) => {
setTimeout(() => {
refreshThemeColorObject();
colorVars.forEach((colorName) => {
let color;

View file

@ -249,7 +249,8 @@ function applyConfig(configObj) {
style="display:inline-block;width:850px;height:90px"
data-ad-client="ca-pub-7261919841327810"
data-ad-slot="2225821478"></ins>`);
(adsbygoogle = window.adsbygoogle || []).push({});
const adsbygoogle = window.adsbygoogle || [];
adsbygoogle.push({});
} else if (config.enableAds === "max") {
$("#ad1").removeClass("hidden");
$("#ad2").removeClass("hidden");
@ -279,9 +280,10 @@ function applyConfig(configObj) {
style="display:inline-block;width:160px;height:600px"
data-ad-client="ca-pub-7261919841327810"
data-ad-slot="1159796595"></ins>`);
(adsbygoogle = window.adsbygoogle || []).push({});
(adsbygoogle = window.adsbygoogle || []).push({});
(adsbygoogle = window.adsbygoogle || []).push({});
const adsbygoogle = window.adsbygoogle || [];
adsbygoogle.push({});
adsbygoogle.push({});
adsbygoogle.push({});
} else {
$("#ad1").remove();
$("#ad2").remove();
@ -366,7 +368,7 @@ function setFavThemes(themes, nosave) {
//blind mode
function toggleBlindMode() {
blind = !config.blindMode;
let blind = !config.blindMode;
if (blind == undefined) {
blind = false;
}
@ -602,7 +604,7 @@ function setSingleListCommandLine(option, nosave) {
//show all lines
function toggleShowAllLines() {
sal = !config.showAllLines;
let sal = !config.showAllLines;
if (sal == undefined) {
sal = false;
}
@ -624,7 +626,7 @@ function setShowAllLines(sal, nosave) {
//quickend
function toggleQuickEnd() {
qe = !config.quickEnd;
let qe = !config.quickEnd;
if (qe == undefined) {
qe = false;
}
@ -1117,7 +1119,7 @@ function setConfidenceMode(cm, nosave) {
}
function toggleIndicateTypos() {
it = !config.indicateTypos;
let it = !config.indicateTypos;
if (it == undefined) {
it = false;
}
@ -1223,7 +1225,7 @@ function setCustomThemeColors(colors, nosave) {
}
function applyCustomThemeColors() {
array = config.customThemeColors;
const array = config.customThemeColors;
if (config.customTheme === true) {
$(".current-theme").text("custom");