Use template literals instead of string concatenation (#3066)

We have used it inconsistently till now. Template literals are more
modern and easier to maintain in my opinion.

Because that's a large amount of changes, here's a way to reproduce it:
I added the rule `"prefer-template": "error"` to the `.eslintrc.json`
and did an autofix. Since this caused a new problem in line 409 of
`newsfeed.js`, I reversed it in that line and also removed the rule from
the eslint config file.

The rule is described here:
https://eslint.org/docs/latest/rules/prefer-template

Note: I've played around with some other linter rules as well, and some
seem to point to some specific, non-cosmetic, issues. But before I dive
even deeper and then introduce even bigger and hardly understandable
changes at once, I thought I'd start with this simple cosmetic rule.
This commit is contained in:
Kristjan ESPERANTO
2023-03-19 14:32:23 +01:00
committed by GitHub
parent 8f8945d418
commit d276a7ddb9
45 changed files with 222 additions and 237 deletions

View File

@@ -18,7 +18,7 @@ const envsub = require("envsub");
// Get version number.
global.version = require(`${__dirname}/../package.json`).version;
Log.log("Starting MagicMirror: v" + global.version);
Log.log(`Starting MagicMirror: v${global.version}`);
// global absolute root path
global.root_path = path.resolve(`${__dirname}/../`);
@@ -64,7 +64,7 @@ function App() {
// For this check proposed to TestSuite
// https://forum.magicmirror.builders/topic/1456/test-suite-for-magicmirror/8
const configFilename = path.resolve(global.configuration_file || `${global.root_path}/config/config.js`);
let templateFile = configFilename + ".template";
let templateFile = `${configFilename}.template`;
// check if templateFile exists
try {
@@ -78,21 +78,21 @@ function App() {
// save current config.js
try {
if (fs.existsSync(configFilename)) {
fs.copyFileSync(configFilename, configFilename + "_" + Date.now());
fs.copyFileSync(configFilename, `${configFilename}_${Date.now()}`);
}
} catch (err) {
Log.warn("Could not copy " + configFilename + ": " + err.message);
Log.warn(`Could not copy ${configFilename}: ${err.message}`);
}
// check if config.env exists
const envFiles = [];
const configEnvFile = configFilename.substr(0, configFilename.lastIndexOf(".")) + ".env";
const configEnvFile = `${configFilename.substr(0, configFilename.lastIndexOf("."))}.env`;
try {
if (fs.existsSync(configEnvFile)) {
envFiles.push(configEnvFile);
}
} catch (err) {
Log.debug(configEnvFile + " does not exist. " + err.message);
Log.debug(`${configEnvFile} does not exist. ${err.message}`);
}
let options = {
@@ -110,7 +110,7 @@ function App() {
try {
await envsub({ templateFile, outputFile, options });
} catch (err) {
Log.error("Could not envsubst variables: " + err.message);
Log.error(`Could not envsubst variables: ${err.message}`);
}
}

View File

@@ -44,7 +44,7 @@ const Loader = (function () {
// Starting modules also hides any modules that have requested to be initially hidden
for (const thisModule of moduleObjects) {
if (thisModule.data.hiddenOnStartup) {
Log.info("Initially hiding " + thisModule.name);
Log.info(`Initially hiding ${thisModule.name}`);
thisModule.hide();
}
}
@@ -73,10 +73,10 @@ const Loader = (function () {
const elements = module.split("/");
const moduleName = elements[elements.length - 1];
let moduleFolder = config.paths.modules + "/" + module;
let moduleFolder = `${config.paths.modules}/${module}`;
if (defaultModules.indexOf(moduleName) !== -1) {
moduleFolder = config.paths.modules + "/default/" + module;
moduleFolder = `${config.paths.modules}/default/${module}`;
}
if (moduleData.disabled === true) {
@@ -85,16 +85,16 @@ const Loader = (function () {
moduleFiles.push({
index: index,
identifier: "module_" + index + "_" + module,
identifier: `module_${index}_${module}`,
name: moduleName,
path: moduleFolder + "/",
file: moduleName + ".js",
path: `${moduleFolder}/`,
file: `${moduleName}.js`,
position: moduleData.position,
hiddenOnStartup: moduleData.hiddenOnStartup,
header: moduleData.header,
configDeepMerge: typeof moduleData.configDeepMerge === "boolean" ? moduleData.configDeepMerge : false,
config: moduleData.config,
classes: typeof moduleData.classes !== "undefined" ? moduleData.classes + " " + module : module
classes: typeof moduleData.classes !== "undefined" ? `${moduleData.classes} ${module}` : module
});
});
@@ -136,17 +136,17 @@ const Loader = (function () {
* @param {Module} mObj Modules instance.
*/
const bootstrapModule = async function (module, mObj) {
Log.info("Bootstrapping module: " + module.name);
Log.info(`Bootstrapping module: ${module.name}`);
mObj.setData(module);
await mObj.loadScripts();
Log.log("Scripts loaded for: " + module.name);
Log.log(`Scripts loaded for: ${module.name}`);
await mObj.loadStyles();
Log.log("Styles loaded for: " + module.name);
Log.log(`Styles loaded for: ${module.name}`);
await mObj.loadTranslations();
Log.log("Translations loaded for: " + module.name);
Log.log(`Translations loaded for: ${module.name}`);
moduleObjects.push(mObj);
};
@@ -164,7 +164,7 @@ const Loader = (function () {
switch (extension.toLowerCase()) {
case "js":
return new Promise((resolve) => {
Log.log("Load script: " + fileName);
Log.log(`Load script: ${fileName}`);
script = document.createElement("script");
script.type = "text/javascript";
script.src = fileName;
@@ -179,7 +179,7 @@ const Loader = (function () {
});
case "css":
return new Promise((resolve) => {
Log.log("Load stylesheet: " + fileName);
Log.log(`Load stylesheet: ${fileName}`);
stylesheet = document.createElement("link");
stylesheet.rel = "stylesheet";
@@ -236,7 +236,7 @@ const Loader = (function () {
*/
loadFileForModule: async function (fileName, module) {
if (loadedFiles.indexOf(fileName.toLowerCase()) !== -1) {
Log.log("File already loaded: " + fileName);
Log.log(`File already loaded: ${fileName}`);
return;
}
@@ -251,7 +251,7 @@ const Loader = (function () {
// This file is available in the vendor folder.
// Load it from this vendor folder.
loadedFiles.push(fileName.toLowerCase());
return loadFile(config.paths.vendor + "/" + vendor[fileName]);
return loadFile(`${config.paths.vendor}/${vendor[fileName]}`);
}
// File not loaded yet.

View File

@@ -29,7 +29,7 @@ const MM = (function () {
dom.className = module.name;
if (typeof module.data.classes === "string") {
dom.className = "module " + dom.className + " " + module.data.classes;
dom.className = `module ${dom.className} ${module.data.classes}`;
}
dom.opacity = 0;
@@ -243,7 +243,7 @@ const MM = (function () {
const moduleWrapper = document.getElementById(module.identifier);
if (moduleWrapper !== null) {
moduleWrapper.style.transition = "opacity " + speed / 1000 + "s";
moduleWrapper.style.transition = `opacity ${speed / 1000}s`;
moduleWrapper.style.opacity = 0;
moduleWrapper.classList.add("hidden");
@@ -291,7 +291,7 @@ const MM = (function () {
// Check if there are no more lockstrings set, or the force option is set.
// Otherwise cancel show action.
if (module.lockStrings.length !== 0 && options.force !== true) {
Log.log("Will not show " + module.name + ". LockStrings active: " + module.lockStrings.join(","));
Log.log(`Will not show ${module.name}. LockStrings active: ${module.lockStrings.join(",")}`);
if (typeof options.onError === "function") {
options.onError(new Error("LOCK_STRING_ACTIVE"));
}
@@ -302,13 +302,13 @@ const MM = (function () {
// If forced show, clean current lockstrings.
if (module.lockStrings.length !== 0 && options.force === true) {
Log.log("Force show of module: " + module.name);
Log.log(`Force show of module: ${module.name}`);
module.lockStrings = [];
}
const moduleWrapper = document.getElementById(module.identifier);
if (moduleWrapper !== null) {
moduleWrapper.style.transition = "opacity " + speed / 1000 + "s";
moduleWrapper.style.transition = `opacity ${speed / 1000}s`;
// Restore the position. See hideModule() for more info.
moduleWrapper.style.position = "static";
moduleWrapper.classList.remove("hidden");

View File

@@ -41,7 +41,7 @@ const Module = Class.extend({
* Called when the module is started.
*/
start: async function () {
Log.info("Starting module: " + this.name);
Log.info(`Starting module: ${this.name}`);
},
/**
@@ -127,7 +127,7 @@ const Module = Class.extend({
* @returns {string} The template string of filename.
*/
getTemplate: function () {
return '<div class="normal">' + this.name + '</div><div class="small dimmed">' + this.identifier + "</div>";
return `<div class="normal">${this.name}</div><div class="small dimmed">${this.identifier}</div>`;
},
/**
@@ -185,21 +185,21 @@ const Module = Class.extend({
* @param {*} payload The payload of the notification.
*/
socketNotificationReceived: function (notification, payload) {
Log.log(this.name + " received a socket notification: " + notification + " - Payload: " + payload);
Log.log(`${this.name} received a socket notification: ${notification} - Payload: ${payload}`);
},
/**
* Called when the module is hidden.
*/
suspend: function () {
Log.log(this.name + " is suspended.");
Log.log(`${this.name} is suspended.`);
},
/**
* Called when the module is shown.
*/
resume: function () {
Log.log(this.name + " is resumed.");
Log.log(`${this.name} is resumed.`);
},
/*********************************************
@@ -255,7 +255,7 @@ const Module = Class.extend({
* @returns {string} the file path
*/
file: function (file) {
return (this.data.path + "/" + file).replace("//", "/");
return `${this.data.path}/${file}`.replace("//", "/");
},
/**
@@ -491,15 +491,15 @@ Module.create = function (name) {
Module.register = function (name, moduleDefinition) {
if (moduleDefinition.requiresVersion) {
Log.log("Check MagicMirror² version for module '" + name + "' - Minimum version: " + moduleDefinition.requiresVersion + " - Current version: " + window.mmVersion);
Log.log(`Check MagicMirror² version for module '${name}' - Minimum version: ${moduleDefinition.requiresVersion} - Current version: ${window.mmVersion}`);
if (cmpVersions(window.mmVersion, moduleDefinition.requiresVersion) >= 0) {
Log.log("Version is ok!");
} else {
Log.warn("Version is incorrect. Skip module: '" + name + "'");
Log.warn(`Version is incorrect. Skip module: '${name}'`);
return;
}
}
Log.log("Module registered: " + name);
Log.log(`Module registered: ${name}`);
Module.definitions[name] = moduleDefinition;
};

View File

@@ -30,7 +30,7 @@ async function cors(req, res) {
const match = new RegExp(urlRegEx, "g").exec(req.url);
if (!match) {
url = "invalid url: " + req.url;
url = `invalid url: ${req.url}`;
Log.error(url);
res.send(url);
} else {
@@ -39,7 +39,7 @@ async function cors(req, res) {
const headersToSend = getHeadersToSend(req.url);
const expectedRecievedHeaders = geExpectedRecievedHeaders(req.url);
Log.log("cors url: " + url);
Log.log(`cors url: ${url}`);
const response = await fetch(url, { headers: headersToSend });
for (const header of expectedRecievedHeaders) {
@@ -62,7 +62,7 @@ async function cors(req, res) {
* @returns {object} An object specifying name and value of the headers.
*/
function getHeadersToSend(url) {
const headersToSend = { "User-Agent": "Mozilla/5.0 MagicMirror/" + global.version };
const headersToSend = { "User-Agent": `Mozilla/5.0 MagicMirror/${global.version}` };
const headersToSendMatch = new RegExp("sendheaders=(.+?)(&|$)", "g").exec(url);
if (headersToSendMatch) {
const headers = headersToSendMatch[1].split(",");

View File

@@ -18,8 +18,8 @@ const MMSocket = function (moduleName) {
if (typeof config !== "undefined" && typeof config.basePath !== "undefined") {
base = config.basePath;
}
this.socket = io("/" + this.moduleName, {
path: base + "socket.io"
this.socket = io(`/${this.moduleName}`, {
path: `${base}socket.io`
});
let notificationCallback = function () {};

View File

@@ -26,7 +26,7 @@ const Translator = (function () {
fileinfo = JSON.parse(xhr.responseText);
} catch (exception) {
// nothing here, but don't die
Log.error(" loading json file =" + file + " failed");
Log.error(` loading json file =${file} failed`);
}
resolve(fileinfo);
}
@@ -70,7 +70,7 @@ const Translator = (function () {
template = variables.fallback;
}
return template.replace(new RegExp("{([^}]+)}", "g"), function (_unused, varName) {
return varName in variables ? variables[varName] : "{" + varName + "}";
return varName in variables ? variables[varName] : `{${varName}}`;
});
}
@@ -123,7 +123,7 @@ const Translator = (function () {
*/
loadCoreTranslations: async function (lang) {
if (lang in translations) {
Log.log("Loading core translation file: " + translations[lang]);
Log.log(`Loading core translation file: ${translations[lang]}`);
this.coreTranslations = await loadJSON(translations[lang]);
} else {
Log.log("Configured language not found in core translations.");
@@ -139,7 +139,7 @@ const Translator = (function () {
loadCoreTranslationsFallback: async function () {
let first = Object.keys(translations)[0];
if (first) {
Log.log("Loading core translation fallback file: " + translations[first]);
Log.log(`Loading core translation fallback file: ${translations[first]}`);
this.coreTranslationsFallback = await loadJSON(translations[first]);
}
}