-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMMM-Chores.js
More file actions
801 lines (722 loc) · 27.4 KB
/
MMM-Chores.js
File metadata and controls
801 lines (722 loc) · 27.4 KB
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
const BOARD_TITLES = {
weekly: "Tasks Completed Per Week",
weekdays: "Busiest Weekdays",
perPerson: "Chores Per Person",
perPersonFinished: "Chores Per Person (Finished)",
perPersonFinishedWeek: "Chores Per Person (Finished This Week)",
perPersonUnfinished: "Chores Per Person (Unfinished)",
perPersonUnfinishedWeek: "Chores Per Person (Unfinished This Week)",
taskmaster: "Taskmaster This Month",
lazyLegends: "Lazy Legends",
speedDemons: "Speed Demons",
weekendWarriors: "Weekend Warriors",
slacker9000: "Slacker Detector 9000"
};
Module.register("MMM-Chores", {
defaults: {
updateInterval: 60 * 1000,
adminPort: 5003,
settings: "locked", // set to "unlocked" to enable settings popup or to a 6-digit PIN (e.g. "000000") to require a PIN
showDays: 1,
showPast: false,
dateFormatting: "yyyy-mm-dd", // Standardformat, kan ändras i config
textMirrorSize: "small", // small, medium or large
useAI: true, // hide AI features when false
openaiApiKey: "",
pushoverApiKey: "",
pushoverUser: "",
pushoverEnabled: false,
reminderTime: "",
login: false,
users: [],
showAnalyticsOnMirror: false, // display analytics cards on the mirror
analyticsCards: [], // board types selected in the admin UI
showCoinsOnMirror: true, // display coin balances next to assignees when coin system is active
showLevelOnMirror: true, // display level badge next to assignees when level system is active
showRedeemedRewards: true, // display redeemed rewards on mirror above chores when coin system is active
usePointSystem: false, // use point system instead of level system
leveling: {
enabled: true,
mode: "years",
yearsToMaxLevel: 3,
choresPerWeekEstimate: 4,
choresToMaxLevel: 0
},
levelTitles: [
"Junior",
"Apprentice",
"Journeyman",
"Experienced",
"Expert",
"Veteran",
"Master",
"Grandmaster",
"Legend",
"Mythic"
],
customLevelTitles: {},
voiceAssistant: {
enabled: false,
language: null, // null = derive from module language (en->en-US, sv->sv-SE, etc.)
continuous: false,
interimResults: false,
maxAlternatives: 1,
ttsEnabled: true,
ttsVoice: "default",
ttsRate: 1.0,
ttsPitch: 1.0,
showTranscription: true,
wakeWord: null // Optional wake word like "hey chores"
},
ttsAudio: {
volume: 0.7,
pauseMs: 600,
fadeMs: 120
}
},
start() {
this.tasks = [];
this.allTasks = [];
this.people = [];
this.redemptions = [];
this.levelInfo = null;
this.chartInstances = {};
this.voiceRecognition = null;
this.isListening = false;
this.lastTranscript = "";
this.sendSocketNotification("INIT_SERVER", this.config);
this.scheduleUpdate();
if (this.config.voiceAssistant && this.config.voiceAssistant.enabled) {
this.initVoiceRecognition();
}
},
getStyles() {
return ["MMM-Chores.css"];
},
getScripts() {
if (this.config.showAnalyticsOnMirror) {
return [
"https://cdn.jsdelivr.net/npm/chart.js@4.3.0/dist/chart.umd.min.js"
];
}
return [];
},
scheduleUpdate() {
if (this.config.showAnalyticsOnMirror) {
// Avoid refreshing the entire DOM while analytics charts are visible to
// prevent a flashing effect. Updates instead come from socket
// notifications when data changes.
return;
}
setInterval(() => this.updateDom(), this.config.updateInterval);
},
socketNotificationReceived(notification, payload) {
if (notification === "TASKS_UPDATE") {
this.allTasks = payload;
this.updateDom();
}
if (notification === "CHORES_DATA") {
this.tasks = payload;
this.updateDom();
}
if (notification === "REDEMPTIONS_UPDATE") {
this.redemptions = Array.isArray(payload) ? payload : [];
this.updateDom();
}
if (notification === "PEOPLE_UPDATE") {
this.people = payload;
this.updateDom();
}
if (notification === "SETTINGS_UPDATE") {
const prevAnalytics = this.config.showAnalyticsOnMirror;
Object.assign(this.config, payload);
if (payload.levelingEnabled !== undefined) {
this.config.leveling = this.config.leveling || {};
this.config.leveling.enabled = payload.levelingEnabled;
}
if (payload.usePointSystem !== undefined) {
this.config.usePointSystem = payload.usePointSystem;
}
if (payload.showAnalyticsOnMirror && !prevAnalytics && typeof Chart === "undefined") {
const script = document.createElement("script");
script.src = "https://cdn.jsdelivr.net/npm/chart.js@4.3.0/dist/chart.umd.min.js";
script.onload = () => this.updateDom();
document.head.appendChild(script);
} else {
this.updateDom();
}
}
if (notification === "ANALYTICS_UPDATE") {
if (Array.isArray(payload)) {
this.config.analyticsCards = payload;
this.updateDom();
}
}
if (notification === "LEVEL_INFO") {
const prevTitle = this.levelInfo ? this.levelInfo.title : null;
this.levelInfo = payload;
if (prevTitle && prevTitle !== payload.title) {
this.titleChangeMessage = `Congrats! You advanced from ${prevTitle} to ${payload.title}!`;
setTimeout(() => { this.titleChangeMessage = null; this.updateDom(); }, 5000);
}
this.updateDom();
}
if (notification === "PUSHOVER_CONFIG_ERROR") {
this.sendNotification("SHOW_ALERT", {
type: "notification",
title: "MMM-Chores",
message: payload || "Please set pushoverApiKey and pushoverUser in config.js to use Pushover notifications."
});
}
if (notification === "VOICE_RESPONSE") {
if (this.config.voiceAssistant && this.config.voiceAssistant.ttsEnabled) {
this.speakResponse(payload.text);
}
if (payload.action) {
this.handleVoiceAction(payload.action);
}
}
},
shouldShowTask(task) {
const showDays = parseInt(this.config.showDays, 10);
const showPast = Boolean(this.config.showPast);
const today = new Date();
today.setHours(0, 0, 0, 0);
// Parse the task's date as a local date to avoid timezone shifts that
// make today's chores appear as past tasks in some regions.
let tDate;
if (typeof task.date === "string") {
const parts = task.date.split("-").map(Number);
if (parts.length === 3) {
tDate = new Date(parts[0], parts[1] - 1, parts[2]);
} else {
tDate = new Date(task.date);
}
} else {
tDate = new Date(task.date);
}
tDate.setHours(0, 0, 0, 0);
const diffMs = tDate - today;
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
if (diffDays < 0) {
// Task is in the past. Respect the showPast setting and only display
// unfinished tasks when enabled. Completed past tasks are always hidden.
if (!showPast) return false;
return !task.done;
}
return diffDays < showDays;
},
getPersonName(id) {
const p = this.people.find(p => p.id === id);
return p ? p.name : "";
},
getPerson(id) {
return this.people.find(p => p.id === id) || null;
},
toggleDone(task, done) {
this.sendSocketNotification("USER_TOGGLE_CHORE", { id: task.id, done });
},
handleVoiceAction(action) {
if (action.type === "TOGGLE_TASK" && action.taskId) {
const task = this.tasks.find(t => t.id === action.taskId);
if (task) {
this.toggleDone(task, action.done);
}
}
// Additional actions can be handled here
},
formatDate(dateStr) {
if (!dateStr) return "";
const match = dateStr.match(/(\d{4})-(\d{2})-(\d{2})/);
if (!match) return dateStr;
const [ , yyyy, mm, dd ] = match;
// Use module config for formatting. If set to empty string, hide the date
// entirely. Only fall back to the default when no value is specified.
let result =
this.config.dateFormatting !== undefined &&
this.config.dateFormatting !== null
? this.config.dateFormatting
: "yyyy-mm-dd";
if (result === "") return "";
// Ersätt både små och stora bokstäver för yyyy, mm, dd
result = result.replace(/yyyy/gi, yyyy);
result = result.replace(/mm/gi, mm);
result = result.replace(/dd/gi, dd);
// Extra stöd för stora bokstäver som kan missas pga regex
// (Om användaren skriver t.ex "DD" istället för "dd")
result = result.replace(/YYYY/g, yyyy);
result = result.replace(/MM/g, mm);
result = result.replace(/DD/g, dd);
return result;
},
buildChartData(type) {
const source = Array.isArray(this.allTasks) && this.allTasks.length ? this.allTasks : this.tasks;
const filteredTasks = fn => source.filter(t => !(t.deleted && !t.done) && fn(t));
let data = { labels: [], datasets: [] };
let options = { scales: { y: { beginAtZero: true } } };
let chartType = "bar";
switch (type) {
case "weekly": {
const today = new Date();
const labels = [];
const counts = [];
for (let i = 3; i >= 0; i--) {
const d = new Date(today);
d.setDate(today.getDate() - i * 7);
labels.push(d.toISOString().split("T")[0]);
const c = filteredTasks(t => {
const td = new Date(t.date);
return t.done && ((today - td) / 86400000) >= i * 7 && ((today - td) / 86400000) < (i + 1) * 7;
}).length;
counts.push(c);
}
data = { labels, datasets: [{ label: "Completed Tasks", data: counts, backgroundColor: "rgba(75,192,192,0.5)" }] };
break;
}
case "weekdays": {
chartType = "pie";
const labels = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
const arr = [0,0,0,0,0,0,0];
filteredTasks(t => true).forEach(t => {
const idx = (new Date(t.date).getDay() + 6) % 7;
arr[idx]++;
});
data = {
labels,
datasets: [{ data: arr, backgroundColor: ["#FF6384","#36A2EB","#FFCE56","#4BC0C0","#9966FF","#FF9F40","#C9CBCF"] }]
};
options = {};
break;
}
case "perPerson": {
const labels = this.people.map(p => p.name);
const counts = this.people.map(p => filteredTasks(t => t.assignedTo === p.id).length);
data = { labels, datasets: [{ label: "Finished Tasks", data: counts, backgroundColor: "rgba(153,102,255,0.5)" }] };
break;
}
case "perPersonFinished": {
const labels = this.people.map(p => p.name);
const counts = this.people.map(p => filteredTasks(t => t.assignedTo === p.id && t.done).length);
data = { labels, datasets: [{ label: BOARD_TITLES.perPersonFinished, data: counts, backgroundColor: "rgba(75,192,192,0.5)" }] };
break;
}
case "perPersonFinishedWeek": {
const now = new Date();
const start = new Date(now);
start.setDate(now.getDate() - ((now.getDay() + 6) % 7));
start.setHours(0, 0, 0, 0);
const end = new Date(start);
end.setDate(start.getDate() + 7);
const labels = this.people.map(p => p.name);
const counts = this.people.map(p =>
filteredTasks(t => {
if (!t.done || t.assignedTo !== p.id) return false;
const d = new Date(t.date);
return d >= start && d < end;
}).length
);
data = { labels, datasets: [{ label: BOARD_TITLES.perPersonFinishedWeek, data: counts, backgroundColor: "rgba(75,192,192,0.5)" }] };
break;
}
case "perPersonUnfinished": {
const labels = this.people.map(p => p.name);
const counts = this.people.map(p => filteredTasks(t => t.assignedTo === p.id && !t.done).length);
data = { labels, datasets: [{ label: BOARD_TITLES.perPersonUnfinished, data: counts, backgroundColor: "rgba(255,99,132,0.5)" }] };
break;
}
case "perPersonUnfinishedWeek": {
const now = new Date();
const start = new Date(now);
start.setDate(now.getDate() - ((now.getDay() + 6) % 7));
start.setHours(0, 0, 0, 0);
const end = new Date(start);
end.setDate(start.getDate() + 7);
const labels = this.people.map(p => p.name);
const counts = this.people.map(p =>
filteredTasks(t => {
if (t.done || t.assignedTo !== p.id) return false;
const d = new Date(t.date);
return d >= start && d < end;
}).length
);
data = { labels, datasets: [{ label: BOARD_TITLES.perPersonUnfinishedWeek, data: counts, backgroundColor: "rgba(255,99,132,0.5)" }] };
break;
}
case "taskmaster": {
const now = new Date();
const labels = this.people.map(p => p.name);
const counts = this.people.map(p => source.filter(t => {
const d = new Date(t.date);
return t.done && d.getMonth() === now.getMonth() && d.getFullYear() === now.getFullYear() && t.assignedTo === p.id;
}).length);
data = { labels, datasets: [{ label: BOARD_TITLES.taskmaster, data: counts, backgroundColor: "rgba(255,159,64,0.5)" }] };
break;
}
case "lazyLegends": {
const labels = this.people.map(p => p.name);
const counts = this.people.map(p => filteredTasks(t => t.assignedTo === p.id && !t.done).length);
data = { labels, datasets: [{ label: BOARD_TITLES.lazyLegends, data: counts, backgroundColor: "rgba(255,99,132,0.5)" }] };
break;
}
case "speedDemons": {
const labels = this.people.map(p => p.name);
const avgDays = this.people.map(p => {
const times = filteredTasks(t => t.assignedTo === p.id && t.done && t.finished && t.assignedDate).map(t => {
const dDone = new Date(t.finished);
const dAssigned = new Date(t.assignedDate);
return (dDone - dAssigned) / (1000*60*60*24);
});
if (times.length === 0) return 0;
return times.reduce((a,b) => a+b, 0) / times.length;
});
data = { labels, datasets: [{ label: BOARD_TITLES.speedDemons, data: avgDays, backgroundColor: "rgba(54,162,235,0.5)" }] };
break;
}
case "weekendWarriors": {
const labels = this.people.map(p => p.name);
const counts = this.people.map(p => filteredTasks(t => {
if (!t.done || t.assignedTo !== p.id) return false;
const d = new Date(t.date);
return d.getDay() === 0 || d.getDay() === 6;
}).length);
data = { labels, datasets: [{ label: BOARD_TITLES.weekendWarriors, data: counts, backgroundColor: "rgba(255,206,86,0.5)" }] };
break;
}
case "slacker9000": {
const labels = this.people.map(p => p.name);
const ages = this.people.map(p => {
const open = filteredTasks(t => t.assignedTo === p.id && !t.done && t.assignedDate);
if (open.length === 0) return 0;
const now = new Date();
return Math.max(...open.map(t => (now - new Date(t.assignedDate)) / (1000*60*60*24)));
});
data = { labels, datasets: [{ label: BOARD_TITLES.slacker9000, data: ages, backgroundColor: "rgba(153,102,255,0.5)" }] };
break;
}
default:
data = { labels: [], datasets: [] };
break;
}
return { chartType, data, options };
},
renderCharts() {
if (!this.config.showAnalyticsOnMirror || typeof Chart === "undefined") return;
const types = this.config.analyticsCards;
const currentIds = [];
types.forEach((type, idx) => {
const id = `chart-${idx}`;
currentIds.push(id);
const canvas = document.getElementById(id);
if (!canvas) return;
const ctx = canvas.getContext("2d");
const { chartType, data, options } = this.buildChartData(type);
const existing = this.chartInstances[id];
if (existing) {
existing.destroy();
}
this.chartInstances[id] = new Chart(ctx, { type: chartType, data, options });
});
// destroy charts that are no longer configured
Object.keys(this.chartInstances).forEach(id => {
if (!currentIds.includes(id)) {
this.chartInstances[id].destroy();
delete this.chartInstances[id];
}
});
},
getRedeemedLabel() {
const lang = (this.config.language || "en").toLowerCase();
const labels = {
en: "redeemed",
sv: "löste in",
es: "canjeó",
fr: "a utilisé",
de: "eingelöst",
it: "ha riscattato",
nl: "verzilverd",
pl: "zrealizował",
zh: "兑换了",
ar: "استبدل"
};
// Match exact or locale-prefixed codes, default to English
const entry = Object.entries(labels).find(([code]) => lang === code || lang.startsWith(`${code}-`));
return entry ? entry[1] : labels.en;
},
resolveVoiceLocale(preferred) {
const fallback = "en-US";
const fromConfig = (this.config.language || "").toLowerCase();
const preferredCode = (preferred || fromConfig || "en").toLowerCase();
const map = {
en: "en-US",
sv: "sv-SE",
es: "es-ES",
fr: "fr-FR",
de: "de-DE",
it: "it-IT",
nl: "nl-NL",
pl: "pl-PL",
zh: "zh-CN",
ar: "ar-AR"
};
return map[preferredCode.split("-")[0]] || preferred || fallback;
},
initVoiceRecognition() {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!SpeechRecognition) {
Log.warn("MMM-Chores: Speech recognition not supported in this browser");
return;
}
const config = this.config.voiceAssistant;
this.voiceRecognition = new SpeechRecognition();
this.voiceRecognition.lang = this.resolveVoiceLocale(config.language);
this.voiceRecognition.continuous = config.continuous || false;
this.voiceRecognition.interimResults = config.interimResults || false;
this.voiceRecognition.maxAlternatives = config.maxAlternatives || 1;
this.voiceRecognition.onstart = () => {
this.isListening = true;
this.updateDom();
};
this.voiceRecognition.onresult = (event) => {
const result = event.results[event.results.length - 1];
if (result.isFinal) {
const transcript = result[0].transcript.trim();
this.lastTranscript = transcript;
this.handleVoiceCommand(transcript);
}
};
this.voiceRecognition.onerror = (event) => {
Log.error("MMM-Chores: Voice recognition error", event.error);
this.isListening = false;
this.updateDom();
};
this.voiceRecognition.onend = () => {
this.isListening = false;
this.updateDom();
};
},
startListening() {
if (!this.voiceRecognition) {
this.initVoiceRecognition();
}
if (this.voiceRecognition && !this.isListening) {
try {
this.voiceRecognition.start();
} catch (err) {
Log.error("MMM-Chores: Failed to start voice recognition", err);
}
}
},
stopListening() {
if (this.voiceRecognition && this.isListening) {
this.voiceRecognition.stop();
}
},
handleVoiceCommand(transcript) {
Log.log("MMM-Chores: Voice command received:", transcript);
this.sendSocketNotification("VOICE_COMMAND", {
transcript,
people: this.people,
tasks: this.tasks
});
this.updateDom();
},
speakResponse(text) {
if (!this.config.voiceAssistant || !this.config.voiceAssistant.ttsEnabled) {
return;
}
if ('speechSynthesis' in window) {
// Cancel any ongoing speech to prevent overlap
window.speechSynthesis.cancel();
// Add a pause before speaking to prevent the first word from being cut off
const cfg = this.config.ttsAudio || {};
const pauseMs = Number.isFinite(cfg.pauseMs) ? cfg.pauseMs : 600;
const volume = Number.isFinite(cfg.volume) ? cfg.volume : 0.7;
const utterance = new SpeechSynthesisUtterance(text);
const config = this.config.voiceAssistant;
if (config.ttsVoice && config.ttsVoice !== 'default') {
const voices = window.speechSynthesis.getVoices();
const voice = voices.find(v => v.name === config.ttsVoice);
if (voice) utterance.voice = voice;
}
utterance.rate = config.ttsRate || 1.0;
utterance.pitch = config.ttsPitch || 1.0;
utterance.lang = this.resolveVoiceLocale(config.language);
utterance.volume = Math.min(Math.max(volume, 0), 1);
// Temporarily stop recognition to prevent feedback/ducking
const wasListening = this.isListening;
if (this.voiceRecognition && wasListening) {
this.voiceRecognition.abort();
this.isListening = false;
this.updateDom();
}
utterance.onend = () => {
// No auto-restart of listening. User must press mic button.
};
// Small delay to allow mic to fully close and audio context to settle
setTimeout(() => {
window.speechSynthesis.speak(utterance);
}, pauseMs);
}
},
getDom() {
const wrapper = document.createElement("div");
// Voice Assistant UI
if (this.config.voiceAssistant && this.config.voiceAssistant.enabled) {
const voiceControls = document.createElement("div");
voiceControls.className = "voice-controls";
const micButton = document.createElement("button");
micButton.className = `voice-mic-button ${this.isListening ? "listening" : ""}`;
micButton.innerHTML = this.isListening ? "🎙️ Listening..." : "🎤 Voice";
micButton.addEventListener("click", () => {
if (this.isListening) {
this.stopListening();
} else {
this.startListening();
}
});
voiceControls.appendChild(micButton);
if (this.config.voiceAssistant.showTranscription && this.lastTranscript) {
const transcript = document.createElement("div");
transcript.className = "voice-transcript xsmall dimmed";
transcript.textContent = `"${this.lastTranscript}"`;
voiceControls.appendChild(transcript);
}
wrapper.appendChild(voiceControls);
}
// Remove the large header showing the global level. Levels are displayed
// next to each person's name instead.
if (this.titleChangeMessage) {
const note = document.createElement("div");
note.className = "small bright";
note.innerHTML = this.titleChangeMessage;
wrapper.appendChild(note);
}
const showRedeemed = this.config.usePointSystem && this.config.showRedeemedRewards !== false;
const pendingRedemptions = showRedeemed
? (this.redemptions || []).filter(r => !r.used).sort((a, b) => new Date(b.redeemed) - new Date(a.redeemed))
: [];
// Filter out all deleted tasks completely from the mirror
const visible = this.tasks
.filter(t => !t.deleted && this.shouldShowTask(t))
.sort((a, b) => {
if (a.done && !b.done) return 1;
if (!a.done && b.done) return -1;
const da = new Date(a.date);
const db = new Date(b.date);
if (da < db) return -1;
if (da > db) return 1;
return (a.order || 0) - (b.order || 0);
});
// Show pending redemptions above tasks when enabled (no header, no date)
if (pendingRedemptions.length) {
const redemptionsWrap = document.createElement("div");
redemptionsWrap.className = "redemptions-block";
const list = document.createElement("ul");
list.className = "normal";
const redeemedLabel = this.getRedeemedLabel();
pendingRedemptions.forEach(red => {
const li = document.createElement("li");
li.className = `${this.config.textMirrorSize}`;
const nameEl = document.createElement("strong");
nameEl.textContent = red.personName || "";
const labelEl = document.createElement("span");
labelEl.className = "dimmed";
labelEl.textContent = redeemedLabel;
const rewardEl = document.createElement("strong");
rewardEl.textContent = red.rewardName || "";
// explicit text nodes to enforce spacing between parts
const space = document.createTextNode("\u00a0");
li.append(
nameEl,
space.cloneNode(),
labelEl,
space.cloneNode(),
rewardEl
);
list.appendChild(li);
});
redemptionsWrap.appendChild(list);
wrapper.appendChild(redemptionsWrap);
}
if (pendingRedemptions.length && visible.length) {
const divider = document.createElement("hr");
divider.className = "redemptions-divider";
divider.style.margin = "8px 0";
wrapper.appendChild(divider);
}
if (visible.length === 0) {
const emptyEl = document.createElement("div");
emptyEl.className = `${this.config.textMirrorSize} dimmed`;
emptyEl.innerHTML = pendingRedemptions.length ? "" : "No tasks to show 🎉";
if (!pendingRedemptions.length) {
wrapper.appendChild(emptyEl);
}
return wrapper;
}
const ul = document.createElement("ul");
ul.className = "normal";
visible.forEach(task => {
const li = document.createElement("li");
li.className = `${this.config.textMirrorSize}${task.done ? " task-done" : ""}`;
const cb = document.createElement("input");
cb.type = "checkbox";
cb.checked = task.done;
cb.style.marginRight = "8px";
cb.addEventListener("change", () => {
li.classList.add("moving");
setTimeout(() => this.toggleDone(task, cb.checked), 200);
});
li.appendChild(cb);
const dateText = this.formatDate(task.date);
const text = document.createTextNode(`${task.name} ${dateText}`);
li.appendChild(text);
if (task.assignedTo) {
const p = this.getPerson(task.assignedTo);
const assignedEl = document.createElement("span");
assignedEl.className = "xsmall dimmed";
assignedEl.style.marginLeft = "6px";
let html = ` — ${p ? p.name : ""}`;
// Show coins if the coin system is active and the mirror toggle allows it; otherwise show level info
if (this.config.usePointSystem) {
if (this.config.showCoinsOnMirror !== false && p) {
const coins = p.points || 0;
html += ` <span class="coin-badge">🪙${coins}</span>`;
}
} else {
const lvlEnabled = !(
this.config.leveling && this.config.leveling.enabled === false
);
const showLevel = this.config.showLevelOnMirror !== false;
if (lvlEnabled && showLevel && p && p.level) {
html += ` <span class="lvl-badge">lvl${p.level}</span>`;
}
}
assignedEl.innerHTML = html;
li.appendChild(assignedEl);
}
ul.appendChild(li);
});
wrapper.appendChild(ul);
if (this.config.showAnalyticsOnMirror && this.config.analyticsCards.length) {
const charts = document.createElement("div");
charts.className = "analytics-wrapper";
this.config.analyticsCards.forEach((type, idx) => {
const card = document.createElement("div");
card.className = "analytics-card";
const title = document.createElement("div");
title.className = "small bright";
title.innerHTML = BOARD_TITLES[type] || type;
const canvas = document.createElement("canvas");
const id = `chart-${idx}`;
canvas.id = id;
canvas.className = "analytics-chart";
card.appendChild(title);
card.appendChild(canvas);
charts.appendChild(card);
});
wrapper.appendChild(charts);
setTimeout(() => this.renderCharts(), 0);
}
return wrapper;
}
});