-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
module.js
509 lines (441 loc) · 14.4 KB
/
module.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/* global Class, cloneObject, Loader, MMSocket, nunjucks, Translator */
/* MagicMirror²
* Module Blueprint.
* @typedef {Object} Module
*
* By Michael Teeuw https://michaelteeuw.nl
* MIT Licensed.
*/
const Module = Class.extend({
/*********************************************************
* All methods (and properties) below can be subclassed. *
*********************************************************/
// Set the minimum MagicMirror² module version for this module.
requiresVersion: "2.0.0",
// Module config defaults.
defaults: {},
// Timer reference used for showHide animation callbacks.
showHideTimer: null,
// Array to store lockStrings. These strings are used to lock
// visibility when hiding and showing module.
lockStrings: [],
// Storage of the nunjucks Environment,
// This should not be referenced directly.
// Use the nunjucksEnvironment() to get it.
_nunjucksEnvironment: null,
/**
* Called when the module is instantiated.
*/
init: function () {
//Log.log(this.defaults);
},
/**
* Called when the module is started.
*/
start: async function () {
Log.info(`Starting module: ${this.name}`);
},
/**
* Returns a list of scripts the module requires to be loaded.
* @returns {string[]} An array with filenames.
*/
getScripts: function () {
return [];
},
/**
* Returns a list of stylesheets the module requires to be loaded.
* @returns {string[]} An array with filenames.
*/
getStyles: function () {
return [];
},
/**
* Returns a map of translation files the module requires to be loaded.
*
* return Map<String, String> -
* @returns {*} A map with langKeys and filenames.
*/
getTranslations: function () {
return false;
},
/**
* Generates the dom which needs to be displayed. This method is called by the MagicMirror² core.
* This method can to be subclassed if the module wants to display info on the mirror.
* Alternatively, the getTemplate method could be subclassed.
* @returns {HTMLElement|Promise} The dom or a promise with the dom to display.
*/
getDom: function () {
return new Promise((resolve) => {
const div = document.createElement("div");
const template = this.getTemplate();
const templateData = this.getTemplateData();
// Check to see if we need to render a template string or a file.
if (/^.*((\.html)|(\.njk))$/.test(template)) {
// the template is a filename
this.nunjucksEnvironment().render(template, templateData, function (err, res) {
if (err) {
Log.error(err);
}
div.innerHTML = res;
resolve(div);
});
} else {
// the template is a template string.
div.innerHTML = this.nunjucksEnvironment().renderString(template, templateData);
resolve(div);
}
});
},
/**
* Generates the header string which needs to be displayed if a user has a header configured for this module.
* This method is called by the MagicMirror² core, but only if the user has configured a default header for the module.
* This method needs to be subclassed if the module wants to display modified headers on the mirror.
* @returns {string} The header to display above the header.
*/
getHeader: function () {
return this.data.header;
},
/**
* Returns the template for the module which is used by the default getDom implementation.
* This method needs to be subclassed if the module wants to use a template.
* It can either return a template sting, or a template filename.
* If the string ends with '.html' it's considered a file from within the module's folder.
* @returns {string} The template string of filename.
*/
getTemplate: function () {
return `<div class="normal">${this.name}</div><div class="small dimmed">${this.identifier}</div>`;
},
/**
* Returns the data to be used in the template.
* This method needs to be subclassed if the module wants to use a custom data.
* @returns {object} The data for the template
*/
getTemplateData: function () {
return {};
},
/**
* Called by the MagicMirror² core when a notification arrives.
* @param {string} notification The identifier of the notification.
* @param {*} payload The payload of the notification.
* @param {Module} sender The module that sent the notification.
*/
notificationReceived: function (notification, payload, sender) {
if (sender) {
// Log.log(this.name + " received a module notification: " + notification + " from sender: " + sender.name);
} else {
// Log.log(this.name + " received a system notification: " + notification);
}
},
/**
* Returns the nunjucks environment for the current module.
* The environment is checked in the _nunjucksEnvironment instance variable.
* @returns {object} The Nunjucks Environment
*/
nunjucksEnvironment: function () {
if (this._nunjucksEnvironment !== null) {
return this._nunjucksEnvironment;
}
this._nunjucksEnvironment = new nunjucks.Environment(new nunjucks.WebLoader(this.file(""), { async: true }), {
trimBlocks: true,
lstripBlocks: true
});
this._nunjucksEnvironment.addFilter("translate", (str, variables) => {
return nunjucks.runtime.markSafe(this.translate(str, variables));
});
return this._nunjucksEnvironment;
},
/**
* Called when a socket notification arrives.
* @param {string} notification The identifier of the notification.
* @param {*} payload The payload of the notification.
*/
socketNotificationReceived: function (notification, 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.`);
},
/**
* Called when the module is shown.
*/
resume: function () {
Log.log(`${this.name} is resumed.`);
},
/*********************************************
* The methods below don't need subclassing. *
*********************************************/
/**
* Set the module data.
* @param {object} data The module data
*/
setData: function (data) {
this.data = data;
this.name = data.name;
this.identifier = data.identifier;
this.hidden = false;
this.hasAnimateIn = false;
this.hasAnimateOut = false;
this.setConfig(data.config, data.configDeepMerge);
},
/**
* Set the module config and combine it with the module defaults.
* @param {object} config The combined module config.
* @param {boolean} deep Merge module config in deep.
*/
setConfig: function (config, deep) {
this.config = deep ? configMerge({}, this.defaults, config) : Object.assign({}, this.defaults, config);
},
/**
* Returns a socket object. If it doesn't exist, it's created.
* It also registers the notification callback.
* @returns {MMSocket} a socket object
*/
socket: function () {
if (typeof this._socket === "undefined") {
this._socket = new MMSocket(this.name);
}
this._socket.setNotificationCallback((notification, payload) => {
this.socketNotificationReceived(notification, payload);
});
return this._socket;
},
/**
* Retrieve the path to a module file.
* @param {string} file Filename
* @returns {string} the file path
*/
file: function (file) {
return `${this.data.path}/${file}`.replace("//", "/");
},
/**
* Load all required stylesheets by requesting the MM object to load the files.
* @returns {Promise<void>}
*/
loadStyles: function () {
return this.loadDependencies("getStyles");
},
/**
* Load all required scripts by requesting the MM object to load the files.
* @returns {Promise<void>}
*/
loadScripts: function () {
return this.loadDependencies("getScripts");
},
/**
* Helper method to load all dependencies.
* @param {string} funcName Function name to call to get scripts or styles.
* @returns {Promise<void>}
*/
loadDependencies: async function (funcName) {
let dependencies = this[funcName]();
const loadNextDependency = async () => {
if (dependencies.length > 0) {
const nextDependency = dependencies[0];
await Loader.loadFileForModule(nextDependency, this);
dependencies = dependencies.slice(1);
await loadNextDependency();
} else {
return Promise.resolve();
}
};
await loadNextDependency();
},
/**
* Load all translations.
* @returns {Promise<void>}
*/
loadTranslations: async function () {
const translations = this.getTranslations() || {};
const language = config.language.toLowerCase();
const languages = Object.keys(translations);
const fallbackLanguage = languages[0];
if (languages.length === 0) {
return;
}
const translationFile = translations[language];
const translationsFallbackFile = translations[fallbackLanguage];
if (!translationFile) {
return Translator.load(this, translationsFallbackFile, true);
}
await Translator.load(this, translationFile, false);
if (translationFile !== translationsFallbackFile) {
return Translator.load(this, translationsFallbackFile, true);
}
},
/**
* Request the translation for a given key with optional variables and default value.
* @param {string} key The key of the string to translate
* @param {string|object} [defaultValueOrVariables] The default value or variables for translating.
* @param {string} [defaultValue] The default value with variables.
* @returns {string} the translated key
*/
translate: function (key, defaultValueOrVariables, defaultValue) {
if (typeof defaultValueOrVariables === "object") {
return Translator.translate(this, key, defaultValueOrVariables) || defaultValue || "";
}
return Translator.translate(this, key) || defaultValueOrVariables || "";
},
/**
* Request an (animated) update of the module.
* @param {number|object} [updateOptions] The speed of the animation or object with for updateOptions (speed/animates)
*/
updateDom: function (updateOptions) {
MM.updateDom(this, updateOptions);
},
/**
* Send a notification to all modules.
* @param {string} notification The identifier of the notification.
* @param {*} payload The payload of the notification.
*/
sendNotification: function (notification, payload) {
MM.sendNotification(notification, payload, this);
},
/**
* Send a socket notification to the node helper.
* @param {string} notification The identifier of the notification.
* @param {*} payload The payload of the notification.
*/
sendSocketNotification: function (notification, payload) {
this.socket().sendNotification(notification, payload);
},
/**
* Hide this module.
* @param {number} speed The speed of the hide animation.
* @param {Function} callback Called when the animation is done.
* @param {object} [options] Optional settings for the hide method.
*/
hide: function (speed, callback, options = {}) {
let usedCallback = callback || function () {};
let usedOptions = options;
if (typeof callback === "object") {
Log.error("Parameter mismatch in module.hide: callback is not an optional parameter!");
usedOptions = callback;
usedCallback = function () {};
}
MM.hideModule(
this,
speed,
() => {
this.suspend();
usedCallback();
},
usedOptions
);
},
/**
* Show this module.
* @param {number} speed The speed of the show animation.
* @param {Function} callback Called when the animation is done.
* @param {object} [options] Optional settings for the show method.
*/
show: function (speed, callback, options) {
let usedCallback = callback || function () {};
let usedOptions = options;
if (typeof callback === "object") {
Log.error("Parameter mismatch in module.show: callback is not an optional parameter!");
usedOptions = callback;
usedCallback = function () {};
}
MM.showModule(
this,
speed,
() => {
this.resume();
usedCallback();
},
usedOptions
);
}
});
/**
* Merging MagicMirror² (or other) default/config script by @bugsounet
* Merge 2 objects or/with array
*
* Usage:
* -------
* this.config = configMerge({}, this.defaults, this.config)
* -------
* arg1: initial object
* arg2: config model
* arg3: config to merge
* -------
* why using it ?
* Object.assign() function don't to all job
* it don't merge all thing in deep
* -> object in object and array is not merging
* -------
*
* Todo: idea of Mich determinate what do you want to merge or not
* @param {object} result the initial object
* @returns {object} the merged config
*/
function configMerge(result) {
const stack = Array.prototype.slice.call(arguments, 1);
let item, key;
while (stack.length) {
item = stack.shift();
for (key in item) {
if (item.hasOwnProperty(key)) {
if (typeof result[key] === "object" && result[key] && Object.prototype.toString.call(result[key]) !== "[object Array]") {
if (typeof item[key] === "object" && item[key] !== null) {
result[key] = configMerge({}, result[key], item[key]);
} else {
result[key] = item[key];
}
} else {
result[key] = item[key];
}
}
}
}
return result;
}
Module.definitions = {};
Module.create = function (name) {
// Make sure module definition is available.
if (!Module.definitions[name]) {
return;
}
const moduleDefinition = Module.definitions[name];
const clonedDefinition = cloneObject(moduleDefinition);
// Note that we clone the definition. Otherwise the objects are shared, which gives problems.
const ModuleClass = Module.extend(clonedDefinition);
return new ModuleClass();
};
Module.register = function (name, moduleDefinition) {
if (moduleDefinition.requiresVersion) {
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}'`);
return;
}
}
Log.log(`Module registered: ${name}`);
Module.definitions[name] = moduleDefinition;
};
window.Module = Module;
/**
* Compare two semantic version numbers and return the difference.
* @param {string} a Version number a.
* @param {string} b Version number b.
* @returns {number} A positive number if a is larger than b, a negative
* number if a is smaller and 0 if they are the same
*/
function cmpVersions(a, b) {
const regExStrip0 = /(\.0+)+$/;
const segmentsA = a.replace(regExStrip0, "").split(".");
const segmentsB = b.replace(regExStrip0, "").split(".");
const l = Math.min(segmentsA.length, segmentsB.length);
for (let i = 0; i < l; i++) {
let diff = parseInt(segmentsA[i], 10) - parseInt(segmentsB[i], 10);
if (diff) {
return diff;
}
}
return segmentsA.length - segmentsB.length;
}