Upgrade Prettier

This commit is contained in:
Jordan Eldredge 2020-04-06 19:50:20 -07:00
parent 63c112cba5
commit 91fd22ec38
123 changed files with 433 additions and 422 deletions

View file

@ -58,7 +58,7 @@ export function getButterchurnOptions(
const milkdropPresetUrl = params.get("milkdropPresetUrl");
if (butterchurnPresetMapUrlParam) {
if (
!KNOWN_PRESET_URLS_REGEXES.some(pattern =>
!KNOWN_PRESET_URLS_REGEXES.some((pattern) =>
pattern.test(butterchurnPresetMapUrlParam)
)
) {
@ -70,7 +70,7 @@ export function getButterchurnOptions(
}
} else if (butterchurnPresetUrlParam) {
if (
!KNOWN_PRESET_URLS_REGEXES.some(pattern =>
!KNOWN_PRESET_URLS_REGEXES.some((pattern) =>
pattern.test(butterchurnPresetUrlParam)
)
) {

View file

@ -16,7 +16,7 @@ self.addEventListener("activate", () => {
.then(() => {
return self.clients.matchAll();
})
.then(clients => {
clients.forEach(client => client.navigate(client.url));
.then((clients) => {
clients.forEach((client) => client.navigate(client.url));
});
});

View file

@ -31,7 +31,7 @@ const dropboxFilePicker: FilePicker = {
);
// https://github.com/captbaritone/webamp/issues/750
const files = await genAudioFileUrlsFromDropbox();
return files.map(file => ({
return files.map((file) => ({
url: file.link,
defaultName: file.name,
}));

View file

@ -189,7 +189,7 @@ async function main() {
});
}
webamp.onTrackDidChange(track => {
webamp.onTrackDidChange((track) => {
document.title =
track == null
? DEFAULT_DOCUMENT_TITLE
@ -204,7 +204,7 @@ async function main() {
fileInput.style.display = "none";
fileInput.type = "file";
fileInput.value = null;
fileInput.addEventListener("change", e => {
fileInput.addEventListener("change", (e) => {
webamp.store.dispatch(loadFilesFromReferences(e.target.files));
});
document.body.appendChild(fileInput);

View file

@ -3,7 +3,7 @@ import WebampLazy from "../../js/webampLazy";
export default function enableMediaSession(webamp: WebampLazy) {
if ("mediaSession" in navigator) {
/* global MediaMetadata */
webamp.onTrackDidChange(track => {
webamp.onTrackDidChange((track) => {
if (track == null) {
return;
}

View file

@ -5,11 +5,11 @@ new Webamp({
{
metaData: {
artist: "DJ Mike Llama",
title: "Llama Whippin' Intro"
title: "Llama Whippin' Intro",
},
url:
"https://cdn.jsdelivr.net/gh/captbaritone/webamp@43434d82cfe0e37286dbbe0666072dc3190a83bc/mp3/llama-2.91.mp3",
duration: 5.322286
}
]
duration: 5.322286,
},
],
}).renderWhenReady(document.getElementById("app"));

View file

@ -23,7 +23,7 @@ new Webamp({
"https://unpkg.com/butterchurn-presets-weekly@0.0.2/weeks/week1/presets.json"
);
const namesToPresetUrls = await resp.json();
return Object.keys(namesToPresetUrls).map(name => {
return Object.keys(namesToPresetUrls).map((name) => {
return { name, butterchurnPresetUrl: namesToPresetUrls[name] };
});
},

View file

@ -42,7 +42,7 @@ async function testPage({ url, name, firstTrackText }) {
}
log("Getting text of first track...");
const actualFirstTrackText = await page.evaluate(
_ => _.textContent,
(_) => _.textContent,
firstTrack
);
@ -113,7 +113,7 @@ async function main() {
});
}
(async function() {
(async function () {
try {
await main();
} catch (e) {

View file

@ -28,7 +28,7 @@ function getSkinRecord(skin) {
readmeText,
filePaths,
} = skin;
const fileNames = filePaths.map(p => path.basename(p));
const fileNames = filePaths.map((p) => path.basename(p));
const skinUrl = `https://s3.amazonaws.com/webamp-uploaded-skins/skins/${md5}.wsz`;
return {
skinUrl,
@ -184,13 +184,13 @@ async function reconcile() {
S3.getAllTweeted(),
]);
await Promise.all([
...approved.map(md5 =>
...approved.map((md5) =>
skins.findOneAndUpdate({ md5 }, { $set: { approved: true } })
),
...rejected.map(md5 =>
...rejected.map((md5) =>
skins.findOneAndUpdate({ md5 }, { $set: { rejected: true } })
),
...tweeted.map(md5 =>
...tweeted.map((md5) =>
skins.findOneAndUpdate({ md5 }, { $set: { tweeted: true } })
),
]);

View file

@ -14,12 +14,12 @@ async function handler(message, args) {
let filename = null;
await Utils.postSkin({
md5,
title: f => {
title: (f) => {
// Hack to get access to the file name
filename = f;
return `Approve: ${f}`;
},
dest: tweetBotChannel
dest: tweetBotChannel,
});
await tweetBotChannel.send(
`${filename} was approved by ${message.author.username}`
@ -30,5 +30,5 @@ module.exports = {
command: "approve",
handler,
usage: "<md5-hash>",
description: "Approve a given skin to be Tweeted by the Twitter bot"
description: "Approve a given skin to be Tweeted by the Twitter bot",
};

View file

@ -13,7 +13,7 @@ async function handler(message) {
return;
}
const files = await Promise.all(
attachments.map(async attachment => {
attachments.map(async (attachment) => {
const { filename, url } = attachment;
const response = await fetch(url);
console.log("got response");
@ -43,7 +43,7 @@ async function handler(message) {
await message.channel.send(`This skin is already in our collection.`);
await Utils.postSkin({
md5: file.md5,
dest: message.channel
dest: message.channel,
});
} else {
fs.writeFileSync(
@ -67,5 +67,5 @@ module.exports = {
usage: "",
description:
"Queues the accompanying uploaded skin for inclusion in the Archive",
handler
handler,
};

View file

@ -4,12 +4,12 @@ const { getCache } = require("../info");
async function handler(message) {
const cache = getCache();
const skins = Object.values(cache).filter(skin => skin.type === "CLASSIC");
const skins = Object.values(cache).filter((skin) => skin.type === "CLASSIC");
const skin = skins[Math.floor(Math.random() * skins.length)];
const { md5 } = skin;
await Utils.postSkin({
md5,
dest: message.channel
dest: message.channel,
});
}
@ -17,5 +17,5 @@ module.exports = {
usage: "",
description: "Show information about a random skin",
command: "random",
handler
handler,
};

View file

@ -14,12 +14,12 @@ async function handler(message, args) {
let filename = null;
await Utils.postSkin({
md5,
title: f => {
title: (f) => {
// Hack to get access to the file name
filename = f;
return `Rejected: ${f}`;
},
dest: tweetBotChannel
dest: tweetBotChannel,
});
await tweetBotChannel.send(
`${filename} was rejected by ${message.author.username}`
@ -30,5 +30,5 @@ module.exports = {
command: "reject",
handler,
usage: "<md5-hash>",
description: "Reject a given skin from being Tweeted by the Twitter bot"
description: "Reject a given skin from being Tweeted by the Twitter bot",
};

View file

@ -9,8 +9,8 @@ async function reviewSkin(message) {
const { md5 } = skin;
await Utils.postSkin({
md5,
title: filename => `Review: ${filename}`,
dest: message.channel
title: (filename) => `Review: ${filename}`,
dest: message.channel,
});
}
@ -39,5 +39,5 @@ module.exports = {
handler,
usage: "[<number>]",
description:
"Post a <number> of skins to be reviewed for inclusion in the Twitter bot. Defaults to 1"
"Post a <number> of skins to be reviewed for inclusion in the Twitter bot. Defaults to 1",
};

View file

@ -14,7 +14,7 @@ async function handler(message) {
return;
}
const files = await Promise.all(
attachments.map(async attachment => {
attachments.map(async (attachment) => {
const { filename, url } = attachment;
const response = await fetch(url);
console.log("got response");
@ -37,7 +37,7 @@ async function handler(message) {
try {
await shooter.takeScreenshot(tempFile, tempScreenshotPath, {
minify: true
minify: true,
});
} catch (e) {
await message.channel.send(
@ -64,5 +64,5 @@ module.exports = {
command: "screenshot",
usage: "",
description: "Take a screenshot of the accompanying uploaded skin",
handler
handler,
};

View file

@ -5,7 +5,7 @@ async function handler(message, args) {
const md5 = await Skins.getMd5ByAnything(anything);
await Utils.postSkin({
md5,
dest: message.channel
dest: message.channel,
});
}
@ -13,5 +13,5 @@ module.exports = {
usage: "<md5-skin>",
description: "Show information about a skin",
command: "skin",
handler
handler,
};

View file

@ -5,7 +5,7 @@ async function handler(message) {
const info = getCache();
let classic = 0;
const { tweeted, approved, rejected, tweetable } = await getStats();
Object.values(info).forEach(skin => {
Object.values(info).forEach((skin) => {
if (skin.type === "CLASSIC") {
classic++;
}
@ -22,5 +22,5 @@ module.exports = {
command: "stats",
handler,
usage: "",
description: "Give some statistics about the skin archive"
description: "Give some statistics about the skin archive",
};

View file

@ -15,5 +15,5 @@ module.exports = {
command: "tweet",
handler,
usage: "",
description: "Tweet an approved skin"
description: "Tweet an approved skin",
};

View file

@ -7,13 +7,13 @@ const DiscordWinstonTransport = require("../DiscordWinstonTransport");
const client = new Discord.Client();
const handlers = {
help: handleHelp
help: handleHelp,
};
const commands = fs
.readdirSync(path.resolve(__dirname, "./commands"))
.filter(file => file.endsWith(".js"))
.map(file => {
.filter((file) => file.endsWith(".js"))
.map((file) => {
return require(`./commands/${file}`);
});
@ -23,7 +23,7 @@ for (const command of commands) {
async function handleHelp(message) {
const commandHelp = commands
.map(command => {
.map((command) => {
return `\`!${command.command} ${command.usage || ""}\` -- ${
command.description
}`;
@ -41,7 +41,7 @@ You can issue these commands in a DM to me or in any channel. For tasks relating
message.channel.send(help);
}
client.on("message", async message => {
client.on("message", async (message) => {
if (message.author.bot) {
return;
}
@ -54,7 +54,7 @@ client.on("message", async message => {
command,
user: message.author.username,
args,
channel: message.channel.name || "DM"
channel: message.channel.name || "DM",
});
const handler = handlers[command];
if (handler == null) {
@ -62,14 +62,14 @@ client.on("message", async message => {
command,
user: message.author.username,
args,
alert: true
alert: true,
});
return;
}
handler(message, args);
});
client.on("error", e => {
client.on("error", (e) => {
logger.error("The WebSocket encountered an error:", e);
});

View file

@ -20,7 +20,7 @@ function getInfo(md5) {
// TODO: Make async and rewriting using DB
function getFilename(md5) {
const info = getInfo(md5);
return info.filePaths.map(filepath => path.basename(filepath))[0];
return info.filePaths.map((filepath) => path.basename(filepath))[0];
}
module.exports = { getInfo, getCache, getFilename };

View file

@ -3,8 +3,8 @@ const rgbHex = require("rgb-hex");
const Skins = require("../data/skins");
const logger = require("../logger");
const filter = reaction => {
return ["👍", "👎"].some(name => reaction.emoji.name === name);
const filter = (reaction) => {
return ["👍", "👎"].some((name) => reaction.emoji.name === name);
};
async function postSkin({ md5, title, dest }) {
@ -25,7 +25,7 @@ async function postSkin({ md5, title, dest }) {
tweetStatus,
internetArchiveUrl,
internetArchiveItemName,
readmeText
readmeText,
} = skin;
title = title ? title(canonicalFilename) : canonicalFilename;
@ -49,7 +49,7 @@ async function postSkin({ md5, title, dest }) {
logger.warn("Did not get a safe color", {
averageColor,
color,
warn: true
warn: true,
});
}
} catch (e) {
@ -81,7 +81,7 @@ async function postSkin({ md5, title, dest }) {
const msg = await dest.send(embed);
await msg.awaitReactions(filter, { max: 1 }).then(async collected => {
await msg.awaitReactions(filter, { max: 1 }).then(async (collected) => {
const vote = collected.first();
const user = vote.users.first();
switch (vote.emoji.name) {

View file

@ -75,31 +75,31 @@ class Skin {
}
async canonicalFilename() {
return this._get(skin => skin.canonicalFilename);
return this._get((skin) => skin.canonicalFilename);
}
async filenames() {
return this._get(skin => skin.fileNames);
return this._get((skin) => skin.fileNames);
}
async emails() {
return this._get(skin => skin.emails);
return this._get((skin) => skin.emails);
}
async tweetUrl() {
return this._get(skin => skin.tweetUrl);
return this._get((skin) => skin.tweetUrl);
}
async skinUrl() {
return this._get(skin => skin.skinUrl);
return this._get((skin) => skin.skinUrl);
}
async screenshotUrl() {
return this._get(skin => skin.screenshotUrl);
return this._get((skin) => skin.screenshotUrl);
}
async webampUrl() {
return this._get(skin => skin.webampUrl);
return this._get((skin) => skin.webampUrl);
}
async tweetStatus() {
@ -107,11 +107,11 @@ class Skin {
}
async readmeText() {
return this._get(skin => skin.readmeText);
return this._get((skin) => skin.readmeText);
}
async averageColor() {
return this._get(skin => skin.averageColor);
return this._get((skin) => skin.averageColor);
}
internetArchiveItem() {
@ -126,7 +126,7 @@ const root = {
},
};
exports.default = function() {
exports.default = function () {
return graphqlHTTP({
schema: schema,
rootValue: root,

View file

@ -6,7 +6,7 @@ const hashes = new Map();
fs.readFileSync(path.join(__dirname, "./hash.txt"), "utf8")
.split("\n")
.forEach(line => {
.forEach((line) => {
const [md5, imgHash] = line.split(" ");
hashes.set(md5, imgHash);
});

View file

@ -20,7 +20,7 @@ function getFile(key) {
function putFile(key, body) {
return new Promise((resolve, rejectPromise) => {
const bucketName = "winamp2-js-skins";
s3.putObject({ Bucket: bucketName, Key: key, Body: body }, err => {
s3.putObject({ Bucket: bucketName, Key: key, Body: body }, (err) => {
if (err) {
rejectPromise(err);
return;
@ -34,7 +34,7 @@ function getLines(body) {
return body
.trim()
.split("\n")
.map(line => line.trim());
.map((line) => line.trim());
}
async function getAllApproved() {
@ -98,7 +98,7 @@ async function getSkinToReview() {
const tweetedSet = new Set(getLines(tweeted));
const filenameLines = getLines(filenames);
const skins = filenameLines.map(line => {
const skins = filenameLines.map((line) => {
const [md5, ...filename] = line.split(" ");
return { md5, filename: filename.join(" ") };
});
@ -125,7 +125,7 @@ async function getTweetableSkins() {
const filenameLines = getLines(filenames);
return filenameLines
.map(line => {
.map((line) => {
const [md5, ...filename] = line.split(" ");
return { md5, filename: filename.join(" ") };
})

View file

@ -22,10 +22,10 @@ class Shooter {
this._page.on("console", (...args) => {
console.log("page log:", ...args);
});
this._page.on("error", e => {
this._page.on("error", (e) => {
console.log(`Page error: ${e.toString()}`);
});
this._page.on("dialog", async dialog => {
this._page.on("dialog", async (dialog) => {
console.log(`Page dialog ${dialog.message()}`);
await dialog.dismiss();
});

View file

@ -13,7 +13,7 @@ module.exports = async function main() {
);
for (const item of items) {
const skinFiles = item.metadata.files.filter(file => {
const skinFiles = item.metadata.files.filter((file) => {
return file.name.endsWith(".wsz");
});
if (skinFiles.length !== 1) {

View file

@ -24,7 +24,7 @@ async function fetchAllMetadata(limit) {
);
console.log(`Found ${items.length} missing metadata`);
await Promise.all(
items.map(item => {
items.map((item) => {
return fetchMetadata(item.identifier);
})
);
@ -33,7 +33,7 @@ async function fetchAllMetadata(limit) {
// TODO: Refetch collections from:
// https://archive.org/advancedsearch.php?q=collection%3Awinampskins&fl%5B%5D=identifier&rows=100000&page=1&output=json
module.exports = async function main() {
return new Promise(resolve => {
return new Promise((resolve) => {
let delay = 60000;
let timeout = null;
async function go() {

View file

@ -10,7 +10,7 @@ module.exports = async function main() {
const items = collections.response.docs;
const bulkUpdates = items
.map(item => {
.map((item) => {
const { identifier } = item;
return {
updateOne: {

View file

@ -11,16 +11,16 @@ function spawnPromise(command, args) {
let stdout = "";
let stderr = "";
ls.stdout.on("data", data => {
ls.stdout.on("data", (data) => {
stdout += data;
});
ls.stderr.on("data", data => {
ls.stderr.on("data", (data) => {
stderr += data;
console.log(`stderr: ${data}`);
});
ls.on("close", code => {
ls.on("close", (code) => {
console.log(`child process exited with code ${code}`);
if (code === 0) {
resolve(stdout);

View file

@ -18,8 +18,8 @@ function md5File(filePath) {
module.exports = async function collectSkins({ inputDir, cache }) {
console.log("Searching for files in", inputDir);
const paths = new Set();
Object.values(cache).forEach(skin => {
skin.filePaths.forEach(filePath => {
Object.values(cache).forEach((skin) => {
skin.filePaths.forEach((filePath) => {
paths.add(filePath);
});
});
@ -36,7 +36,7 @@ module.exports = async function collectSkins({ inputDir, cache }) {
}, 10000);
await Bluebird.map(
files,
async filePath => {
async (filePath) => {
if (paths.has(filePath)) {
return;
}

View file

@ -1,7 +1,7 @@
const exec = require("child_process").exec;
const shellescape = require("shell-escape");
const getColor = imgPath => {
const getColor = (imgPath) => {
return new Promise((resolve, reject) => {
const excapedImgPath = shellescape([imgPath]);
const command = `convert ${excapedImgPath} -scale 1x1\! -format '%[pixel:u]' info:-`;

View file

@ -70,7 +70,7 @@ async function main() {
let screenshotCount = 0;
let archived = 0;
let generated = 0;
Object.values(cache).forEach(skin => {
Object.values(cache).forEach((skin) => {
switch (skin.type) {
case FILE_TYPES.CLASSIC:
classic++;
@ -114,7 +114,7 @@ async function main() {
}
if (moveHome) {
console.log("Moving skins to md5AllSkins");
Object.values(cache).forEach(skin => {
Object.values(cache).forEach((skin) => {
const md5Path = path.join(outputDir, "md5AllSkins", `${skin.md5}`);
if (md5Path === skin.md5Path) {
return;
@ -127,8 +127,8 @@ async function main() {
save();
console.log("Moving classic skins to md5Skins");
Object.values(cache)
.filter(skin => skin.type === FILE_TYPES.CLASSIC)
.forEach(skin => {
.filter((skin) => skin.type === FILE_TYPES.CLASSIC)
.forEach((skin) => {
const classicMd5Path = path.join(
outputDir,
"md5Skins",
@ -157,7 +157,7 @@ async function main() {
}, 10000);
await Bluebird.map(
skins,
async skin => {
async (skin) => {
if (skin.type && force === false) {
return;
}
@ -182,7 +182,7 @@ async function main() {
save();
}, 10000);
const needScreenshot = skins.filter(skin => {
const needScreenshot = skins.filter((skin) => {
return skin.type === FILE_TYPES.CLASSIC && !skin.screenshotPath;
});
@ -217,7 +217,7 @@ async function main() {
if (detectGenerated) {
const unknownSkins = Object.values(cache).filter(
skin => skin.type === FILE_TYPES.CLASSIC && skin.generated == null
(skin) => skin.type === FILE_TYPES.CLASSIC && skin.generated == null
);
console.log(
`Found ${unknownSkins.length} skins to check if they are generated`
@ -232,7 +232,7 @@ async function main() {
}, 10000);
await Bluebird.map(
unknownSkins,
async skin => {
async (skin) => {
const generated = await Utils.skinWasGenerated(skin.classicMd5Path);
j++;
if (generated) {
@ -248,11 +248,11 @@ async function main() {
if (archive) {
const classicSkins = Object.values(cache).filter(
skin => skin.type === FILE_TYPES.CLASSIC && skin.iaItemName == null
(skin) => skin.type === FILE_TYPES.CLASSIC && skin.iaItemName == null
);
const seenItemNames = new Set();
Object.values(cache).forEach(skin => {
Object.values(cache).forEach((skin) => {
if (skin.iaItemName != null) {
seenItemNames.add(skin.iaItemName.toLowerCase());
}
@ -260,7 +260,7 @@ async function main() {
await Bluebird.map(
classicSkins,
async skin => {
async (skin) => {
const itemName = Utils.getArchiveItemName(skin);
console.log("going to upload ", itemName);
if (seenItemNames.has(itemName.toLowerCase())) {
@ -285,7 +285,7 @@ async function main() {
if (color) {
const classicSkins = Object.values(cache).filter(
skin => skin.type === FILE_TYPES.CLASSIC
(skin) => skin.type === FILE_TYPES.CLASSIC
);
let i = 0;
const interval = setInterval(() => {
@ -297,7 +297,7 @@ async function main() {
await Bluebird.map(
classicSkins,
async skin => {
async (skin) => {
if (skin.screenshotPath == null) {
console.log("Could not extract color from skin");
return;
@ -320,7 +320,7 @@ async function main() {
path.join("/Volumes/Mobile Backup/skins/", "likes.txt"),
"utf8"
);
content.split("\n").forEach(line => {
content.split("\n").forEach((line) => {
if (!line.length) {
return;
}
@ -337,7 +337,7 @@ async function main() {
if (readme) {
const classicSkins = Object.values(cache).filter(
skin => skin.type === FILE_TYPES.CLASSIC
(skin) => skin.type === FILE_TYPES.CLASSIC
);
let i = 0;
const interval = setInterval(() => {
@ -349,7 +349,7 @@ async function main() {
await Bluebird.map(
classicSkins,
async skin => {
async (skin) => {
const readmePath = path.join(outputDir, "readmes", `${skin.md5}.txt`);
// if (skin.readmePath || skin.emails) {
if (skin.readmePath !== undefined) {

View file

@ -1,7 +1,7 @@
const { exec } = require("child_process");
const reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/gi;
const extract = value => (value && value.match(reg)) || [];
const extract = (value) => (value && value.match(reg)) || [];
async function extractTextData(skinPath) {
const ignoreFiles = [
@ -18,7 +18,7 @@ async function extractTextData(skinPath) {
];
const ignoreArgs = ignoreFiles
.map(file => `-x "**/${file}" ${file}`)
.map((file) => `-x "**/${file}" ${file}`)
.join(" ");
// Change -p to -c to get context of which file is missing
@ -28,7 +28,7 @@ async function extractTextData(skinPath) {
// TODO: Escape path
const cmd = `unzip ${listFlag} -C "${skinPath}" "file_id.diz" "*.txt" ${ignoreArgs}`;
const raw = await new Promise(resolve => {
const raw = await new Promise((resolve) => {
exec(cmd, (error, stdout) => {
if (error != null) {
// reject(error);

View file

@ -21,10 +21,10 @@ class Shooter {
this._page.on("console", (...args) => {
console.log("page log:", ...args);
});
this._page.on("error", e => {
this._page.on("error", (e) => {
console.log(`Page error: ${e.toString()}`);
});
this._page.on("dialog", async dialog => {
this._page.on("dialog", async (dialog) => {
console.log(`Page dialog ${dialog.message()}`);
await dialog.dismiss();
});

View file

@ -9,7 +9,7 @@ async function unique(arr, hasher) {
const seen = new Set();
const items = [];
await Promise.all(
arr.map(async item => {
arr.map(async (item) => {
const key = await hasher(item);
if (seen.has(key)) {
return;
@ -35,11 +35,11 @@ function md5File(filePath) {
}
function skinWasGenerated(filePath) {
return new Promise(resolve => {
return new Promise((resolve) => {
childProcess.execFile(
`zipgrep`,
["This file was created by Skinamp", filePath],
err => {
(err) => {
if (err) {
// node couldn't execute the command
resolve(false);

View file

@ -10,7 +10,7 @@ async function main() {
const filenames = await fsPromises.readFile(filenamesPath, "utf8");
const filenamesMap = new Map();
filenames.split("\n").forEach(line => {
filenames.split("\n").forEach((line) => {
const md5 = line.slice(0, 32);
const filename = line.slice(33);
filenamesMap.set(md5, filename);
@ -19,17 +19,17 @@ async function main() {
const skins = await fsPromises.readdir(skinDir);
const screenshots = await fsPromises.readdir(screenshotDir);
const skinMd5s = skins.map(skinPath => path.basename(skinPath, ".wsz"));
const screenshotMd5s = screenshots.map(screenshotPath =>
const skinMd5s = skins.map((skinPath) => path.basename(skinPath, ".wsz"));
const screenshotMd5s = screenshots.map((screenshotPath) =>
path.basename(screenshotPath, ".png")
);
const skinMd5sSet = new Set(skinMd5s);
const missing = screenshotMd5s.filter(md5 => !skinMd5sSet.has(md5));
const missing = screenshotMd5s.filter((md5) => !skinMd5sSet.has(md5));
await Promise.all(
missing.map(async md5 => {
missing.map(async (md5) => {
const filename = filenamesMap.get(md5);
if (filename == null) {
return;

View file

@ -23,7 +23,7 @@ export default class Disposable {
"Attempted to dispose disposable which is already disposed."
);
}
this._teardowns.forEach(teardown => {
this._teardowns.forEach((teardown) => {
if (typeof teardown === "function") {
teardown();
} else if (typeof teardown.dispose === "function") {

View file

@ -26,8 +26,8 @@ export function setEqBand(band: Band, value: number): Action {
}
function _setEqTo(value: number): Thunk {
return dispatch => {
Object.values(BANDS).forEach(band => {
return (dispatch) => {
Object.values(BANDS).forEach((band) => {
dispatch({
type: SET_BAND_VALUE,
value,
@ -64,7 +64,7 @@ export function toggleEq(): Thunk {
}
export function toggleEqAuto(): Thunk {
return dispatch => {
return (dispatch) => {
// We don't actually support this feature yet so don't let the user ever turn it on.
// dispatch({ type: SET_EQ_AUTO, value: !getState().equalizer.auto });
dispatch({ type: SET_EQ_AUTO, value: false });

View file

@ -48,7 +48,7 @@ export function addTracksFromReferences(
loadStyle: LoadStyle,
atIndex: number | undefined
): Thunk {
const tracks: Track[] = Array.from(fileReferences).map(file => ({
const tracks: Track[] = Array.from(fileReferences).map((file) => ({
blob: file,
defaultName: file.name,
}));
@ -62,7 +62,7 @@ export function loadFilesFromReferences(
loadStyle: LoadStyle = LOAD_STYLE.PLAY,
atIndex: number | undefined = undefined
): Thunk {
return dispatch => {
return (dispatch) => {
if (fileReferences.length < 1) {
return;
} else if (fileReferences.length === 1) {
@ -118,7 +118,7 @@ export function setSkinFromBlob(blob: Blob | Promise<Blob>): Thunk {
}
export function setSkinFromUrl(url: string): Thunk {
return async dispatch => {
return async (dispatch) => {
dispatch({ type: LOADING });
try {
const response = await fetch(url);
@ -138,7 +138,7 @@ export function setSkinFromUrl(url: string): Thunk {
// opening files via other methods. Only use the file type specific
// versions below, since they can defer to the user-defined behavior.
function _openFileDialog(accept: string | null): Thunk {
return async dispatch => {
return async (dispatch) => {
const fileReferences = await promptForFileReferences({ accept });
dispatch(loadFilesFromReferences(fileReferences));
};
@ -202,7 +202,7 @@ export function loadMediaFiles(
loadStyle: LoadStyle = LOAD_STYLE.NONE,
atIndex = 0
): Thunk {
return dispatch => {
return (dispatch) => {
if (loadStyle === LOAD_STYLE.PLAY) {
// I'm the worst. It just so happens that in every case that we autoPlay,
// we should also clear all tracks.
@ -220,7 +220,7 @@ export function loadMediaFile(
priority: LoadStyle = LOAD_STYLE.NONE,
atIndex = 0
): Thunk {
return dispatch => {
return (dispatch) => {
const id = Utils.uniqueId();
const { defaultName, metaData, duration } = track;
let canonicalUrl: string;
@ -330,7 +330,7 @@ export function fetchMediaTags(file: string | Blob, id: number): Thunk {
}
export function setEqFromFileReference(fileReference: File): Thunk {
return async dispatch => {
return async (dispatch) => {
const arrayBuffer = await genArrayBufferFromFileReference(fileReference);
const eqf = parser(arrayBuffer);
const preset: EqfPreset = eqf.presets[0];
@ -339,9 +339,9 @@ export function setEqFromFileReference(fileReference: File): Thunk {
}
export function setEqFromObject(preset: EqfPreset): Thunk {
return dispatch => {
return (dispatch) => {
dispatch(setPreamp(Utils.normalizeEqBand(preset.preamp)));
BANDS.forEach(band => {
BANDS.forEach((band) => {
// @ts-ignore band and EqfPreset align
dispatch(setEqBand(band, Utils.normalizeEqBand(preset[`hz${band}`])));
});
@ -380,7 +380,7 @@ const DIR_SUPPORT =
el = null;
export function addFilesAtIndex(nextIndex: number): Thunk {
return async dispatch => {
return async (dispatch) => {
const fileReferences = await promptForFileReferences();
dispatch(
addTracksFromReferences(fileReferences, LOAD_STYLE.NONE, nextIndex)
@ -389,7 +389,7 @@ export function addFilesAtIndex(nextIndex: number): Thunk {
}
export function addDirAtIndex(nextIndex: number): Thunk {
return async dispatch => {
return async (dispatch) => {
if (!DIR_SUPPORT) {
alert("Not supported in your browser");
return;

View file

@ -99,7 +99,7 @@ test("setEqToMax", () => {
const mockDispatch = jest.fn();
const dispatcher = setEqToMax();
dispatcher(mockDispatch);
const expectedCalls = BANDS.map(band => [
const expectedCalls = BANDS.map((band) => [
{ type: SET_BAND_VALUE, band, value: 100 },
]);
expect(mockDispatch.mock.calls).toEqual(expectedCalls);
@ -109,7 +109,7 @@ test("setEqToMin", () => {
const mockDispatch = jest.fn();
const dispatcher = setEqToMin();
dispatcher(mockDispatch);
const expectedCalls = BANDS.map(band => [
const expectedCalls = BANDS.map((band) => [
{ type: SET_BAND_VALUE, band, value: 0 },
]);
expect(mockDispatch.mock.calls).toEqual(expectedCalls);
@ -119,7 +119,7 @@ test("setEqToMid", () => {
const mockDispatch = jest.fn();
const dispatcher = setEqToMid();
dispatcher(mockDispatch);
const expectedCalls = BANDS.map(band => [
const expectedCalls = BANDS.map((band) => [
{ type: SET_BAND_VALUE, band, value: 50 },
]);
expect(mockDispatch.mock.calls).toEqual(expectedCalls);

View file

@ -125,7 +125,7 @@ export {
} from "./milkdrop";
export function close(): Thunk {
return dispatch => {
return (dispatch) => {
// TODO: This could probably be improved by adding a "PREVENT_CLOSE" action
// or something, but this works okay for now.
let defaultPrevented = false;
@ -168,7 +168,7 @@ export function loadSerializedState(
// In the future this type should be the union of all versioned types.
serializedState: SerializedStateV1
): Thunk {
return dispatch => {
return (dispatch) => {
dispatch({ type: LOAD_SERIALIZED_STATE, serializedState });
dispatch(ensureWindowsAreOnScreen());
};

View file

@ -81,7 +81,7 @@ export function previous(): Thunk {
}
export function seekToTime(seconds: number): Thunk {
return function(dispatch, getState) {
return function (dispatch, getState) {
const state = getState();
const duration = Selectors.getDuration(state);
if (duration == null) {
@ -94,7 +94,7 @@ export function seekToTime(seconds: number): Thunk {
};
}
export function seekForward(seconds: number): Thunk {
return function(dispatch, getState) {
return function (dispatch, getState) {
const timeElapsed = Selectors.getTimeElapsed(getState());
dispatch(seekToTime(timeElapsed + seconds));
};

View file

@ -47,9 +47,9 @@ function normalizePresetTypes(preset: Preset): StatePreset {
}
export function initializePresets(presetOptions: ButterchurnOptions): Thunk {
return async dispatch => {
return async (dispatch) => {
const { getPresets, importButterchurn } = presetOptions;
importButterchurn().then(butterchurn => {
importButterchurn().then((butterchurn) => {
dispatch({ type: GOT_BUTTERCHURN, butterchurn: butterchurn.default });
});
@ -77,7 +77,7 @@ export function loadPresets(presets: StatePreset[]): Thunk {
export function appendPresetFileList(fileList: FileList): Thunk {
return async (dispatch, getState, { convertPreset }) => {
const presets: StatePreset[] = Array.from(fileList)
.map(file => {
.map((file) => {
const JSON_EXT = ".json";
const MILK_EXT = ".milk";
const filename = file.name.toLowerCase();

View file

@ -31,7 +31,7 @@ export function cropPlaylist(): Thunk {
type: REMOVE_TRACKS,
// @ts-ignore The keys are numbers, but TypeScript does not trust us.
// https://github.com/Microsoft/TypeScript/pull/12253#issuecomment-263132208
ids: trackOrder.filter(id => !selectedTrackIds.has(id)),
ids: trackOrder.filter((id) => !selectedTrackIds.has(id)),
});
};
}
@ -48,7 +48,7 @@ export function removeSelectedTracks(): Thunk {
}
export function removeAllTracks(): Thunk {
return dispatch => {
return (dispatch) => {
// It's a bit funky that we need to do both of these.
dispatch({ type: STOP });
dispatch({ type: REMOVE_ALL_TRACKS });
@ -67,7 +67,7 @@ export function sortListByTitle(): Thunk {
return (dispatch, getState) => {
const state = getState();
const tracks = Selectors.getTracks(state);
const trackOrder = sort(Selectors.getTrackOrder(state), i =>
const trackOrder = sort(Selectors.getTrackOrder(state), (i) =>
`${tracks[i].title}`.toLowerCase()
);
return dispatch({ type: SET_TRACK_ORDER, trackOrder });
@ -128,14 +128,14 @@ export function dragSelected(offset: number): Thunk {
const trackOrder = Selectors.getTrackOrder(state);
const selectedIds = Selectors.getSelectedTrackIds(state);
const firstSelected = trackOrder.findIndex(
trackId => tracks[trackId] && selectedIds.has(trackId)
(trackId) => tracks[trackId] && selectedIds.has(trackId)
);
if (firstSelected === -1) {
return;
}
const lastSelected = findLastIndex(
trackOrder,
trackId => tracks[trackId] && selectedIds.has(trackId)
(trackId) => tracks[trackId] && selectedIds.has(trackId)
);
if (lastSelected === -1) {
throw new Error("We found a first selected, but not a last selected.");

View file

@ -156,7 +156,7 @@ export function centerWindows(box: {
// A layout has been suplied. We will compute the bounding box and
// center the given layout.
const bounding = Utils.calculateBoundingBox(
windowsInfo.filter(w => getOpen(w.key))
windowsInfo.filter((w) => getOpen(w.key))
);
if (bounding == null) {
@ -214,7 +214,7 @@ export function ensureWindowsAreOnScreen(): Thunk {
const getOpen = Selectors.getWindowOpen(state);
const { height, width } = Utils.getWindowSize();
const bounding = Utils.calculateBoundingBox(
windowsInfo.filter(w => getOpen(w.key))
windowsInfo.filter((w) => getOpen(w.key))
);
if (bounding == null) {
// There are no windows visible, so there's no work to do.
@ -252,7 +252,7 @@ export function ensureWindowsAreOnScreen(): Thunk {
moveX = bounding.right - width;
}
const newPositions = Utils.objectMap(positions, position => ({
const newPositions = Utils.objectMap(positions, (position) => ({
x: position.x - moveX,
y: position.y - moveY,
}));

View file

@ -25,7 +25,7 @@ export default function Balance({ style, className, id }: Props) {
step="1"
value={balance}
style={style}
onChange={e => setBalance(Number(e.target.value))}
onChange={(e) => setBalance(Number(e.target.value))}
onMouseDown={() => setFocus("balance")}
onMouseUp={unsetFocus}
title="Balance"

View file

@ -7,9 +7,7 @@ interface Props extends React.HTMLAttributes<HTMLSpanElement> {
}
export const characterClassName = (char: string | number) =>
`character-${deburr(char.toString())
.toLowerCase()
.charCodeAt(0)}`;
`character-${deburr(char.toString()).toLowerCase().charCodeAt(0)}`;
const Character = React.memo(
({ children: char, className, ...passThrough }: Props) => {

View file

@ -20,7 +20,7 @@ export default function ClipPaths({ children }: Props) {
return createPortal(
<svg height={0} width={0}>
<defs>
{Object.keys(children).map(id => (
{Object.keys(children).map((id) => (
<clipPath id={id} key={id}>
{children[id].map((points, i) => (
<polygon points={points} key={i} />

View file

@ -5,7 +5,7 @@ import * as Actions from "../../actionCreators";
import { useTypedSelector, useActionCreator } from "../../hooks";
const EqAuto = React.memo(() => {
const selected = useTypedSelector(state => state.equalizer.auto);
const selected = useTypedSelector((state) => state.equalizer.auto);
const toggleAuto = useActionCreator(Actions.toggleEqAuto);
return (
<div id="auto" className={classnames({ selected })} onClick={toggleAuto} />

View file

@ -78,7 +78,7 @@ function drawEqLine({
preampLineImage.height
);
const amplitudes = BANDS.map(band => sliders[band]);
const amplitudes = BANDS.map((band) => sliders[band]);
canvasCtx.fillStyle = colorPattern;
const paddingLeft = 2; // TODO: This should be 1.5

View file

@ -16,7 +16,7 @@ const PresetsContextMenu = () => {
renderMenu={() => (
<>
<Parent label="Load">
{builtin.presets.map(preset => (
{builtin.presets.map((preset) => (
<Node
key={preset.name}
onClick={() => setEqFromObject(preset)}

View file

@ -69,12 +69,12 @@ const EqualizerWindow = () => {
<div id="plus12db" onClick={setEqToMax} />
<div id="zerodb" onClick={setEqToMid} />
<div id="minus12db" onClick={setEqToMin} />
{BANDS.map(hertz => (
{BANDS.map((hertz) => (
<Band
key={hertz}
id={bandClassName(hertz)}
band={hertz}
onChange={value => setHertzValue(hertz, value)}
onChange={(value) => setHertzValue(hertz, value)}
/>
))}
</div>

View file

@ -44,14 +44,14 @@ function FocusTarget({ onKeyDown, windowId, children }: Props) {
return;
}
const observer = new MutationObserver(mutations => {
const observer = new MutationObserver((mutations) => {
// In the common case we won't have focused the body, so we can do this
// inexpensive check first to avoid calling the more expensive `O(n)`
// check of the individual mutations.
if (document.activeElement !== document.body) {
return;
}
if (mutations.some(mutation => mutation.removedNodes.length > 0)) {
if (mutations.some((mutation) => mutation.removedNodes.length > 0)) {
ref.focus();
}
});

View file

@ -95,7 +95,7 @@ export const GenWindow = ({ children, title, windowId, onKeyDown }: Props) => {
<div className="gen-bottom-right draggable">
<ResizeTarget
currentSize={windowSize}
setWindowSize={size => setWindowSize(windowId, size)}
setWindowSize={(size) => setWindowSize(windowId, size)}
id={"gen-resize-target"}
/>
</div>

View file

@ -13,7 +13,7 @@ function setFocusDouble(): Action {
}
function mouseUp(): Thunk {
return dispatch => {
return (dispatch) => {
dispatch(Actions.toggleDoubleSizeMode());
dispatch(Actions.unsetFocus());
};

View file

@ -53,7 +53,7 @@ const MainContextMenu = React.memo((props: Props) => {
)}
</Parent>
<Hr />
{Object.keys(genWindows).map(i => (
{Object.keys(genWindows).map((i) => (
<Node
key={i}
label={genWindows[i].title}

View file

@ -27,7 +27,7 @@ const Position = React.memo(() => {
const dispatch = useTypedDispatch();
const seekToPercentComplete = React.useCallback(
e => {
(e) => {
dispatch({
type: SEEK_TO_PERCENT_COMPLETE,
percent: Number((e.target as HTMLInputElement).value),
@ -38,7 +38,7 @@ const Position = React.memo(() => {
);
const setPosition = React.useCallback(
e => {
(e) => {
dispatch({ type: SET_FOCUS, input: "position" });
dispatch({
type: SET_SCRUB_POSITION,

View file

@ -10,7 +10,7 @@ const Shade = React.memo(() => {
<ClickedDiv
id="shade"
onMouseDown={handleClick}
onDoubleClick={e => e.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
title="Toggle Windowshade Mode"
/>
);

View file

@ -111,11 +111,11 @@ function PresetOverlay({ height, width }: Props) {
(e: React.KeyboardEvent<HTMLDivElement>) => {
switch (e.keyCode) {
case 38: // up arrow
setSelectedListIndex(value => Math.max(value - 1, 0));
setSelectedListIndex((value) => Math.max(value - 1, 0));
e.stopPropagation();
break;
case 40: // down arrow
setSelectedListIndex(value => Math.min(value + 1, maxListIndex));
setSelectedListIndex((value) => Math.min(value + 1, maxListIndex));
e.stopPropagation();
break;
case 13: // enter

View file

@ -6,7 +6,7 @@ import MiscOptionsContextMenu from "./MiscOptionsContextMenu";
const MiscMenu = () => (
<PlaylistMenu id="playlist-misc-menu">
<div className="sort-list" onClick={e => e.stopPropagation()}>
<div className="sort-list" onClick={(e) => e.stopPropagation()}>
<SortContextMenu />
</div>
<div
@ -14,7 +14,7 @@ const MiscMenu = () => (
onClick={() => alert("Not supported in Webamp")}
/>
<div className="misc-options" onClick={e => e.stopPropagation()}>
<div className="misc-options" onClick={(e) => e.stopPropagation()}>
<MiscOptionsContextMenu />
</div>
</PlaylistMenu>

View file

@ -38,7 +38,7 @@ function PlaylistMenu(props: Props) {
selected,
})}
ref={setRef}
onClick={() => setSelected(selected_ => !selected_)}
onClick={() => setSelected((selected_) => !selected_)}
>
<div className="bar" />
{selected && (

View file

@ -17,7 +17,7 @@ function PlaylistResizeTarget({ widthOnly }: Props) {
<ResizeTarget
currentSize={currentSize}
id="playlist-resize-target"
setWindowSize={size => {
setWindowSize={(size) => {
setWindowSize("playlist", size);
}}
widthOnly={widthOnly}

View file

@ -59,9 +59,9 @@ function TrackCell({ children, handleMoveClick, index, id }: Props) {
<div
className={classnames("track-cell", { selected, current })}
style={style}
onClick={e => e.stopPropagation()}
onClick={(e) => e.stopPropagation()}
onMouseDown={onMouseDown}
onContextMenu={e => e.preventDefault()}
onContextMenu={(e) => e.preventDefault()}
onDoubleClick={() => playTrack(id)}
>
{children}

View file

@ -95,7 +95,7 @@ function TrackList() {
))}
</div>
<div className="playlist-track-durations">
{_renderTracks(id => getTimeStr(tracks[id].duration))}
{_renderTracks((id) => getTimeStr(tracks[id].duration))}
</div>
</div>
);

View file

@ -44,11 +44,11 @@ const getCssRules = createSelector(
return null;
}
const cssRules = [];
Object.keys(imageSelectors).forEach(imageName => {
Object.keys(imageSelectors).forEach((imageName) => {
const imageUrl =
skinImages[imageName] || skinImages[FALLBACKS[imageName]];
if (imageUrl) {
imageSelectors[imageName].forEach(selector => {
imageSelectors[imageName].forEach((selector) => {
cssRules.push(
`${CSS_PREFIX} ${selector} {background-image: url(${imageUrl})}`
);
@ -57,7 +57,7 @@ const getCssRules = createSelector(
});
if (skinGenLetterWidths != null) {
LETTERS.forEach(letter => {
LETTERS.forEach((letter) => {
const width = skinGenLetterWidths[`GEN_TEXT_${letter}`];
const selectedWidth =
skinGenLetterWidths[`GEN_TEXT_SELECTED_${letter}`];
@ -69,10 +69,10 @@ const getCssRules = createSelector(
);
});
}
Object.keys(cursorSelectors).forEach(cursorName => {
Object.keys(cursorSelectors).forEach((cursorName) => {
const cursorUrl = skinCursors[cursorName];
if (cursorUrl) {
cursorSelectors[cursorName].forEach(selector => {
cursorSelectors[cursorName].forEach((selector) => {
cssRules.push(
`${
// TODO: Fix this hack
@ -106,7 +106,7 @@ const getCssRules = createSelector(
}
);
const getClipPaths = createSelector(Selectors.getSkinRegion, skinRegion => {
const getClipPaths = createSelector(Selectors.getSkinRegion, (skinRegion) => {
const clipPaths: { [id: string]: string[] } = {};
for (const [regionName, polygons] of Object.entries(skinRegion)) {
if (polygons) {

View file

@ -15,7 +15,7 @@ const SkinContextMenu = () => {
<Node onClick={openSkinFileDialog} label="Load Skin..." />
<Hr />
<Node onClick={loadDefaultSkin} label={"<Base Skin>"} />
{availableSkins.map(skin => (
{availableSkins.map((skin) => (
<Node
key={skin.url}
onClick={() => setSkin(skin.url)}

View file

@ -114,7 +114,7 @@ class Visualizer extends React.Component {
const loop = () => {
if (this.props.status === MEDIA_STATUS.PLAYING) {
if (this.props.dummyVizData) {
Object.keys(this.props.dummyVizData).forEach(i => {
Object.keys(this.props.dummyVizData).forEach((i) => {
this._printBar(i, this.props.dummyVizData[i]);
});
} else {
@ -310,7 +310,7 @@ class Visualizer extends React.Component {
return (
<canvas
id="visualizer"
ref={node => (this.canvas = node)}
ref={(node) => (this.canvas = node)}
style={{ width, height }}
width={width * PIXEL_DENSITY}
height={height * PIXEL_DENSITY}
@ -320,7 +320,7 @@ class Visualizer extends React.Component {
}
}
const mapStateToProps = state => ({
const mapStateToProps = (state) => ({
colors: state.display.skinColors,
style: getVisualizerStyle(state),
width: getWindowShade(state)("main") ? 38 : 76,

View file

@ -25,7 +25,7 @@ export default function Volume({ id, style, className }: Props) {
value={volume}
style={style}
className={className}
onChange={e => setVolume(Number(e.target.value))}
onChange={(e) => setVolume(Number(e.target.value))}
onMouseDown={() => setFocus("volume")}
onMouseUp={unsetFocus}
title="Volume Bar"

View file

@ -48,7 +48,7 @@ function useHandleMouseDown(propsWindows: {
y: ee.clientY - mouseStart.y,
};
const proposedWindows = moving.map(node => ({
const proposedWindows = moving.map((node) => ({
...node,
...SnapUtils.applyDiff(node, proposedDiff),
}));
@ -75,7 +75,7 @@ function useHandleMouseDown(propsWindows: {
);
const windowPositionDiff: { [windowId: string]: Point } = {};
moving.forEach(w => {
moving.forEach((w) => {
windowPositionDiff[w.key] = SnapUtils.applyDiff(w, finalDiff);
});
@ -108,9 +108,9 @@ function useHandleMouseDown(propsWindows: {
}
const windows = windowsInfo.filter(
w => propsWindows[w.key] != null && !getWindowHidden(w.key)
(w) => propsWindows[w.key] != null && !getWindowHidden(w.key)
);
const targetNode = windows.find(node => node.key === key);
const targetNode = windows.find((node) => node.key === key);
if (targetNode == null) {
throw new Error(`Tried to move a node that does not exist: ${key}`);
}
@ -122,7 +122,7 @@ function useHandleMouseDown(propsWindows: {
movingSet = findAllConnected(windows, targetNode);
}
const stationary = windows.filter(w => !movingSet.has(w));
const stationary = windows.filter((w) => !movingSet.has(w));
const moving = Array.from(movingSet);
const mouseStart = { x: e.clientX, y: e.clientY };
@ -139,7 +139,7 @@ export default function WindowManager({ windows: propsWindows }: Props) {
const setFocusedWindow = useActionCreator(Actions.setFocusedWindow);
const handleMouseDown = useHandleMouseDown(propsWindows);
const windows = windowsInfo.filter(w => propsWindows[w.key]);
const windows = windowsInfo.filter((w) => propsWindows[w.key]);
const onBlur = useCallback(
// I give up on trying to type things with `relatedTarget`.
@ -158,7 +158,7 @@ export default function WindowManager({ windows: propsWindows }: Props) {
return (
<>
{windows.map(w => (
{windows.map((w) => (
<div
key={w.key}
onBlur={onBlur}

View file

@ -10,7 +10,7 @@ export default class Emitter {
eventListeners.push(callback);
this._listeners[event] = eventListeners;
const unsubscribe = () => {
this._listeners[event] = eventListeners.filter(cb => cb !== callback);
this._listeners[event] = eventListeners.filter((cb) => cb !== callback);
};
return unsubscribe;
}
@ -18,7 +18,7 @@ export default class Emitter {
trigger(event: string, ...args: any[]) {
const callbacks = this._listeners[event];
if (callbacks) {
callbacks.forEach(cb => cb(...args));
callbacks.forEach((cb) => cb(...args));
}
}

View file

@ -42,7 +42,7 @@ export function genMediaDuration(url: string): Promise<number> {
// TODO: Not sure if this really gets cleaned up.
};
audio.addEventListener("durationchange", durationChange);
audio.addEventListener("error", e => {
audio.addEventListener("error", (e) => {
reject(e);
});
audio.src = url;
@ -90,7 +90,7 @@ export async function promptForFileReferences(
directory: false,
}
): Promise<FileList> {
return new Promise<FileList>(resolve => {
return new Promise<FileList>((resolve) => {
// Does this represent a memory leak somehow?
// Can this fail? Do we ever reject?
const fileInput = document.createElement("input");

View file

@ -28,7 +28,7 @@ export function usePromiseValueOrNull<T>(propValue: Promise<T>): T | null {
const [value, setValue] = useState<T | null>(null);
useEffect(() => {
let disposed = false;
propValue.then(resolvedValue => {
propValue.then((resolvedValue) => {
if (disposed) {
return;
}

View file

@ -27,7 +27,7 @@ export default class LoadQueue {
return () => {
// TODO: Could return a boolean representing if the task has already been
// kicked off.
this._queue = this._queue.filter(t1 => t1 !== t);
this._queue = this._queue.filter((t1) => t1 !== t);
};
}

View file

@ -49,7 +49,7 @@ export default class ElementSource {
});
// TODO: #leak
this._audio.addEventListener("error", e => {
this._audio.addEventListener("error", (e) => {
switch (this._audio.error!.code) {
case 1:
// The fetching of the associated resource was aborted by the user's request.

View file

@ -136,7 +136,7 @@ const Playlist = (props: Props) => (
<ul>
<Font face="Arial" color="#FFFFFF">
<small>
{props.tracks.map(track => (
{props.tracks.map((track) => (
<span key={track}>
{track}
<br />

View file

@ -90,7 +90,7 @@ const playlist = (
return {
...state,
selectedTracks: new Set(
state.trackOrder.filter(id => !state.selectedTracks.has(id))
state.trackOrder.filter((id) => !state.selectedTracks.has(id))
),
};
case REMOVE_ALL_TRACKS:
@ -108,10 +108,12 @@ const playlist = (
const { currentTrack } = state;
return {
...state,
trackOrder: state.trackOrder.filter(trackId => !actionIds.has(trackId)),
trackOrder: state.trackOrder.filter(
(trackId) => !actionIds.has(trackId)
),
currentTrack: actionIds.has(Number(currentTrack)) ? null : currentTrack,
selectedTracks: new Set(
Array.from(state.selectedTracks).filter(id => actionIds.has(id))
Array.from(state.selectedTracks).filter((id) => actionIds.has(id))
),
// TODO: This could probably be made to work, but we clear it just to be safe.
lastSelectedIndex: null,
@ -155,7 +157,7 @@ const playlist = (
...state,
trackOrder: moveSelected(
state.trackOrder,
i => state.selectedTracks.has(state.trackOrder[i]),
(i) => state.selectedTracks.has(state.trackOrder[i]),
action.offset
),
// TODO: This could probably be made to work, but we clear it just to be safe.

View file

@ -124,7 +124,7 @@ const windows = (
let windowOrder = state.windowOrder;
if (action.window != null) {
windowOrder = [
...state.windowOrder.filter(windowId => windowId !== action.window),
...state.windowOrder.filter((windowId) => windowId !== action.window),
action.window,
];
}
@ -215,7 +215,7 @@ const windows = (
case RESET_WINDOW_SIZES:
return {
...state,
genWindows: Utils.objectMap(state.genWindows, w => ({
genWindows: Utils.objectMap(state.genWindows, (w) => ({
...w,
// Not sure why TypeScript can't figure this out for itself.
size: [0, 0] as [number, number],
@ -256,7 +256,7 @@ export function getSerializedState(
): WindowsSerializedStateV1 {
return {
positionsAreRelative: state.positionsAreRelative,
genWindows: Utils.objectMap(state.genWindows, w => {
genWindows: Utils.objectMap(state.genWindows, (w) => {
return {
size: w.size,
open: w.open,

View file

@ -13,18 +13,18 @@ type RegionData = { [section: string]: string[] };
export default function regionParser(regionStr: string): RegionData {
const iniData = parseIni(regionStr);
const data: RegionData = {};
Object.keys(iniData).forEach(section => {
Object.keys(iniData).forEach((section) => {
const { numpoints, pointlist } = iniData[section];
if (!numpoints || !pointlist) {
return;
}
const pointCounts = numpoints.split(/\s*,\s*/).filter(val => val !== "");
const pointCounts = numpoints.split(/\s*,\s*/).filter((val) => val !== "");
const points = pointPairs(
// points can be separated by spaces, or by commas
pointlist.split(/\s*[, ]\s*/).filter(val => val !== "")
pointlist.split(/\s*[, ]\s*/).filter((val) => val !== "")
);
let pointIndex = 0;
const polygons = pointCounts.map(numStr => {
const polygons = pointCounts.map((numStr) => {
const num = Number(numStr);
const polygon = points.slice(pointIndex, pointIndex + num).join(" ");
if (!polygon.length) {
@ -35,7 +35,7 @@ export default function regionParser(regionStr: string): RegionData {
return polygon;
});
const validPolygons = polygons.filter(
polygon => polygon != null
(polygon) => polygon != null
) as string[];
if (validPolygons.length) {
data[section] = validPolygons;

View file

@ -46,7 +46,7 @@ export function getPositionDiff(
function walkRight(key: WindowId) {
const node = newGraph[key];
const nodeSizeDiff = sizeDiff[key];
node.left.forEach(left => {
node.left.forEach((left) => {
positionDiff[left].x += nodeSizeDiff.width + positionDiff[key].x;
walkRight(left);
});
@ -55,7 +55,7 @@ export function getPositionDiff(
function walkDown(key: WindowId) {
const node = newGraph[key];
const nodeSizeDiff = sizeDiff[key];
node.above.forEach(above => {
node.above.forEach((above) => {
positionDiff[above].y += nodeSizeDiff.height + positionDiff[key].y;
walkDown(above);
});

View file

@ -41,12 +41,12 @@ import { SerializedStateV1 } from "./serializedStates/v1Types";
export const getSliders = (state: AppState) => state.equalizer.sliders;
export const getEqfData = createSelector(getSliders, sliders => {
export const getEqfData = createSelector(getSliders, (sliders) => {
const preset: { [key: string]: number | string } = {
name: "Entry1",
preamp: Utils.denormalizeEqBand(sliders.preamp),
};
BANDS.forEach(band => {
BANDS.forEach((band) => {
preset[`hz${band}`] = Utils.denormalizeEqBand(sliders[band]);
});
const eqfData = {
@ -66,19 +66,19 @@ export const getTrackOrder = (state: AppState) => state.playlist.trackOrder;
export const getTrackCount = createSelector(
getTrackOrder,
trackOrder => trackOrder.length
(trackOrder) => trackOrder.length
);
export const getOrderedTracks = createSelector(
getTracks,
getTrackOrder,
(tracks, trackOrder) => trackOrder.filter(id => tracks[id])
(tracks, trackOrder) => trackOrder.filter((id) => tracks[id])
);
const getOrderedTrackObjects = createSelector(
getTracks,
getOrderedTracks,
(tracks, trackOrder): PlaylistTrack[] => trackOrder.map(id => tracks[id])
(tracks, trackOrder): PlaylistTrack[] => trackOrder.map((id) => tracks[id])
);
export const getSelectedTrackIds = (state: AppState): Set<number> => {
@ -88,7 +88,7 @@ export const getSelectedTrackIds = (state: AppState): Set<number> => {
export const getSelectedTrackObjects = createSelector(
getOrderedTrackObjects,
getSelectedTrackIds,
(tracks, selectedIds) => tracks.filter(track => selectedIds.has(track.id))
(tracks, selectedIds) => tracks.filter((track) => selectedIds.has(track.id))
);
// If a duration is `null`, it counts as zero, which seems fine enough.
@ -126,7 +126,7 @@ export const getCurrentTrackIndex = (state: AppState): number => {
export const getCurrentTrackNumber = createSelector(
getCurrentTrackIndex,
currentTrackIndex => currentTrackIndex + 1
(currentTrackIndex) => currentTrackIndex + 1
);
export const getCurrentTrackId = (state: AppState) =>
@ -187,31 +187,31 @@ export const getGenWindows = (state: AppState) => {
return state.windows.genWindows;
};
export const getWindowOpen = createSelector(getGenWindows, genWindows => {
export const getWindowOpen = createSelector(getGenWindows, (genWindows) => {
return (windowId: WindowId) => genWindows[windowId].open;
});
export const getWindowHidden = createSelector(getGenWindows, genWindows => {
export const getWindowHidden = createSelector(getGenWindows, (genWindows) => {
return (windowId: WindowId) => genWindows[windowId].hidden;
});
export const getWindowShade = createSelector(getGenWindows, genWindows => {
export const getWindowShade = createSelector(getGenWindows, (genWindows) => {
return (windowId: WindowId) => genWindows[windowId].shade;
});
export const getWindowSize = createSelector(getGenWindows, genWindows => {
export const getWindowSize = createSelector(getGenWindows, (genWindows) => {
return (windowId: WindowId) => genWindows[windowId].size;
});
export const getWindowPositions = createSelector(
getGenWindows,
(windows): WindowPositions => Utils.objectMap(windows, w => w.position)
(windows): WindowPositions => Utils.objectMap(windows, (w) => w.position)
);
const BASE_WINDOW_HEIGHT = 58;
export const getNumberOfVisibleTracks = createSelector(
getWindowSize,
getWindowSize_ => {
(getWindowSize_) => {
const playlistSize = getWindowSize_("playlist");
return Math.floor(
(BASE_WINDOW_HEIGHT + WINDOW_RESIZE_SEGMENT_HEIGHT * playlistSize[1]) /
@ -269,7 +269,7 @@ export function getAllTracksAreVisible(state: AppState): boolean {
export const getTrackIsVisibleFunction = createSelector(
getVisibleTrackIds,
visibleTrackIds => {
(visibleTrackIds) => {
return (id: number) => visibleTrackIds.includes(id);
}
);
@ -277,7 +277,7 @@ export const getTrackIsVisibleFunction = createSelector(
export const getVisibleTracks = createSelector(
getVisibleTrackIds,
getTracks,
(visibleTrackIds, tracks) => visibleTrackIds.map(id => tracks[id])
(visibleTrackIds, tracks) => visibleTrackIds.map((id) => tracks[id])
);
export const getPlaylist = (state: AppState) => state.playlist;
@ -291,7 +291,7 @@ export const getDuration = (state: AppState): number | null => {
return currentTrack && currentTrack.duration;
};
export const getTrackDisplayName = createSelector(getTracks, tracks => {
export const getTrackDisplayName = createSelector(getTracks, (tracks) => {
return defaultMemoize((trackId: number | null) =>
fromTracks.getTrackDisplayName(tracks, trackId)
);
@ -370,7 +370,7 @@ export const getMediaText = createSelector(
export const getNumberOfTracks = (state: AppState) =>
getTrackOrder(state).length;
const getPlaylistDuration = createSelector(getTracks, tracks =>
const getPlaylistDuration = createSelector(getTracks, (tracks) =>
Object.values(tracks).reduce(
(total, track) => total + (track.duration || 0),
0
@ -444,11 +444,11 @@ export const getWindowSizes = createSelector(
getGenWindows,
getDoubled,
(windows, doubled) => {
return Utils.objectMap(windows, w => getWPixelSize(w, doubled));
return Utils.objectMap(windows, (w) => getWPixelSize(w, doubled));
}
);
export const getWindowPixelSize = createSelector(getWindowSizes, sizes => {
export const getWindowPixelSize = createSelector(getWindowSizes, (sizes) => {
return (windowId: WindowId) => sizes[windowId];
});
@ -462,7 +462,7 @@ export const getNormalizedWindowOrder = createSelector(
return [
WINDOWS.MAIN,
...windowOrder.filter(
windowId => windowId !== WINDOWS.MAIN && genWindows[windowId] != null
(windowId) => windowId !== WINDOWS.MAIN && genWindows[windowId] != null
),
];
}
@ -474,7 +474,11 @@ export const getWindowsInfo = createSelector(
getWindowPositions,
getNormalizedWindowOrder,
(sizes, positions, windowOrder): WindowInfo[] => {
return windowOrder.map(key => ({ key, ...sizes[key], ...positions[key] }));
return windowOrder.map((key) => ({
key,
...sizes[key],
...positions[key],
}));
}
);
@ -540,8 +544,8 @@ export function getBrowserWindowSize(
return state.windows.browserWindowSize;
}
export const getOpenWindows = createSelector(getGenWindows, genWindows =>
Utils.objectFilter(genWindows, w => w.open)
export const getOpenWindows = createSelector(getGenWindows, (genWindows) =>
Utils.objectFilter(genWindows, (w) => w.open)
);
export const getStackedLayoutPositions = createSelector(
@ -549,7 +553,7 @@ export const getStackedLayoutPositions = createSelector(
getDoubled,
(openWindows, doubled): WindowPositions => {
let offset = 0;
return Utils.objectMap(openWindows, w => {
return Utils.objectMap(openWindows, (w) => {
const position = { x: 0, y: offset };
offset += getWPixelSize(w, doubled).height;
return position;
@ -675,7 +679,7 @@ export function getCurrentPreset(state: AppState): any | null {
}
export function getPresetNames(state: AppState): string[] {
return state.milkdrop.presets.map(preset => preset.name);
return state.milkdrop.presets.map((preset) => preset.name);
}
export function getPresetOverlayOpen(state: AppState): boolean {

View file

@ -141,14 +141,14 @@ describe("can serialize", () => {
testSerialization({
name: "equalizer band",
action: Actions.setEqBand(60, 100),
selector: state => Selectors.getSliders(state)[60],
selector: (state) => Selectors.getSliders(state)[60],
expected: 100,
});
testSerialization({
name: "equalizer preamp",
action: Actions.setPreamp(10),
selector: state => Selectors.getSliders(state).preamp,
selector: (state) => Selectors.getSliders(state).preamp,
expected: 10,
});
@ -182,21 +182,21 @@ describe("can serialize", () => {
testSerialization({
name: "window size",
action: Actions.setWindowSize("playlist", [4, 5]),
selector: state => Selectors.getWindowSize(state)("playlist"),
selector: (state) => Selectors.getWindowSize(state)("playlist"),
expected: [4, 5],
});
testSerialization({
name: "window open",
action: Actions.closeWindow("playlist"),
selector: state => Selectors.getWindowOpen(state)("playlist"),
selector: (state) => Selectors.getWindowOpen(state)("playlist"),
expected: false,
});
testSerialization({
name: "window hidden",
action: Actions.hideWindow("playlist"),
selector: state => Selectors.getWindowHidden(state)("playlist"),
selector: (state) => Selectors.getWindowHidden(state)("playlist"),
expected: true,
});
@ -204,14 +204,14 @@ describe("can serialize", () => {
name: "window shade",
// @ts-ignore
action: Actions.toggleEqualizerShadeMode(),
selector: state => Boolean(Selectors.getWindowShade(state)("equalizer")),
selector: (state) => Boolean(Selectors.getWindowShade(state)("equalizer")),
expected: true,
});
testSerialization({
name: "main window position",
action: Actions.updateWindowPositions({ main: { x: 100, y: 100 } }),
selector: state => Selectors.getWindowPosition(state)("main"),
selector: (state) => Selectors.getWindowPosition(state)("main"),
expected: { x: 100, y: 100 },
});
@ -225,7 +225,7 @@ describe("can serialize", () => {
testSerialization({
name: "focused window",
action: Actions.setFocusedWindow("equalizer"),
selector: state => Selectors.getFocusedWindow(state),
selector: (state) => Selectors.getFocusedWindow(state),
expected: "equalizer",
});
});

View file

@ -4,7 +4,7 @@ import { LETTERS, DEFAULT_SKIN } from "./constants";
import { parseViscolors } from "./utils";
import * as SkinParserUtils from "./skinParserUtils";
const shallowMerge = objs =>
const shallowMerge = (objs) =>
objs.reduce((prev, img) => Object.assign(prev, img), {});
const CURSORS = [
@ -63,7 +63,7 @@ async function genVizColors(zip) {
async function genImages(zip) {
const imageObjs = await Promise.all(
Object.keys(SKIN_SPRITES).map(fileName =>
Object.keys(SKIN_SPRITES).map((fileName) =>
SkinParserUtils.getSpriteUrisFromFilename(zip, fileName)
)
);
@ -72,7 +72,7 @@ async function genImages(zip) {
}
async function genCursors(zip) {
const cursorObjs = await Promise.all(
CURSORS.map(async cursorName => ({
CURSORS.map(async (cursorName) => ({
[cursorName]: await SkinParserUtils.getCursorFromFilename(
zip,
cursorName
@ -105,13 +105,13 @@ async function genGenTextSprites(zip) {
context.drawImage(img, 0, 0);
const getLetters = (y, prefix) => {
const getColorAt = x => context.getImageData(x, y, 1, 1).data.join(",");
const getColorAt = (x) => context.getImageData(x, y, 1, 1).data.join(",");
let x = 1;
const backgroundColor = getColorAt(0);
const height = 7;
return LETTERS.map(letter => {
return LETTERS.map((letter) => {
let nextBackground = x;
while (
getColorAt(nextBackground) !== backgroundColor &&
@ -132,7 +132,7 @@ async function genGenTextSprites(zip) {
...getLetters(88, "GEN_TEXT_SELECTED"),
...getLetters(96, "GEN_TEXT"),
];
sprites.forEach(sprite => {
sprites.forEach((sprite) => {
letterWidths[sprite.name] = sprite.width;
});
return [letterWidths, SkinParserUtils.getSpriteUrisFromImg(img, sprites)];

View file

@ -62,7 +62,7 @@ export function getSpriteUrisFromImg(
throw new Error("Failed to get canvas context");
}
const images: { [spriteName: string]: string } = {};
sprites.forEach(sprite => {
sprites.forEach((sprite) => {
canvas.height = sprite.height;
canvas.width = sprite.width;
@ -133,7 +133,7 @@ export async function getPlaylistStyle(zip: JSZip): Promise<PlaylistStyle> {
// Winamp seems to permit colors that contain too many characters.
// For compatibility with existing skins, we normalize them here.
["normal", "current", "normalbg", "selectedbg", "mbFG", "mbBG"].forEach(
colorKey => {
(colorKey) => {
let color = data[colorKey];
if (!color) {
return;

View file

@ -320,13 +320,13 @@ export const imageSelectors: Selectors = {
GEN_CLOSE_SELECTED: [".gen-window .gen-close:active"],
};
Object.keys(FONT_LOOKUP).forEach(character => {
Object.keys(FONT_LOOKUP).forEach((character) => {
const key = imageConstFromChar(character);
const code = character.charCodeAt(0);
imageSelectors[key] = [`.character-${code}`];
});
LETTERS.forEach(character => {
LETTERS.forEach((character) => {
imageSelectors[`GEN_TEXT_${character}`] = [
`.gen-text-${character.toLowerCase()}`,
];

View file

@ -1,36 +1,36 @@
import skinSprites from "./skinSprites";
const each = (obj, iterator) => {
Object.keys(obj).forEach(key => {
Object.keys(obj).forEach((key) => {
iterator(obj[key]);
});
};
const getNames = arr => arr.map(item => item.name);
const getNames = (arr) => arr.map((item) => item.name);
describe("skinSprites", () => {
it("each spritSheet has a unique name", () => {
const spriteSheetNames = Object.keys(skinSprites);
const seenNames = [];
spriteSheetNames.forEach(name => {
spriteSheetNames.forEach((name) => {
expect(seenNames).not.toContain(name);
seenNames.push(name);
});
});
it("each sprite has a unique name", () => {
let spriteNames = [];
each(skinSprites, spriteSheet => {
each(skinSprites, (spriteSheet) => {
spriteNames = spriteNames.concat(getNames(spriteSheet));
});
const seenNames = [];
spriteNames.forEach(name => {
spriteNames.forEach((name) => {
expect(seenNames).not.toContain(name);
seenNames.push(name);
});
});
it("each sprite has the needed properties", () => {
each(skinSprites, spriteSheet => {
spriteSheet.forEach(sprite => {
each(skinSprites, (spriteSheet) => {
spriteSheet.forEach((sprite) => {
expect(typeof sprite.name).toBe("string");
expect(typeof sprite.x).toBe("number");
expect(typeof sprite.y).toBe("number");

View file

@ -75,7 +75,7 @@ export const snapToMany = (boxA: Box, otherBoxes: Box[]): Diff => {
let x: number | undefined;
let y: number | undefined;
otherBoxes.forEach(boxB => {
otherBoxes.forEach((boxB) => {
const newPos = snap(boxA, boxB);
x = newPos.x || x;
y = newPos.y || y;
@ -133,7 +133,7 @@ export const boundingBox = (nodes: Box[]): Box => {
left: left(firstNode),
};
boxes.forEach(node => {
boxes.forEach((node) => {
bounding.top = Math.min(bounding.top, top(node));
bounding.right = Math.max(bounding.right, right(node));
bounding.bottom = Math.max(bounding.bottom, bottom(node));

View file

@ -14,7 +14,7 @@ const compose = composeWithDevTools({
actionsBlacklist: [UPDATE_TIME_ELAPSED, STEP_MARQUEE],
});
export default function(
export default function (
media: Media,
actionEmitter: Emitter,
customMiddlewares: Middleware[] = [],

View file

@ -334,7 +334,7 @@ describe("moveSelected", () => {
expect(
moveSelected(
["a", "b", "c", "d", "e", "f", "g", "h"],
i => new Set([1]).has(i),
(i) => new Set([1]).has(i),
1
)
).toEqual(["a", "c", "b", "d", "e", "f", "g", "h"]);
@ -343,7 +343,7 @@ describe("moveSelected", () => {
expect(
moveSelected(
["a", "b", "c", "d", "e", "f", "g", "h"],
i => new Set([1]).has(i),
(i) => new Set([1]).has(i),
3
)
).toEqual(["a", "c", "d", "e", "b", "f", "g", "h"]);
@ -352,18 +352,18 @@ describe("moveSelected", () => {
expect(
moveSelected(
["a", "b", "c", "d", "e", "f", "g", "h"],
i => new Set([1, 2]).has(i),
(i) => new Set([1, 2]).has(i),
3
)
).toEqual(["a", "d", "e", "f", "b", "c", "g", "h"]);
});
it("works for a simple example", () => {
const arr = [true, false, false];
expect(moveSelected(arr, i => arr[i], 1)).toEqual([false, true, false]);
expect(moveSelected(arr, (i) => arr[i], 1)).toEqual([false, true, false]);
});
it("works for a simple negative example", () => {
const arr = [false, false, true];
expect(moveSelected(arr, i => arr[i], -1)).toEqual([false, true, false]);
expect(moveSelected(arr, (i) => arr[i], -1)).toEqual([false, true, false]);
});
});

View file

@ -91,9 +91,9 @@ export const parseViscolors = (text: string): string[] => {
const regex = /^\s*(\d+)\s*,?\s*(\d+)\s*,?\s*(\d+)/;
const colors = [...DEFAULT_SKIN.colors];
entries
.map(line => regex.exec(line))
.map((line) => regex.exec(line))
.filter(Boolean)
.map(matches => (matches as RegExpExecArray).slice(1, 4).join(","))
.map((matches) => (matches as RegExpExecArray).slice(1, 4).join(","))
.map((rgb, i) => {
colors[i] = `rgb(${rgb})`;
});
@ -273,7 +273,7 @@ export function debounce(func: Function, delay: number): Function {
let timeout: number;
let callbackArgs: any[] = [];
return function(context: Object, ...args: any[]): void {
return function (context: Object, ...args: any[]): void {
callbackArgs = args;
if (timeout != null) {
@ -290,7 +290,7 @@ export function throttle(func: Function, delay: number): Function {
let timeout: number | null = null;
let callbackArgs: any[] = [];
return function(context: Object, ...args: any[]): void {
return function (context: Object, ...args: any[]): void {
callbackArgs = args;
if (!timeout) {
@ -311,7 +311,7 @@ export function objectForEach<V>(
obj: { [key: string]: V },
cb: (value: V, key: string) => void
): void {
Object.keys(obj).forEach(key => cb(obj[key], key));
Object.keys(obj).forEach((key) => cb(obj[key], key));
}
export function objectMap<V, N>(
@ -319,7 +319,7 @@ export function objectMap<V, N>(
cb: (value: V, key: string) => N
): { [key: string]: N } {
const modified: { [key: string]: N } = {};
Object.keys(obj).forEach(key => (modified[key] = cb(obj[key], key)));
Object.keys(obj).forEach((key) => (modified[key] = cb(obj[key], key)));
return modified;
}
@ -340,7 +340,7 @@ export const calculateBoundingBox = (windows: WindowInfo[]) => {
if (windows.length === 0) {
return null;
}
const windowSizes = windows.map(w => ({
const windowSizes = windows.map((w) => ({
left: w.x,
top: w.y,
bottom: w.y + w.height,

View file

@ -133,7 +133,7 @@ const storeHas = (
store: Store,
predicate: (state: AppState) => boolean
): Promise<void> =>
new Promise(resolve => {
new Promise((resolve) => {
if (predicate(store.getState())) {
resolve();
return;
@ -282,7 +282,7 @@ class Winamp {
});
this.store.dispatch(
Actions.updateWindowPositions(
Utils.objectMap(layout, w => w.position),
Utils.objectMap(layout, (w) => w.position),
false
)
);
@ -350,7 +350,7 @@ class Winamp {
}
onWillClose(cb: (cancel: () => void) => void): () => void {
return this._actionEmitter.on(CLOSE_REQUESTED, action => {
return this._actionEmitter.on(CLOSE_REQUESTED, (action) => {
cb(action.cancel);
});
}
@ -388,7 +388,7 @@ class Winamp {
async skinIsLoaded(): Promise<void> {
// Wait for the skin to load.
// TODO #leak
await storeHas(this.store, state => !state.display.loading);
await storeHas(this.store, (state) => !state.display.loading);
// We attempt to pre-resolve these promises before we declare the skin
// loaded. That's because `<EqGraph>` needs these in order to render fully.
// As long as these are resolved before we attempt to render, we can ensure

View file

@ -19,9 +19,9 @@ module.exports = {
schema: [],
fixable: "code",
},
create: function(context) {
create: function (context) {
return {
ClassDeclaration: function(node) {
ClassDeclaration: function (node) {
const className = node.id.name;
if (isJsMakiNode(node)) {
return;

View file

@ -52,9 +52,9 @@ module.exports = {
schema: [],
fixable: "code",
},
create: function(context) {
create: function (context) {
return {
MethodDefinition: function(node) {
MethodDefinition: function (node) {
const currentObject = getMakiObjectfromClassDeclarationNode(
node.parent.parent
);
@ -62,7 +62,7 @@ module.exports = {
return;
}
const methods = {};
currentObject.functions.forEach(func => {
currentObject.functions.forEach((func) => {
methods[func.name.toLowerCase()] = func;
});
@ -102,7 +102,7 @@ module.exports = {
context.report({
node: body,
message: `Missing return type for Maki method. Expected \`${expectedTypeData.stringRepresentation}\`.`,
fix: fixer => {
fix: (fixer) => {
return fixer.insertTextBefore(
body,
`: ${expectedTypeData.stringRepresentation}`
@ -147,7 +147,7 @@ module.exports = {
// console.warn(`Missing type data for ${type}.`);
return;
}
const fix = fixer => {
const fix = (fixer) => {
return fixer.replaceText(
actual,
`${actual.name}: ${expectedTypeData.stringRepresentation}`

View file

@ -12,9 +12,9 @@ module.exports = {
schema: [],
fixable: "code",
},
create: function(context) {
create: function (context) {
return {
ClassBody: function(node) {
ClassBody: function (node) {
const currentObject = getMakiObjectfromClassDeclarationNode(
node.parent
);
@ -24,11 +24,11 @@ module.exports = {
const implementedMethodNames = new Set(
node.body
.filter(prop => prop.type === "MethodDefinition")
.map(method => method.key.name)
.filter((prop) => prop.type === "MethodDefinition")
.map((method) => method.key.name)
);
currentObject.functions.forEach(func => {
currentObject.functions.forEach((func) => {
const methodName = func.name.toLowerCase();
if (implementedMethodNames.has(methodName)) {
return;
@ -47,7 +47,7 @@ module.exports = {
context.report({
node: node,
message: `Missing method ${methodName}`,
fix: fixer => {
fix: (fixer) => {
return fixer.insertTextAfter(lastChild, methodString);
},
});

View file

@ -21,7 +21,7 @@ export function setMakiTree(makiTree: MakiTree): ModernAction {
}
export function setXmlTree(xmlTree: XmlTree): Thunk {
return async dispatch => {
return async (dispatch) => {
dispatch({
type: "SET_XML_TREE",
xmlTree: await initializeStateTree(xmlTree),
@ -30,14 +30,14 @@ export function setXmlTree(xmlTree: XmlTree): Thunk {
}
export function gotSkinUrl(skinUrl: string, store: ModernStore): Thunk {
return async dispatch => {
return async (dispatch) => {
const resp = await fetch(skinUrl);
dispatch(gotSkinBlob(await resp.blob(), store));
};
}
export function gotSkinBlob(blob: Blob, store: ModernStore): Thunk {
return async dispatch => {
return async (dispatch) => {
dispatch(gotSkinZip(await JSZip.loadAsync(blob), store));
};
}
@ -53,7 +53,7 @@ async function unloadSkin(makiTree: MakiTree): Promise<void> {
}
export function gotSkinZip(zip: JSZip, store: ModernStore): Thunk {
return async dispatch => {
return async (dispatch) => {
// unload current skin if one has been loaded
if (store.getState().modernSkin.skinLoaded) {
await unloadSkin(store.getState().modernSkin.makiTree);

View file

@ -59,7 +59,7 @@ const skinUrls = [
];
function useJsUpdates(makiObject) {
const [, forceUpdate] = useReducer(x => x + 1, 0);
const [, forceUpdate] = useReducer((x) => x + 1, 0);
useEffect(() => makiObject.js_listen("js_update", forceUpdate));
}
@ -124,7 +124,7 @@ function GuiObjectEvents({ makiObject, children }) {
return (
<div
onMouseDown={e =>
onMouseDown={(e) =>
handleMouseButtonEventDispatch(
makiObject,
e,
@ -132,7 +132,7 @@ function GuiObjectEvents({ makiObject, children }) {
"onRightButtonDown"
)
}
onDoubleClick={e =>
onDoubleClick={(e) =>
handleMouseButtonEventDispatch(
makiObject,
e,
@ -140,15 +140,21 @@ function GuiObjectEvents({ makiObject, children }) {
"onRightButtonDblClk"
)
}
onMouseMove={e => handleMouseEventDispatch(makiObject, e, "onMouseMove")}
onMouseEnter={e => handleMouseEventDispatch(makiObject, e, "onEnterArea")}
onMouseLeave={e => handleMouseEventDispatch(makiObject, e, "onLeaveArea")}
onMouseMove={(e) =>
handleMouseEventDispatch(makiObject, e, "onMouseMove")
}
onMouseEnter={(e) =>
handleMouseEventDispatch(makiObject, e, "onEnterArea")
}
onMouseLeave={(e) =>
handleMouseEventDispatch(makiObject, e, "onLeaveArea")
}
onDragEnter={() => makiObject.js_trigger("onDragEnter")}
onDragLeave={() => makiObject.js_trigger("onDragLeave")}
onDragOver={e => handleMouseEventDispatch(makiObject, e, "onDragOver")}
onKeyUp={e => makiObject.js_trigger("onKeyUp", e.keyCode)}
onKeyDown={e => makiObject.js_trigger("onKeyDown", e.keyCode)}
onContextMenu={e => {
onDragOver={(e) => handleMouseEventDispatch(makiObject, e, "onDragOver")}
onKeyUp={(e) => makiObject.js_trigger("onKeyUp", e.keyCode)}
onKeyDown={(e) => makiObject.js_trigger("onKeyDown", e.keyCode)}
onContextMenu={(e) => {
e.preventDefault();
return false;
}}
@ -444,7 +450,7 @@ function Button({ makiObject }) {
setDown(false);
});
}}
onClick={e => {
onClick={(e) => {
if (e.button === 2) {
makiObject.js_trigger("onRightClick");
} else {
@ -473,7 +479,7 @@ function Button({ makiObject }) {
function Popupmenu({ makiObject }) {
const { id, x, y } = makiObject.attributes;
const children = makiObject.js_getCommands().map(item => {
const children = makiObject.js_getCommands().map((item) => {
if (item.id === "seperator") {
return <li />;
}
@ -680,7 +686,7 @@ function Modern() {
<div style={{ width: "100vw", height: "100vh", display: "flex" }}>
<DropTarget
style={{ width: "100%", height: "100%" }}
handleDrop={e => {
handleDrop={(e) => {
dispatch(Actions.gotSkinBlob(e.dataTransfer.files[0], store));
}}
>
@ -689,7 +695,7 @@ function Modern() {
<select
style={{ position: "absolute", bottom: 0 }}
value={skinUrl}
onChange={e => {
onChange={(e) => {
const newSkinUrl = e.target.value;
setSkinUrl(newSkinUrl);
// TODO: This should really go in a middleware somewhere.
@ -697,7 +703,7 @@ function Modern() {
dispatch(Actions.gotSkinUrl(newSkinUrl, store));
}}
>
{skinUrls.map(url => (
{skinUrls.map((url) => (
<option value={url} key={url}>
{url}
</option>

View file

@ -17,9 +17,9 @@ let METHOD_COUNT = 0;
let IMPLEMENTED_METHOD_COUNT = 0;
const normalizedMethods = [];
Object.keys(objects).forEach(key => {
Object.keys(objects).forEach((key) => {
const makiObject = objects[key];
makiObject.functions.forEach(method => {
makiObject.functions.forEach((method) => {
METHOD_COUNT++;
const normalizedName = `${makiObject.name}.${method.name.toLowerCase()}`;
const implemented = !unimplemented.has(normalizedName);
@ -40,7 +40,7 @@ Object.keys(objects).forEach(key => {
});
const foundMethods = normalizedMethods.filter(
method => method.foundInSkins > 0
(method) => method.foundInSkins > 0
);
function PercentBox({ number, total, label }) {
@ -85,13 +85,13 @@ function PercentBox({ number, total, label }) {
);
}
export default function() {
export default function () {
const [searchQuery, setSearchQuery] = React.useState("");
const [sortKey, setSortKey] = React.useState("totalCalls");
const [sortDirection, setSortDirection] = React.useState("ASC");
function setOrToggleSort(key) {
if (sortKey === key) {
setSortDirection(dir => (dir === "ASC" ? "DESC" : "ASC"));
setSortDirection((dir) => (dir === "ASC" ? "DESC" : "ASC"));
} else {
setSortKey(key);
}
@ -105,7 +105,7 @@ export default function() {
if (searchQuery) {
const normalizedQuery = searchQuery.toLowerCase();
filterFunction = method => {
filterFunction = (method) => {
return method.normalizedName.toLowerCase().includes(normalizedQuery);
};
}
@ -118,14 +118,14 @@ export default function() {
label="All Methods"
/>
<PercentBox
number={foundMethods.filter(method => method.implemented).length}
number={foundMethods.filter((method) => method.implemented).length}
total={foundMethods.length}
label="Used Methods"
/>
<input
placeholder={"Search..."}
value={searchQuery}
onChange={e => setSearchQuery(e.target.value)}
onChange={(e) => setSearchQuery(e.target.value)}
/>
<table>
<thead>

View file

@ -15,23 +15,23 @@ export default class Emitter {
this._hooks[eventName].push(cb);
return () => {
this._hooks[eventName] = this._hooks[eventName].filter(
hookCb => hookCb !== cb
(hookCb) => hookCb !== cb
);
};
}
trigger(eventName: string, ...args: any[]) {
this._globalHooks.map(cb => cb(eventName, ...args));
this._globalHooks.map((cb) => cb(eventName, ...args));
if (this._hooks[eventName] == null) {
return;
}
this._hooks[eventName].map(cb => cb(...args));
this._hooks[eventName].map((cb) => cb(...args));
}
listenToAll(cb: (eventName: string, ...args: any[]) => void) {
this._globalHooks.push(cb);
return () => {
this._globalHooks = this._globalHooks.filter(hookCb => hookCb !== cb);
this._globalHooks = this._globalHooks.filter((hookCb) => hookCb !== cb);
};
}

View file

@ -44,7 +44,7 @@ function buildZipFromDirectory(dir, zip, root) {
// Returns a promise that resolves when the state of a Redux store matches the
// given predicate
function isInState(store, predicate) {
return new Promise(resolve => {
return new Promise((resolve) => {
const unsubscribe = store.subscribe(() => {
if (predicate(store.getState())) {
resolve();
@ -77,7 +77,7 @@ async function runSkin(skinDirectory) {
const store = create();
store.dispatch(Actions.gotSkinZip(zip, store));
await isInState(store, state => state.modernSkin.skinLoaded);
await isInState(store, (state) => state.modernSkin.skinLoaded);
return mockMessageBox.mock.calls;
}
@ -92,10 +92,10 @@ Utils.getSizeFromUrl = jest.fn(() => {
// It will likely require converting data URIs generted by getUrlFromBlob into a buffer.
return { width: 0, height: 0 };
});
Utils.getUrlFromBlob = jest.fn(blob => {
return new Promise(resolve => {
Utils.getUrlFromBlob = jest.fn((blob) => {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = function(e) {
reader.onload = function (e) {
resolve(e.target.result);
};
// TODO: Preserve the mimetype of these files

View file

@ -2,22 +2,22 @@ import { getClass, getFormattedId, objects } from "../maki-interpreter/objects";
import runtime from "../runtime";
test("getFormattedId() is reversable", () => {
Object.keys(runtime).forEach(id => {
Object.keys(runtime).forEach((id) => {
const formattedId = getFormattedId(id);
const inverse = getFormattedId(formattedId);
expect(inverse).toBe(id);
});
Object.keys(objects)
.map(id => id.toLowerCase())
.forEach(id => {
.map((id) => id.toLowerCase())
.forEach((id) => {
const formattedId = getFormattedId(id);
const inverse = getFormattedId(formattedId);
expect(inverse).toBe(id);
});
});
const getMakiMethods = obj =>
Object.getOwnPropertyNames(obj).filter(name => {
const getMakiMethods = (obj) =>
Object.getOwnPropertyNames(obj).filter((name) => {
return (
typeof obj[name] === "function" &&
!name.startsWith("js_") &&
@ -41,7 +41,7 @@ for (const [key, Klass] of Object.entries(runtime)) {
expect(Parent.prototype.getclassname()).toBe(obj.parent);
});
describe("methods have the correct arity", () => {
obj.functions.forEach(func => {
obj.functions.forEach((func) => {
const methodName = func.name.toLowerCase();
// Once all methods are implemented this check can be removed.
// For now we have a separate test which checks that we haven't
@ -68,25 +68,25 @@ describe("Maki classes", () => {
const objectMethods = new Set();
for (const [key, Klass] of Object.entries(runtime)) {
const obj = getClass(key);
getMakiMethods(Klass.prototype).forEach(methodName => {
getMakiMethods(Klass.prototype).forEach((methodName) => {
runtimeMethods.add(`${obj.name}.${methodName}`);
const methodSource = Klass.prototype[methodName].toString();
if (methodSource.includes("unimplementedWarning")) {
unimplementedRuntimeMethods.add(`${obj.name}.${methodName}`);
}
});
obj.functions.forEach(func => {
obj.functions.forEach((func) => {
objectMethods.add(`${obj.name}.${func.name.toLowerCase()}`);
});
}
test("All classes are implemented", () => {
const getName = Klass => Klass.prototype.getclassname();
const getName = (Klass) => Klass.prototype.getclassname();
const actualNames = Object.keys(runtime).map(
id => `${getName(runtime[id])} (${id})`
(id) => `${getName(runtime[id])} (${id})`
);
const expectedNames = Object.keys(objects).map(
id => `${objects[id].name} (${getFormattedId(id)})`
(id) => `${objects[id].name} (${getFormattedId(id)})`
);
expect(new Set(actualNames)).toEqual(new Set(expectedNames));
});
@ -111,7 +111,7 @@ describe("Maki classes", () => {
});
test("There are no missing methods", () => {
const missing = [...objectMethods].filter(x => !runtimeMethods.has(x));
const missing = [...objectMethods].filter((x) => !runtimeMethods.has(x));
expect(missing).toEqual([]);
});

View file

@ -24,9 +24,9 @@ describe("can parse without crashing", () => {
"simpleFunctions.maki",
];
scripts.forEach(script => {
scripts.forEach((script) => {
describe(`script ${script}`, () => {
versions.forEach(version => {
versions.forEach((version) => {
test(`compiled with compiler version ${version}`, () => {
expect(() => {
parseFile(`../../resources/maki_compiler/${version}/${script}`);
@ -62,7 +62,7 @@ describe("standardframe.maki", () => {
});
test("can read classes", () => {
expect(maki.classes.map(klass => getClass(klass).name)).toEqual([
expect(maki.classes.map((klass) => getClass(klass).name)).toEqual([
"Object",
"System",
"Container",
@ -100,7 +100,7 @@ describe("standardframe.maki", () => {
});
test("can read methods", () => {
expect(maki.methods.map(func => func.name)).toEqual([
expect(maki.methods.map((func) => func.name)).toEqual([
"onScriptLoaded",
"getScriptGroup",
"getParam",
@ -114,13 +114,13 @@ describe("standardframe.maki", () => {
"newGroup",
"init",
]);
expect(maki.methods.every(func => func.typeOffset != null)).toBe(true);
expect(maki.methods.every((func) => func.typeOffset != null)).toBe(true);
});
test("can read variables", () => {
expect(maki.variables.length).toBe(56);
expect(
maki.variables.map(variable => {
maki.variables.map((variable) => {
const { typeName, type } = variable;
if (typeName === "OBJECT") {
return type;
@ -187,7 +187,7 @@ Array [
"STRING",
]
`);
maki.variables.forEach(variable => {
maki.variables.forEach((variable) => {
expect(variable.type).not.toBe(undefined);
});
});

Some files were not shown because too many files have changed in this diff Show more