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

@@ -80,7 +80,7 @@
NotificationFx.prototype._init = function () {
// create HTML structure
this.ntf = document.createElement("div");
this.ntf.className = this.options.al_no + " ns-" + this.options.layout + " ns-effect-" + this.options.effect + " ns-type-" + this.options.type;
this.ntf.className = `${this.options.al_no} ns-${this.options.layout} ns-effect-${this.options.effect} ns-type-${this.options.type}`;
let strinner = '<div class="ns-box-inner">';
strinner += this.options.message;
strinner += "</div>";

View File

@@ -94,7 +94,7 @@ Module.register("calendar", {
start: function () {
const ONE_MINUTE = 60 * 1000;
Log.info("Starting module: " + this.name);
Log.info(`Starting module: ${this.name}`);
if (this.config.colored) {
Log.warn("Your are using the deprecated config values 'colored'. Please switch to 'coloredSymbol' & 'coloredText'!");
@@ -203,13 +203,13 @@ Module.register("calendar", {
if (this.error) {
wrapper.innerHTML = this.error;
wrapper.className = this.config.tableClass + " dimmed";
wrapper.className = `${this.config.tableClass} dimmed`;
return wrapper;
}
if (events.length === 0) {
wrapper.innerHTML = this.loaded ? this.translate("EMPTY") : this.translate("LOADING");
wrapper.className = this.config.tableClass + " dimmed";
wrapper.className = `${this.config.tableClass} dimmed`;
return wrapper;
}
@@ -259,7 +259,7 @@ Module.register("calendar", {
const eventWrapper = document.createElement("tr");
if (this.config.coloredText) {
eventWrapper.style.cssText = "color:" + this.colorForUrl(event.url, false);
eventWrapper.style.cssText = `color:${this.colorForUrl(event.url, false)}`;
}
if (this.config.coloredBackground) {
@@ -281,11 +281,11 @@ Module.register("calendar", {
if (this.config.displaySymbol) {
if (this.config.coloredSymbol) {
symbolWrapper.style.cssText = "color:" + this.colorForUrl(event.url, false);
symbolWrapper.style.cssText = `color:${this.colorForUrl(event.url, false)}`;
}
const symbolClass = this.symbolClassForUrl(event.url);
symbolWrapper.className = "symbol align-right " + symbolClass;
symbolWrapper.className = `symbol align-right ${symbolClass}`;
const symbols = this.symbolsForEvent(event);
symbols.forEach((s, index) => {
@@ -313,7 +313,7 @@ Module.register("calendar", {
const thisYear = new Date(parseInt(event.startDate)).getFullYear(),
yearDiff = thisYear - event.firstYear;
repeatingCountTitle = ", " + yearDiff + ". " + repeatingCountTitle;
repeatingCountTitle = `, ${yearDiff}. ${repeatingCountTitle}`;
}
}
@@ -325,11 +325,11 @@ Module.register("calendar", {
if (needle.test(event.title)) {
// Respect parameter ColoredSymbolOnly also for custom events
if (this.config.coloredText) {
eventWrapper.style.cssText = "color:" + this.config.customEvents[ev].color;
titleWrapper.style.cssText = "color:" + this.config.customEvents[ev].color;
eventWrapper.style.cssText = `color:${this.config.customEvents[ev].color}`;
titleWrapper.style.cssText = `color:${this.config.customEvents[ev].color}`;
}
if (this.config.displaySymbol && this.config.coloredSymbol) {
symbolWrapper.style.cssText = "color:" + this.config.customEvents[ev].color;
symbolWrapper.style.cssText = `color:${this.config.customEvents[ev].color}`;
}
break;
}
@@ -342,9 +342,9 @@ Module.register("calendar", {
const titleClass = this.titleClassForUrl(event.url);
if (!this.config.coloredText) {
titleWrapper.className = "title bright " + titleClass;
titleWrapper.className = `title bright ${titleClass}`;
} else {
titleWrapper.className = "title " + titleClass;
titleWrapper.className = `title ${titleClass}`;
}
if (this.config.timeFormat === "dateheaders") {
@@ -355,14 +355,14 @@ Module.register("calendar", {
titleWrapper.classList.add("align-left");
} else {
const timeWrapper = document.createElement("td");
timeWrapper.className = "time light " + (this.config.flipDateHeaderTitle ? "align-right " : "align-left ") + this.timeClassForUrl(event.url);
timeWrapper.className = `time light ${this.config.flipDateHeaderTitle ? "align-right " : "align-left "}${this.timeClassForUrl(event.url)}`;
timeWrapper.style.paddingLeft = "2px";
timeWrapper.style.textAlign = this.config.flipDateHeaderTitle ? "right" : "left";
timeWrapper.innerHTML = moment(event.startDate, "x").format("LT");
// Add endDate to dataheaders if showEnd is enabled
if (this.config.showEnd) {
timeWrapper.innerHTML += " - " + this.capFirst(moment(event.endDate, "x").format("LT"));
timeWrapper.innerHTML += ` - ${this.capFirst(moment(event.endDate, "x").format("LT"))}`;
}
eventWrapper.appendChild(timeWrapper);
@@ -393,7 +393,7 @@ Module.register("calendar", {
// Ongoing and getRelative is set
timeWrapper.innerHTML = this.capFirst(
this.translate("RUNNING", {
fallback: this.translate("RUNNING") + " {timeUntilEnd}",
fallback: `${this.translate("RUNNING")} {timeUntilEnd}`,
timeUntilEnd: moment(event.endDate, "x").fromNow(true)
})
);
@@ -424,8 +424,8 @@ Module.register("calendar", {
} else {
timeWrapper.innerHTML = this.capFirst(
moment(event.startDate, "x").calendar(null, {
sameDay: this.config.showTimeToday ? "LT" : "[" + this.translate("TODAY") + "]",
nextDay: "[" + this.translate("TOMORROW") + "]",
sameDay: this.config.showTimeToday ? "LT" : `[${this.translate("TODAY")}]`,
nextDay: `[${this.translate("TOMORROW")}]`,
nextWeek: "dddd",
sameElse: event.fullDayEvent ? this.config.fullDayEventDateFormat : this.config.dateFormat
})
@@ -456,13 +456,13 @@ Module.register("calendar", {
// Ongoing event
timeWrapper.innerHTML = this.capFirst(
this.translate("RUNNING", {
fallback: this.translate("RUNNING") + " {timeUntilEnd}",
fallback: `${this.translate("RUNNING")} {timeUntilEnd}`,
timeUntilEnd: moment(event.endDate, "x").fromNow(true)
})
);
}
}
timeWrapper.className = "time light " + this.timeClassForUrl(event.url);
timeWrapper.className = `time light ${this.timeClassForUrl(event.url)}`;
eventWrapper.appendChild(timeWrapper);
}
@@ -489,7 +489,7 @@ Module.register("calendar", {
}
if (this.config.coloredText) {
locationRow.style.cssText = "color:" + this.colorForUrl(event.url, false);
locationRow.style.cssText = `color:${this.colorForUrl(event.url, false)}`;
}
if (this.config.coloredBackground) {
@@ -619,7 +619,7 @@ Module.register("calendar", {
thisEvent.today = thisEvent.startDate >= today && thisEvent.startDate < today + ONE_DAY;
thisEvent.tomorrow = !thisEvent.today && thisEvent.startDate >= today + ONE_DAY && thisEvent.startDate < today + 2 * ONE_DAY;
thisEvent.endDate = midnight;
thisEvent.title += " (" + count + "/" + maxCount + ")";
thisEvent.title += ` (${count}/${maxCount})`;
splitEvents.push(thisEvent);
event.startDate = midnight;
@@ -627,7 +627,7 @@ Module.register("calendar", {
midnight = moment(midnight, "x").add(1, "day").format("x"); // next day
}
// Last day
event.title += " (" + count + "/" + maxCount + ")";
event.title += ` (${count}/${maxCount})`;
event.today += event.startDate >= today && event.startDate < today + ONE_DAY;
event.tomorrow = !event.today && event.startDate >= today + ONE_DAY && event.startDate < today + 2 * ONE_DAY;
splitEvents.push(event);
@@ -894,7 +894,7 @@ Module.register("calendar", {
const word = words[i];
if (currentLine.length + word.length < (typeof maxLength === "number" ? maxLength : 25) - 1) {
// max - 1 to account for a space
currentLine += word + " ";
currentLine += `${word} `;
} else {
line++;
if (line > maxTitleLines - 1) {
@@ -905,9 +905,9 @@ Module.register("calendar", {
}
if (currentLine.length > 0) {
temp += currentLine + "<br>" + word + " ";
temp += `${currentLine}<br>${word} `;
} else {
temp += word + "<br>";
temp += `${word}<br>`;
}
currentLine = "";
}
@@ -916,7 +916,7 @@ Module.register("calendar", {
return (temp + currentLine).trim();
} else {
if (maxLength && typeof maxLength === "number" && string.length > maxLength) {
return string.trim().slice(0, maxLength) + "…";
return `${string.trim().slice(0, maxLength)}`;
} else {
return string.trim();
}

View File

@@ -41,7 +41,7 @@ const CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEn
let fetcher = null;
let httpsAgent = null;
let headers = {
"User-Agent": "Mozilla/5.0 (Node.js " + nodeVersion + ") MagicMirror/" + global.version
"User-Agent": `Mozilla/5.0 (Node.js ${nodeVersion}) MagicMirror/${global.version}`
};
if (selfSignedCert) {
@@ -51,11 +51,11 @@ const CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEn
}
if (auth) {
if (auth.method === "bearer") {
headers.Authorization = "Bearer " + auth.pass;
headers.Authorization = `Bearer ${auth.pass}`;
} else if (auth.method === "digest") {
fetcher = new digest(auth.user, auth.pass).fetch(url, { headers: headers, agent: httpsAgent });
} else {
headers.Authorization = "Basic " + Buffer.from(auth.user + ":" + auth.pass).toString("base64");
headers.Authorization = `Basic ${Buffer.from(`${auth.user}:${auth.pass}`).toString("base64")}`;
}
}
if (fetcher === null) {
@@ -70,7 +70,7 @@ const CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEn
try {
data = ical.parseICS(responseData);
Log.debug("parsed data=" + JSON.stringify(data));
Log.debug(`parsed data=${JSON.stringify(data)}`);
events = CalendarUtils.filterEvents(data, {
excludedEvents,
includePastEvents,
@@ -114,7 +114,7 @@ const CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEn
* Broadcast the existing events.
*/
this.broadcastEvents = function () {
Log.info("Calendar-Fetcher: Broadcasting " + events.length + " events.");
Log.info(`Calendar-Fetcher: Broadcasting ${events.length} events.`);
eventsReceivedCallback(this);
};

View File

@@ -29,7 +29,7 @@ const CalendarUtils = {
Log.debug(" if no tz, guess based on now");
event.start.tz = moment.tz.guess();
}
Log.debug("initial tz=" + event.start.tz);
Log.debug(`initial tz=${event.start.tz}`);
// if there is a start date specified
if (event.start.tz) {
@@ -37,7 +37,7 @@ const CalendarUtils = {
if (event.start.tz.includes(" ")) {
// use the lookup table to get theIANA name as moment and date don't know MS timezones
let tz = CalendarUtils.getIanaTZFromMS(event.start.tz);
Log.debug("corrected TZ=" + tz);
Log.debug(`corrected TZ=${tz}`);
// watch out for unregistered windows timezone names
// if we had a successful lookup
if (tz) {
@@ -46,7 +46,7 @@ const CalendarUtils = {
// Log.debug("corrected timezone="+event.start.tz)
}
}
Log.debug("corrected tz=" + event.start.tz);
Log.debug(`corrected tz=${event.start.tz}`);
let current_offset = 0; // offset from TZ string or calculated
let mm = 0; // date with tz or offset
let start_offset = 0; // utc offset of created with tz
@@ -57,18 +57,18 @@ const CalendarUtils = {
let start_offset = parseInt(start_offsetString[0]);
start_offset *= event.start.tz[1] === "-" ? -1 : 1;
adjustHours = start_offset;
Log.debug("defined offset=" + start_offset + " hours");
Log.debug(`defined offset=${start_offset} hours`);
current_offset = start_offset;
event.start.tz = "";
Log.debug("ical offset=" + current_offset + " date=" + date);
Log.debug(`ical offset=${current_offset} date=${date}`);
mm = moment(date);
let x = parseInt(moment(new Date()).utcOffset());
Log.debug("net mins=" + (current_offset * 60 - x));
Log.debug(`net mins=${current_offset * 60 - x}`);
mm = mm.add(x - current_offset * 60, "minutes");
adjustHours = (current_offset * 60 - x) / 60;
event.start = mm.toDate();
Log.debug("adjusted date=" + event.start);
Log.debug(`adjusted date=${event.start}`);
} else {
// get the start time in that timezone
let es = moment(event.start);
@@ -76,18 +76,18 @@ const CalendarUtils = {
if (es.format("YYYY") < 2007) {
es.set("year", 2013); // if so, use a closer date
}
Log.debug("start date/time=" + es.toDate());
Log.debug(`start date/time=${es.toDate()}`);
start_offset = moment.tz(es, event.start.tz).utcOffset();
Log.debug("start offset=" + start_offset);
Log.debug(`start offset=${start_offset}`);
Log.debug("start date/time w tz =" + moment.tz(moment(event.start), event.start.tz).toDate());
Log.debug(`start date/time w tz =${moment.tz(moment(event.start), event.start.tz).toDate()}`);
// get the specified date in that timezone
mm = moment.tz(moment(date), event.start.tz);
Log.debug("event date=" + mm.toDate());
Log.debug(`event date=${mm.toDate()}`);
current_offset = mm.utcOffset();
}
Log.debug("event offset=" + current_offset + " hour=" + mm.format("H") + " event date=" + mm.toDate());
Log.debug(`event offset=${current_offset} hour=${mm.format("H")} event date=${mm.toDate()}`);
// if the offset is greater than 0, east of london
if (current_offset !== start_offset) {
@@ -113,7 +113,7 @@ const CalendarUtils = {
}
}
}
Log.debug("adjustHours=" + adjustHours);
Log.debug(`adjustHours=${adjustHours}`);
return adjustHours;
},
@@ -138,7 +138,7 @@ const CalendarUtils = {
return CalendarUtils.isFullDayEvent(event) ? moment(event[time], "YYYYMMDD") : moment(new Date(event[time]));
};
Log.debug("There are " + Object.entries(data).length + " calendar entries.");
Log.debug(`There are ${Object.entries(data).length} calendar entries.`);
Object.entries(data).forEach(([key, event]) => {
Log.debug("Processing entry...");
const now = new Date();
@@ -160,7 +160,7 @@ const CalendarUtils = {
}
if (event.type === "VEVENT") {
Log.debug("Event:\n" + JSON.stringify(event));
Log.debug(`Event:\n${JSON.stringify(event)}`);
let startDate = eventDate(event, "start");
let endDate;
@@ -177,12 +177,12 @@ const CalendarUtils = {
}
}
Log.debug("start: " + startDate.toDate());
Log.debug("end:: " + endDate.toDate());
Log.debug(`start: ${startDate.toDate()}`);
Log.debug(`end:: ${endDate.toDate()}`);
// Calculate the duration of the event for use with recurring events.
let duration = parseInt(endDate.format("x")) - parseInt(startDate.format("x"));
Log.debug("duration: " + duration);
Log.debug(`duration: ${duration}`);
// FIXME: Since the parsed json object from node-ical comes with time information
// this check could be removed (?)
@@ -191,7 +191,7 @@ const CalendarUtils = {
}
const title = CalendarUtils.getTitleFromEvent(event);
Log.debug("title: " + title);
Log.debug(`title: ${title}`);
let excluded = false,
dateFilter = null;
@@ -271,8 +271,8 @@ const CalendarUtils = {
pastLocal = pastMoment.toDate();
futureLocal = futureMoment.toDate();
Log.debug("pastLocal: " + pastLocal);
Log.debug("futureLocal: " + futureLocal);
Log.debug(`pastLocal: ${pastLocal}`);
Log.debug(`futureLocal: ${futureLocal}`);
} else {
// if we want past events
if (config.includePastEvents) {
@@ -284,9 +284,9 @@ const CalendarUtils = {
}
futureLocal = futureMoment.toDate(); // future
}
Log.debug("Search for recurring events between: " + pastLocal + " and " + futureLocal);
Log.debug(`Search for recurring events between: ${pastLocal} and ${futureLocal}`);
const dates = rule.between(pastLocal, futureLocal, true, limitFunction);
Log.debug("Title: " + event.summary + ", with dates: " + JSON.stringify(dates));
Log.debug(`Title: ${event.summary}, with dates: ${JSON.stringify(dates)}`);
// The "dates" array contains the set of dates within our desired date range range that are valid
// for the recurrence rule. *However*, it's possible for us to have a specific recurrence that
// had its date changed from outside the range to inside the range. For the time being,
@@ -294,7 +294,7 @@ const CalendarUtils = {
// because the logic below will filter out any recurrences that don't actually belong within
// our display range.
// Would be great if there was a better way to handle this.
Log.debug("event.recurrences: " + event.recurrences);
Log.debug(`event.recurrences: ${event.recurrences}`);
if (event.recurrences !== undefined) {
for (let r in event.recurrences) {
// Only add dates that weren't already in the range we added from the rrule so that
@@ -323,10 +323,10 @@ const CalendarUtils = {
let dateoffset = date.getTimezoneOffset();
// Reduce the time by the following offset.
Log.debug(" recurring date is " + date + " offset is " + dateoffset);
Log.debug(` recurring date is ${date} offset is ${dateoffset}`);
let dh = moment(date).format("HH");
Log.debug(" recurring date is " + date + " offset is " + dateoffset / 60 + " Hour is " + dh);
Log.debug(` recurring date is ${date} offset is ${dateoffset / 60} Hour is ${dh}`);
if (CalendarUtils.isFullDayEvent(event)) {
Log.debug("Fullday");
@@ -342,7 +342,7 @@ const CalendarUtils = {
// the duration was calculated way back at the top before we could correct the start time..
// fix it for this event entry
//duration = 24 * 60 * 60 * 1000;
Log.debug("new recurring date1 fulldate is " + date);
Log.debug(`new recurring date1 fulldate is ${date}`);
}
} else {
// if the timezones are the same, correct date if needed
@@ -357,7 +357,7 @@ const CalendarUtils = {
// the duration was calculated way back at the top before we could correct the start time..
// fix it for this event entry
//duration = 24 * 60 * 60 * 1000;
Log.debug("new recurring date2 fulldate is " + date);
Log.debug(`new recurring date2 fulldate is ${date}`);
}
//}
}
@@ -376,7 +376,7 @@ const CalendarUtils = {
// the duration was calculated way back at the top before we could correct the start time..
// fix it for this event entry
//duration = 24 * 60 * 60 * 1000;
Log.debug("new recurring date1 is " + date);
Log.debug(`new recurring date1 is ${date}`);
}
} else {
// if the timezones are the same, correct date if needed
@@ -391,13 +391,13 @@ const CalendarUtils = {
// the duration was calculated way back at the top before we could correct the start time..
// fix it for this event entry
//duration = 24 * 60 * 60 * 1000;
Log.debug("new recurring date2 is " + date);
Log.debug(`new recurring date2 is ${date}`);
}
//}
}
}
startDate = moment(date);
Log.debug("Corrected startDate: " + startDate.toDate());
Log.debug(`Corrected startDate: ${startDate.toDate()}`);
let adjustDays = CalendarUtils.calculateTimezoneAdjustment(event, date);
@@ -413,7 +413,7 @@ const CalendarUtils = {
// This date is an exception date, which means we should skip it in the recurrence pattern.
showRecurrence = false;
}
Log.debug("duration: " + duration);
Log.debug(`duration: ${duration}`);
endDate = moment(parseInt(startDate.format("x")) + duration, "x");
if (startDate.format("x") === endDate.format("x")) {
@@ -433,7 +433,7 @@ const CalendarUtils = {
}
if (showRecurrence === true) {
Log.debug("saving event: " + description);
Log.debug(`saving event: ${description}`);
addedEvents++;
newEvents.push({
title: recurrenceTitle,
@@ -573,7 +573,7 @@ const CalendarUtils = {
if (filter) {
const until = filter.split(" "),
value = parseInt(until[0]),
increment = until[1].slice(-1) === "s" ? until[1] : until[1] + "s", // Massage the data for moment js
increment = until[1].slice(-1) === "s" ? until[1] : `${until[1]}s`, // Massage the data for moment js
filterUntil = moment(endDate.format()).subtract(value, increment);
return now < filterUntil.format("x");

View File

@@ -11,7 +11,7 @@ const Log = require("logger");
module.exports = NodeHelper.create({
// Override start method.
start: function () {
Log.log("Starting node helper for: " + this.name);
Log.log(`Starting node helper for: ${this.name}`);
this.fetchers = [];
},
@@ -55,7 +55,7 @@ module.exports = NodeHelper.create({
let fetcher;
if (typeof this.fetchers[identifier + url] === "undefined") {
Log.log("Create new calendarfetcher for url: " + url + " - Interval: " + fetchInterval);
Log.log(`Create new calendarfetcher for url: ${url} - Interval: ${fetchInterval}`);
fetcher = new CalendarFetcher(url, fetchInterval, excludedEvents, maximumEntries, maximumNumberOfDays, auth, broadcastPastEvents, selfSignedCert);
fetcher.onReceive((fetcher) => {
@@ -73,7 +73,7 @@ module.exports = NodeHelper.create({
this.fetchers[identifier + url] = fetcher;
} else {
Log.log("Use existing calendarfetcher for url: " + url);
Log.log(`Use existing calendarfetcher for url: ${url}`);
fetcher = this.fetchers[identifier + url];
fetcher.broadcastEvents();
}

View File

@@ -45,7 +45,7 @@ Module.register("clock", {
},
// Define start sequence.
start: function () {
Log.info("Starting module: " + this.name);
Log.info(`Starting module: ${this.name}`);
// Schedule update interval.
this.second = moment().second();
@@ -137,9 +137,9 @@ Module.register("clock", {
}
if (this.config.clockBold) {
timeString = now.format(hourSymbol + '[<span class="bold">]mm[</span>]');
timeString = now.format(`${hourSymbol}[<span class="bold">]mm[</span>]`);
} else {
timeString = now.format(hourSymbol + ":mm");
timeString = now.format(`${hourSymbol}:mm`);
}
if (this.config.showDate) {
@@ -172,7 +172,7 @@ Module.register("clock", {
* @returns {string} The formatted time string
*/
function formatTime(config, time) {
let formatString = hourSymbol + ":mm";
let formatString = `${hourSymbol}:mm`;
if (config.showPeriod && config.timeFormat !== 24) {
formatString += config.showPeriodUpper ? "A" : "a";
}
@@ -195,19 +195,11 @@ Module.register("clock", {
nextEvent = tomorrowSunTimes.sunrise;
}
const untilNextEvent = moment.duration(moment(nextEvent).diff(now));
const untilNextEventString = untilNextEvent.hours() + "h " + untilNextEvent.minutes() + "m";
const untilNextEventString = `${untilNextEvent.hours()}h ${untilNextEvent.minutes()}m`;
sunWrapper.innerHTML =
'<span class="' +
(isVisible ? "bright" : "") +
'"><i class="fas fa-sun" aria-hidden="true"></i> ' +
untilNextEventString +
"</span>" +
'<span><i class="fas fa-arrow-up" aria-hidden="true"></i> ' +
formatTime(this.config, sunTimes.sunrise) +
"</span>" +
'<span><i class="fas fa-arrow-down" aria-hidden="true"></i> ' +
formatTime(this.config, sunTimes.sunset) +
"</span>";
`<span class="${isVisible ? "bright" : ""}"><i class="fas fa-sun" aria-hidden="true"></i> ${untilNextEventString}</span>` +
`<span><i class="fas fa-arrow-up" aria-hidden="true"></i> ${formatTime(this.config, sunTimes.sunrise)}</span>` +
`<span><i class="fas fa-arrow-down" aria-hidden="true"></i> ${formatTime(this.config, sunTimes.sunset)}</span>`;
digitalWrapper.appendChild(sunWrapper);
}
@@ -226,19 +218,11 @@ Module.register("clock", {
moonSet = nextMoonTimes.set;
}
const isVisible = now.isBetween(moonRise, moonSet) || moonTimes.alwaysUp === true;
const illuminatedFractionString = Math.round(moonIllumination.fraction * 100) + "%";
const illuminatedFractionString = `${Math.round(moonIllumination.fraction * 100)}%`;
moonWrapper.innerHTML =
'<span class="' +
(isVisible ? "bright" : "") +
'"><i class="fas fa-moon" aria-hidden="true"></i> ' +
illuminatedFractionString +
"</span>" +
'<span><i class="fas fa-arrow-up" aria-hidden="true"></i> ' +
(moonRise ? formatTime(this.config, moonRise) : "...") +
"</span>" +
'<span><i class="fas fa-arrow-down" aria-hidden="true"></i> ' +
(moonSet ? formatTime(this.config, moonSet) : "...") +
"</span>";
`<span class="${isVisible ? "bright" : ""}"><i class="fas fa-moon" aria-hidden="true"></i> ${illuminatedFractionString}</span>` +
`<span><i class="fas fa-arrow-up" aria-hidden="true"></i> ${moonRise ? formatTime(this.config, moonRise) : "..."}</span>` +
`<span><i class="fas fa-arrow-down" aria-hidden="true"></i> ${moonSet ? formatTime(this.config, moonSet) : "..."}</span>`;
digitalWrapper.appendChild(moonWrapper);
}
@@ -266,7 +250,7 @@ Module.register("clock", {
analogWrapper.style.height = this.config.analogSize;
if (this.config.analogFace !== "" && this.config.analogFace !== "simple" && this.config.analogFace !== "none") {
analogWrapper.style.background = "url(" + this.data.path + "faces/" + this.config.analogFace + ".svg)";
analogWrapper.style.background = `url(${this.data.path}faces/${this.config.analogFace}.svg)`;
analogWrapper.style.backgroundSize = "100%";
// The following line solves issue: https://github.com/MichMich/MagicMirror/issues/611
@@ -280,11 +264,11 @@ Module.register("clock", {
const clockHour = document.createElement("div");
clockHour.id = "clock-hour";
clockHour.style.transform = "rotate(" + hour + "deg)";
clockHour.style.transform = `rotate(${hour}deg)`;
clockHour.className = "clock-hour";
const clockMinute = document.createElement("div");
clockMinute.id = "clock-minute";
clockMinute.style.transform = "rotate(" + minute + "deg)";
clockMinute.style.transform = `rotate(${minute}deg)`;
clockMinute.className = "clock-minute";
// Combine analog wrappers
@@ -294,7 +278,7 @@ Module.register("clock", {
if (this.config.displaySeconds) {
const clockSecond = document.createElement("div");
clockSecond.id = "clock-second";
clockSecond.style.transform = "rotate(" + second + "deg)";
clockSecond.style.transform = `rotate(${second}deg)`;
clockSecond.className = "clock-second";
clockSecond.style.backgroundColor = this.config.secondsColor;
clockFace.appendChild(clockSecond);
@@ -316,7 +300,7 @@ Module.register("clock", {
} else if (this.config.displayType === "digital") {
wrapper.appendChild(digitalWrapper);
} else if (this.config.displayType === "both") {
wrapper.classList.add("clock-grid-" + this.config.analogPlacement);
wrapper.classList.add(`clock-grid-${this.config.analogPlacement}`);
wrapper.appendChild(analogWrapper);
wrapper.appendChild(digitalWrapper);
}

View File

@@ -34,7 +34,7 @@ Module.register("compliments", {
// Define start sequence.
start: async function () {
Log.info("Starting module: " + this.name);
Log.info(`Starting module: ${this.name}`);
this.lastComplimentIndex = -1;

View File

@@ -44,7 +44,7 @@ Module.register("newsfeed", {
getUrlPrefix: function (item) {
if (item.useCorsProxy) {
return location.protocol + "//" + location.host + "/cors?url=";
return `${location.protocol}//${location.host}/cors?url=`;
} else {
return "";
}
@@ -70,7 +70,7 @@ Module.register("newsfeed", {
// Define start sequence.
start: function () {
Log.info("Starting module: " + this.name);
Log.info(`Starting module: ${this.name}`);
// Set locale.
moment.locale(config.language);
@@ -346,7 +346,7 @@ Module.register("newsfeed", {
this.activeItem = 0;
}
this.resetDescrOrFullArticleAndTimer();
Log.debug(this.name + " - going from article #" + before + " to #" + this.activeItem + " (of " + this.newsItems.length + ")");
Log.debug(`${this.name} - going from article #${before} to #${this.activeItem} (of ${this.newsItems.length})`);
this.updateDom(100);
} else if (notification === "ARTICLE_PREVIOUS") {
this.activeItem--;
@@ -354,7 +354,7 @@ Module.register("newsfeed", {
this.activeItem = this.newsItems.length - 1;
}
this.resetDescrOrFullArticleAndTimer();
Log.debug(this.name + " - going from article #" + before + " to #" + this.activeItem + " (of " + this.newsItems.length + ")");
Log.debug(`${this.name} - going from article #${before} to #${this.activeItem} (of ${this.newsItems.length})`);
this.updateDom(100);
}
// if "more details" is received the first time: show article summary, on second time show full article
@@ -363,8 +363,8 @@ Module.register("newsfeed", {
if (this.config.showFullArticle === true) {
this.scrollPosition += this.config.scrollLength;
window.scrollTo(0, this.scrollPosition);
Log.debug(this.name + " - scrolling down");
Log.debug(this.name + " - ARTICLE_MORE_DETAILS, scroll position: " + this.config.scrollLength);
Log.debug(`${this.name} - scrolling down`);
Log.debug(`${this.name} - ARTICLE_MORE_DETAILS, scroll position: ${this.config.scrollLength}`);
} else {
this.showFullArticle();
}
@@ -372,12 +372,12 @@ Module.register("newsfeed", {
if (this.config.showFullArticle === true) {
this.scrollPosition -= this.config.scrollLength;
window.scrollTo(0, this.scrollPosition);
Log.debug(this.name + " - scrolling up");
Log.debug(this.name + " - ARTICLE_SCROLL_UP, scroll position: " + this.config.scrollLength);
Log.debug(`${this.name} - scrolling up`);
Log.debug(`${this.name} - ARTICLE_SCROLL_UP, scroll position: ${this.config.scrollLength}`);
}
} else if (notification === "ARTICLE_LESS_DETAILS") {
this.resetDescrOrFullArticleAndTimer();
Log.debug(this.name + " - showing only article titles again");
Log.debug(`${this.name} - showing only article titles again`);
this.updateDom(100);
} else if (notification === "ARTICLE_TOGGLE_FULL") {
if (this.config.showFullArticle) {
@@ -406,7 +406,7 @@ Module.register("newsfeed", {
}
clearInterval(this.timer);
this.timer = null;
Log.debug(this.name + " - showing " + this.isShowingDescription ? "article description" : "full article");
Log.debug(`${this.name} - showing ${this.isShowingDescription ? "article description" : "full article"}`);
this.updateDom(100);
}
});

View File

@@ -64,9 +64,9 @@ const NewsfeedFetcher = function (url, reloadInterval, encoding, logFeedWarnings
} else if (logFeedWarnings) {
Log.warn("Can't parse feed item:");
Log.warn(item);
Log.warn("Title: " + title);
Log.warn("Description: " + description);
Log.warn("Pubdate: " + pubdate);
Log.warn(`Title: ${title}`);
Log.warn(`Description: ${description}`);
Log.warn(`Pubdate: ${pubdate}`);
}
});
@@ -90,16 +90,16 @@ const NewsfeedFetcher = function (url, reloadInterval, encoding, logFeedWarnings
const ttlms = Math.min(minutes * 60 * 1000, 86400000);
if (ttlms > reloadInterval) {
reloadInterval = ttlms;
Log.info("Newsfeed-Fetcher: reloadInterval set to ttl=" + reloadInterval + " for url " + url);
Log.info(`Newsfeed-Fetcher: reloadInterval set to ttl=${reloadInterval} for url ${url}`);
}
} catch (error) {
Log.warn("Newsfeed-Fetcher: feed ttl is no valid integer=" + minutes + " for url " + url);
Log.warn(`Newsfeed-Fetcher: feed ttl is no valid integer=${minutes} for url ${url}`);
}
});
const nodeVersion = Number(process.version.match(/^v(\d+\.\d+)/)[1]);
const headers = {
"User-Agent": "Mozilla/5.0 (Node.js " + nodeVersion + ") MagicMirror/" + global.version,
"User-Agent": `Mozilla/5.0 (Node.js ${nodeVersion}) MagicMirror/${global.version}`,
"Cache-Control": "max-age=0, no-cache, no-store, must-revalidate",
Pragma: "no-cache"
};
@@ -159,7 +159,7 @@ const NewsfeedFetcher = function (url, reloadInterval, encoding, logFeedWarnings
Log.info("Newsfeed-Fetcher: No items to broadcast yet.");
return;
}
Log.info("Newsfeed-Fetcher: Broadcasting " + items.length + " items.");
Log.info(`Newsfeed-Fetcher: Broadcasting ${items.length} items.`);
itemsReceivedCallback(this);
};

View File

@@ -12,7 +12,7 @@ const Log = require("logger");
module.exports = NodeHelper.create({
// Override start method.
start: function () {
Log.log("Starting node helper for: " + this.name);
Log.log(`Starting node helper for: ${this.name}`);
this.fetchers = [];
},
@@ -47,7 +47,7 @@ module.exports = NodeHelper.create({
let fetcher;
if (typeof this.fetchers[url] === "undefined") {
Log.log("Create new newsfetcher for url: " + url + " - Interval: " + reloadInterval);
Log.log(`Create new newsfetcher for url: ${url} - Interval: ${reloadInterval}`);
fetcher = new NewsfeedFetcher(url, reloadInterval, encoding, config.logFeedWarnings, useCorsProxy);
fetcher.onReceive(() => {
@@ -64,7 +64,7 @@ module.exports = NodeHelper.create({
this.fetchers[url] = fetcher;
} else {
Log.log("Use existing newsfetcher for url: " + url);
Log.log(`Use existing newsfetcher for url: ${url}`);
fetcher = this.fetchers[url];
fetcher.setReloadInterval(reloadInterval);
fetcher.broadcastItems();

View File

@@ -131,7 +131,7 @@ class GitHelper {
// this is the default if there was no match from "git fetch -n --dry-run".
// Its a fallback because if there was a real "git fetch", the above "git fetch -n --dry-run" would deliver nothing.
let refDiff = gitInfo.current + "..origin/" + gitInfo.current;
let refDiff = `${gitInfo.current}..origin/${gitInfo.current}`;
if (matches && matches[0]) {
refDiff = matches[0];
}

View File

@@ -138,7 +138,7 @@ WeatherProvider.register("envcanada", {
// being accessed. This is only pertinent when using the EC data elements that contain a textual forecast.
//
getUrl() {
return "https://dd.weather.gc.ca/citypage_weather/xml/" + this.config.provCode + "/" + this.config.siteCode + "_e.xml";
return `https://dd.weather.gc.ca/citypage_weather/xml/${this.config.provCode}/${this.config.siteCode}_e.xml`;
},
//

View File

@@ -264,9 +264,9 @@ WeatherProvider.register("openmeteo", {
switch (key) {
case "hourly":
case "daily":
return encodeURIComponent(key) + "=" + params[key].join(",");
return `${encodeURIComponent(key)}=${params[key].join(",")}`;
default:
return encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
return `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`;
}
})
.join("&");

View File

@@ -413,8 +413,8 @@ WeatherProvider.register("openweathermap", {
getParams() {
let params = "?";
if (this.config.weatherEndpoint === "/onecall") {
params += "lat=" + this.config.lat;
params += "&lon=" + this.config.lon;
params += `lat=${this.config.lat}`;
params += `&lon=${this.config.lon}`;
if (this.config.type === "current") {
params += "&exclude=minutely,hourly,daily";
} else if (this.config.type === "hourly") {
@@ -425,23 +425,23 @@ WeatherProvider.register("openweathermap", {
params += "&exclude=minutely";
}
} else if (this.config.lat && this.config.lon) {
params += "lat=" + this.config.lat + "&lon=" + this.config.lon;
params += `lat=${this.config.lat}&lon=${this.config.lon}`;
} else if (this.config.locationID) {
params += "id=" + this.config.locationID;
params += `id=${this.config.locationID}`;
} else if (this.config.location) {
params += "q=" + this.config.location;
params += `q=${this.config.location}`;
} else if (this.firstEvent && this.firstEvent.geo) {
params += "lat=" + this.firstEvent.geo.lat + "&lon=" + this.firstEvent.geo.lon;
params += `lat=${this.firstEvent.geo.lat}&lon=${this.firstEvent.geo.lon}`;
} else if (this.firstEvent && this.firstEvent.location) {
params += "q=" + this.firstEvent.location;
params += `q=${this.firstEvent.location}`;
} else {
this.hide(this.config.animationSpeed, { lockString: this.identifier });
return;
}
params += "&units=metric"; // WeatherProviders should use metric internally and use the units only for when displaying data
params += "&lang=" + this.config.lang;
params += "&APPID=" + this.config.apiKey;
params += `&lang=${this.config.lang}`;
params += `&APPID=${this.config.apiKey}`;
return params;
}

View File

@@ -33,7 +33,7 @@ WeatherProvider.register("smhi", {
this.setFetchedLocation(this.config.location || `(${coordinates.lat},${coordinates.lon})`);
this.setCurrentWeather(weatherObject);
})
.catch((error) => Log.error("Could not load data: " + error.message))
.catch((error) => Log.error(`Could not load data: ${error.message}`))
.finally(() => this.updateAvailable());
},
@@ -48,7 +48,7 @@ WeatherProvider.register("smhi", {
this.setFetchedLocation(this.config.location || `(${coordinates.lat},${coordinates.lon})`);
this.setWeatherForecast(weatherObjects);
})
.catch((error) => Log.error("Could not load data: " + error.message))
.catch((error) => Log.error(`Could not load data: ${error.message}`))
.finally(() => this.updateAvailable());
},
@@ -63,7 +63,7 @@ WeatherProvider.register("smhi", {
this.setFetchedLocation(this.config.location || `(${coordinates.lat},${coordinates.lon})`);
this.setWeatherHourly(weatherObjects);
})
.catch((error) => Log.error("Could not load data: " + error.message))
.catch((error) => Log.error(`Could not load data: ${error.message}`))
.finally(() => this.updateAvailable());
},
@@ -75,7 +75,7 @@ WeatherProvider.register("smhi", {
setConfig(config) {
this.config = config;
if (!config.precipitationValue || ["pmin", "pmean", "pmedian", "pmax"].indexOf(config.precipitationValue) === -1) {
Log.log("invalid or not set: " + config.precipitationValue);
Log.log(`invalid or not set: ${config.precipitationValue}`);
config.precipitationValue = this.defaults.precipitationValue;
}
},

View File

@@ -195,8 +195,8 @@ WeatherProvider.register("ukmetoffice", {
*/
getParams(forecastType) {
let params = "?";
params += "res=" + forecastType;
params += "&key=" + this.config.apiKey;
params += `res=${forecastType}`;
params += `&key=${this.config.apiKey}`;
return params;
}
});

View File

@@ -55,9 +55,9 @@ WeatherProvider.register("ukmetofficedatahub", {
// Build URL with query strings according to DataHub API (https://metoffice.apiconnect.ibmcloud.com/metoffice/production/api)
getUrl(forecastType) {
let queryStrings = "?";
queryStrings += "latitude=" + this.config.lat;
queryStrings += "&longitude=" + this.config.lon;
queryStrings += "&includeLocationName=" + true;
queryStrings += `latitude=${this.config.lat}`;
queryStrings += `&longitude=${this.config.lon}`;
queryStrings += `&includeLocationName=${true}`;
// Return URL, making sure there is a trailing "/" in the base URL.
return this.config.apiBase + (this.config.apiBase.endsWith("/") ? "" : "/") + forecastType + queryStrings;
@@ -104,7 +104,7 @@ WeatherProvider.register("ukmetofficedatahub", {
})
// Catch any error(s)
.catch((error) => Log.error("Could not load data: " + error.message))
.catch((error) => Log.error(`Could not load data: ${error.message}`))
// Let the module know there is data available
.finally(() => this.updateAvailable());
@@ -173,7 +173,7 @@ WeatherProvider.register("ukmetofficedatahub", {
})
// Catch any error(s)
.catch((error) => Log.error("Could not load data: " + error.message))
.catch((error) => Log.error(`Could not load data: ${error.message}`))
// Let the module know there is new data available
.finally(() => this.updateAvailable());

View File

@@ -55,7 +55,7 @@ WeatherProvider.register("weatherbit", {
const forecast = this.generateWeatherObjectsFromForecast(data.data);
this.setWeatherForecast(forecast);
this.fetchedLocationName = data.city_name + ", " + data.state_code;
this.fetchedLocationName = `${data.city_name}, ${data.state_code}`;
})
.catch(function (request) {
Log.error("Could not load data ... ", request);
@@ -111,7 +111,7 @@ WeatherProvider.register("weatherbit", {
currentWeather.sunrise = moment(currentWeatherData.data[0].sunrise, "HH:mm").add(tzOffset, "m");
currentWeather.sunset = moment(currentWeatherData.data[0].sunset, "HH:mm").add(tzOffset, "m");
this.fetchedLocationName = currentWeatherData.data[0].city_name + ", " + currentWeatherData.data[0].state_code;
this.fetchedLocationName = `${currentWeatherData.data[0].city_name}, ${currentWeatherData.data[0].state_code}`;
return currentWeather;
},

View File

@@ -129,10 +129,10 @@ WeatherProvider.register("weathergov", {
// points URL did not respond with usable data.
return;
}
this.fetchedLocationName = data.properties.relativeLocation.properties.city + ", " + data.properties.relativeLocation.properties.state;
Log.log("Forecast location is " + this.fetchedLocationName);
this.forecastURL = data.properties.forecast + "?units=si";
this.forecastHourlyURL = data.properties.forecastHourly + "?units=si";
this.fetchedLocationName = `${data.properties.relativeLocation.properties.city}, ${data.properties.relativeLocation.properties.state}`;
Log.log(`Forecast location is ${this.fetchedLocationName}`);
this.forecastURL = `${data.properties.forecast}?units=si`;
this.forecastHourlyURL = `${data.properties.forecastHourly}?units=si`;
this.forecastGridDataURL = data.properties.forecastGridData;
this.observationStationsURL = data.properties.observationStations;
// with this URL, we chain another promise for the station obs URL
@@ -143,7 +143,7 @@ WeatherProvider.register("weathergov", {
// obs station URL did not respond with usable data.
return;
}
this.stationObsURL = obsData.features[0].id + "/observations/latest";
this.stationObsURL = `${obsData.features[0].id}/observations/latest`;
})
.catch((err) => {
Log.error(err);

View File

@@ -252,12 +252,12 @@ WeatherProvider.register("yr", {
this.cacheStellarData(stellarData);
resolve(stellarData);
} else {
reject("No stellar data returned from Yr for " + tomorrow);
reject(`No stellar data returned from Yr for ${tomorrow}`);
}
})
.catch((err) => {
Log.error(err);
reject("Unable to get stellar data from Yr for " + tomorrow);
reject(`Unable to get stellar data from Yr for ${tomorrow}`);
})
.finally(() => {
localStorage.removeItem("yrIsFetchingStellarData");
@@ -275,7 +275,7 @@ WeatherProvider.register("yr", {
this.cacheStellarData(stellarData);
resolve(stellarData);
} else {
Log.error("Something went wrong when fetching stellar data. Responses: " + stellarData);
Log.error(`Something went wrong when fetching stellar data. Responses: ${stellarData}`);
reject(stellarData);
}
})

View File

@@ -60,13 +60,13 @@ Module.register("weather", {
// Return the scripts that are necessary for the weather module.
getScripts: function () {
return ["moment.js", this.file("../utils.js"), "weatherutils.js", "weatherprovider.js", "weatherobject.js", "suncalc.js", this.file("providers/" + this.config.weatherProvider.toLowerCase() + ".js")];
return ["moment.js", this.file("../utils.js"), "weatherutils.js", "weatherprovider.js", "weatherobject.js", "suncalc.js", this.file(`providers/${this.config.weatherProvider.toLowerCase()}.js`)];
},
// Override getHeader method.
getHeader: function () {
if (this.config.appendLocationNameToHeader && this.weatherProvider) {
if (this.data.header) return this.data.header + " " + this.weatherProvider.fetchedLocation();
if (this.data.header) return `${this.data.header} ${this.weatherProvider.fetchedLocation()}`;
else return this.weatherProvider.fetchedLocation();
}
@@ -233,7 +233,7 @@ Module.register("weather", {
"unit",
function (value, type, valueUnit) {
if (type === "temperature") {
value = this.roundValue(WeatherUtils.convertTemp(value, this.config.tempUnits)) + "°";
value = `${this.roundValue(WeatherUtils.convertTemp(value, this.config.tempUnits))}°`;
if (this.config.degreeLabel) {
if (this.config.tempUnits === "metric") {
value += "C";