-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTastyTiles.html
More file actions
780 lines (673 loc) · 23.7 KB
/
Copy pathTastyTiles.html
File metadata and controls
780 lines (673 loc) · 23.7 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rolling Weekly Menu</title>
<script type="application/json" id="homeglow-manifest">
{
"manifestVersion": 1,
"id": "rolling-weekly-menu",
"name": "Rolling Weekly Menu",
"description": "A rolling weekly dinner menu. Fill in what is planned for each day in edit mode, and reset the week when it is time to plan again. The menu is saved in shared household plugin storage, so every display in the house shows the same one.",
"apiVersion": "v1",
"storage": true,
"settings": [
{
"key": "repeatWeekly",
"type": "boolean",
"scope": "household",
"default": false,
"label": "Repeat the week instead of clearing each day"
}
],
"hideableControls": [
{ "id": "editMenu", "label": "Edit the menu (add and remove items)" },
{ "id": "resetWeek", "label": "Clear the whole week" }
]
}
</script>
<link rel="stylesheet" href="/index.css">
<style>
* {
background: transparent !important;
background-color: transparent !important;
background-image: none !important;
}
body {
background: transparent !important;
font-family: 'Inter', sans-serif;
margin: 0;
padding: 0.75rem;
box-sizing: border-box;
font-size: 0.85rem;
color: #333;
}
[data-theme="dark"] body {
color: #a6a6d1;
background: transparent !important;
}
.widget-container {
background: transparent !important;
border: none !important;
box-shadow: none !important;
backdrop-filter: none !important;
border-radius: 12px;
padding: 0.5rem;
width: 100%;
max-height: calc(100vh - 1.5rem);
overflow-y: auto;
}
.widget-title {
font-size: 1.2rem;
font-weight: 700;
margin: 0 0 1rem 0;
color: inherit;
text-align: center;
}
.menu-controls {
display: flex;
justify-content: center;
gap: 0.5rem;
margin-bottom: 1rem;
}
.platform-warning {
margin: 0 0 0.75rem 0;
padding: 0.5rem;
border-radius: 8px;
border: 1px solid rgba(255, 107, 107, 0.35);
background: rgba(255, 107, 107, 0.1) !important;
color: inherit;
font-size: 0.75rem;
line-height: 1.4;
display: none;
}
.custom-button {
background: linear-gradient(45deg, #00ddeb, #ff6b6b) !important;
color: #333 !important;
border: none;
border-radius: 8px;
padding: 6px 12px;
cursor: pointer;
font-size: 0.75rem;
font-weight: 600;
transition: all 0.3s ease;
}
[data-theme="dark"] .custom-button {
background: linear-gradient(45deg, #2e2767, #620808) !important;
color: #a6a6d1 !important;
}
.custom-button:hover {
filter: brightness(1.1);
transform: translateY(-1px);
}
.day-container {
margin-bottom: 0.75rem;
border-radius: 8px;
padding: 0.5rem;
transition: all 0.3s ease;
}
.day-container.current-day {
border: 2px solid #00ddeb;
background: rgba(0, 221, 235, 0.1) !important;
}
[data-theme="dark"] .day-container.current-day {
border-color: #00ddeb;
background: rgba(0, 221, 235, 0.15) !important;
}
.day-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.5rem;
}
.day-name {
font-weight: 600;
font-size: 0.9rem;
color: inherit;
}
.day-date {
font-size: 0.75rem;
opacity: 0.7;
color: inherit;
}
.menu-items {
min-height: 2rem;
}
.menu-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.25rem 0;
border-bottom: 1px solid rgba(128, 128, 128, 0.2);
}
.menu-item:last-child {
border-bottom: none;
}
.menu-item-text {
flex: 1;
color: inherit;
font-size: 0.8rem;
}
.menu-item-actions {
display: flex;
gap: 0.25rem;
}
.small-button {
background: none !important;
border: 1px solid rgba(128, 128, 128, 0.3);
border-radius: 4px;
padding: 2px 6px;
cursor: pointer;
font-size: 0.7rem;
color: inherit;
transition: all 0.2s ease;
}
.small-button:hover {
border-color: #00ddeb;
background: rgba(0, 221, 235, 0.1) !important;
}
[data-theme="dark"] .small-button:hover {
border-color: #00ddeb;
background: rgba(0, 221, 235, 0.15) !important;
}
.add-item-container {
margin-top: 0.5rem;
display: none;
}
.add-item-container.active {
display: block;
}
.add-item-input {
width: 100%;
padding: 0.5rem;
border: 1px solid rgba(128, 128, 128, 0.3);
border-radius: 6px;
background: transparent !important;
color: inherit;
font-size: 0.8rem;
margin-bottom: 0.5rem;
}
.add-item-input:focus {
outline: none;
border-color: #00ddeb;
}
.add-item-actions {
display: flex;
gap: 0.5rem;
justify-content: flex-end;
}
.empty-day {
color: rgba(128, 128, 128, 0.6);
font-style: italic;
font-size: 0.8rem;
text-align: center;
padding: 1rem 0;
}
</style>
</head>
<body>
<div class="widget-container">
<h1 class="widget-title">🍽️ Rolling Weekly Menu</h1>
<div class="menu-controls">
<button class="custom-button" id="toggle-edit-btn" onclick="toggleEditMode()">
<span id="edit-mode-text">Edit Mode</span>
</button>
<button class="custom-button" id="reset-week-btn" onclick="resetWeek()">Reset Week</button>
</div>
<div id="platform-warning" class="platform-warning"></div>
<div id="menu-days"></div>
</div>
<script src="/plugin-sdk/v1.js"></script>
<script>
// Menu data is persisted through manifest-declared plugin storage.
var MANIFEST_PLUGIN_ID = readManifestPluginId();
var SDK = window.HomeGlow && window.HomeGlow.pluginId ? window.HomeGlow : null;
var STORAGE = createStorageClient();
var SETTINGS = createSettingsClient();
var MENU_STORAGE_KEY = 'recipes';
var PLATFORM_AVAILABLE = Boolean(STORAGE);
// Control limits: the dashboard names this plugin's hidden controls on the
// iframe URL, already unprefixed. No param means hide nothing, which is what
// an older dashboard and a direct load of this page both produce.
var HIDDEN_CONTROLS = (new URLSearchParams(window.location.search).get('hide') || '')
.split(',').filter(Boolean);
var HIDE_EDIT_MENU = HIDDEN_CONTROLS.indexOf('editMenu') !== -1;
var HIDE_RESET_WEEK = HIDDEN_CONTROLS.indexOf('resetWeek') !== -1;
// At parse time, not on DOMContentLoaded: this script sits after the buttons
// in the document, so a hidden one can go before it is ever painted.
applyControlLimits();
let editMode = false;
let menuData = {};
// False until the stored menu is actually in hand. Gates every write --
// see saveMenuData(). Without it, a read failure leaves an empty grid that
// the next edit writes back over the real week.
let menuLoaded = false;
let currentAddingDay = null;
// Declared in the manifest, so it is set in Admin > Widgets rather than from
// the widget. Read once per load, which is also the only time it is used:
// checkAndCycleDays() runs on the first load of a new day and not again.
let repeatWeekly = false;
// Day names for the rolling cycle
const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
document.addEventListener('DOMContentLoaded', () => {
// Handle theme
const params = new URLSearchParams(window.location.search);
const theme = params.get('theme');
if (theme === 'dark' || theme === 'light') {
document.documentElement.setAttribute('data-theme', theme);
}
renderPlatformState();
(async () => {
await loadMenuData();
repeatWeekly = await readRepeatWeekly();
await checkAndCycleDays();
renderMenu();
})();
});
function getCurrentDayIndex() {
return new Date().getDay(); // 0 = Sunday, 1 = Monday, etc.
}
function getDateForDayOffset(offset) {
const today = new Date();
const targetDate = new Date(today);
targetDate.setDate(today.getDate() + offset);
return targetDate;
}
function formatDate(date) {
return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}
function getRollingDayOrder() {
const currentDayIndex = getCurrentDayIndex();
const rollingOrder = [];
// Start with today and go forward 7 days
for (let i = 0; i < 7; i++) {
const dayIndex = (currentDayIndex + i) % 7;
const date = getDateForDayOffset(i);
rollingOrder.push({
name: dayNames[dayIndex],
index: dayIndex,
date: date,
isToday: i === 0
});
}
return rollingOrder;
}
function readManifestPluginId() {
try {
var manifestNode = document.getElementById('homeglow-manifest');
if (!manifestNode) return null;
var manifest = JSON.parse(manifestNode.textContent || '{}');
return manifest && typeof manifest.id === 'string' && manifest.id.length > 0
? manifest.id
: null;
} catch (err) {
console.error(err);
return null;
}
}
function createStorageClient() {
if (SDK && SDK.storage) return SDK.storage;
if (!MANIFEST_PLUGIN_ID) return null;
var encodedPluginId = encodeURIComponent(MANIFEST_PLUGIN_ID);
var basePath = '/api/plugin/v1/storage/' + encodedPluginId;
function request(method, suffix, value) {
var options = { method: method, headers: {} };
if (value !== undefined) {
options.headers['Content-Type'] = 'application/json';
options.body = JSON.stringify(value);
}
return fetch(basePath + suffix, options).then(function (response) {
return response.text().then(function (text) {
var data = null;
try {
data = text ? JSON.parse(text) : null;
} catch (e) {
data = text;
}
if (!response.ok) {
var error = new Error((data && data.error) || ('HTTP ' + response.status));
error.status = response.status;
throw error;
}
return data;
});
});
}
return {
get: function (key) {
return request('GET', '/' + encodeURIComponent(key)).catch(function (error) {
if (error.status === 404) return null;
throw error;
});
},
set: function (key, value) {
return request('PUT', '/' + encodeURIComponent(key), value);
}
};
}
// Read-only: the values are written from Admin > Widgets, which renders a
// control for every setting the manifest declares. Mirrors the storage
// client's SDK-first, direct-fetch-fallback shape.
function createSettingsClient() {
if (SDK && SDK.settings) return SDK.settings;
if (!MANIFEST_PLUGIN_ID) return null;
var path = '/api/plugin/v1/settings/' + encodeURIComponent(MANIFEST_PLUGIN_ID);
return {
get: function () {
return fetch(path).then(function (response) {
if (!response.ok) throw new Error('HTTP ' + response.status);
return response.json();
});
}
};
}
/**
* Off (the manifest default) keeps the original behavior: a day is cleared
* as it passes. On makes the week a standing rotation, so a household that
* eats on a fixed cycle does not retype the same menu every week.
*
* Any failure reads as off. Clearing is what the plugin has always done, so
* an unreachable settings route must not silently change the behavior of
* the menu -- and only a literal true turns it on.
*/
async function readRepeatWeekly() {
if (!SETTINGS) return false;
try {
const values = await SETTINGS.get();
return Boolean(values) && values.repeatWeekly === true;
} catch (err) {
console.error(err);
return false;
}
}
// Menus written before this plugin moved to plugin storage live in the
// household settings table under this key. Read once, never written again.
const LEGACY_SETTINGS_KEY = 'plugin_tastytiles_recipes';
/**
* One-time migration. Without it, everyone who used the previous version
* opens an empty week: the menu is still in settings, but nothing reads it.
*
* The old key is deliberately NOT deleted. It costs nothing to leave and it
* keeps a recoverable copy of the menu.
*/
async function readLegacyMenu() {
try {
const response = await fetch('/api/settings', { credentials: 'include' });
if (!response.ok) return null;
const settings = await response.json();
const stored = settings && settings[LEGACY_SETTINGS_KEY];
if (!stored) return null;
// GET /api/settings deserializes any value starting with { or [, so this
// arrives as an object. It was written as a string, so accept both.
const parsed = typeof stored === 'string' ? JSON.parse(stored) : stored;
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
return parsed;
} catch (err) {
console.error(err);
return null;
}
}
async function loadMenuData() {
try {
if (PLATFORM_AVAILABLE) {
// Plugin storage is shared household-wide and supports JSON payloads.
const storedDoc = await STORAGE.get(MENU_STORAGE_KEY);
if (storedDoc && typeof storedDoc === 'object' && !Array.isArray(storedDoc)) {
menuData = normalizeMenuData(storedDoc);
menuLoaded = true;
return;
}
// A present-but-unusable value is a failed read, not an empty store.
// Only a genuinely absent key (404 -> null) means "nothing saved yet".
if (storedDoc !== null && storedDoc !== undefined) {
throw new Error('Unexpected plugin storage payload');
}
const legacy = await readLegacyMenu();
if (legacy) {
menuData = normalizeMenuData(legacy);
menuLoaded = true;
await STORAGE.set(MENU_STORAGE_KEY, menuData);
return;
}
// Nothing stored anywhere: start empty, but do not write. The first
// real edit persists it, so a page load can never clear a menu.
initializeEmptyMenu();
menuLoaded = true;
return;
}
// No plugin identity namespace: keep memory-only empty state and warn.
initializeEmptyMenu();
menuLoaded = false;
} catch (err) {
console.error(err);
initializeEmptyMenu();
menuLoaded = false;
}
}
/**
* Honoring the display's control limits is this widget's job -- the host
* cannot reach into the iframe. A hidden control is removed rather than
* disabled: a display that may not manage the menu should not show the
* button at all.
*/
function applyControlLimits() {
// The controls row holds nothing but these two buttons, so hiding both
// would leave an empty flex box carrying its own bottom margin. Dropping
// the row takes the buttons with it.
if (HIDE_EDIT_MENU && HIDE_RESET_WEEK) {
const row = document.querySelector('.menu-controls');
if (row) row.remove();
return;
}
if (HIDE_EDIT_MENU) {
const editBtn = document.getElementById('toggle-edit-btn');
if (editBtn) editBtn.remove();
}
if (HIDE_RESET_WEEK) {
const resetBtn = document.getElementById('reset-week-btn');
if (resetBtn) resetBtn.remove();
}
}
function setControlEnabled(button, enabled) {
button.disabled = !enabled;
button.style.opacity = enabled ? '1' : '0.6';
button.style.cursor = enabled ? 'pointer' : 'not-allowed';
}
function renderPlatformState() {
const warning = document.getElementById('platform-warning');
// Either button may be gone: applyControlLimits() has already run, and a
// control this display hides is not in the DOM to be disabled.
const buttons = [
document.getElementById('toggle-edit-btn'),
document.getElementById('reset-week-btn'),
].filter(Boolean);
if (!PLATFORM_AVAILABLE) {
warning.textContent = 'Shared menu storage is unavailable because this widget could not resolve a plugin platform namespace. Verify this widget is installed through Admin > Widgets.';
warning.style.display = 'block';
buttons.forEach(button => setControlEnabled(button, false));
return;
}
warning.style.display = 'none';
buttons.forEach(button => setControlEnabled(button, true));
}
function normalizeMenuData(candidate) {
const normalized = {};
dayNames.forEach((day, index) => {
const rawItems = candidate && candidate[index];
normalized[index] = Array.isArray(rawItems)
? rawItems.filter(item => typeof item === 'string' && item.trim().length > 0)
: [];
});
if (candidate && typeof candidate.lastCycleDate === 'string') {
normalized.lastCycleDate = candidate.lastCycleDate;
}
return normalized;
}
async function saveMenuData() {
// Every save rewrites the whole menu. If the load failed we are holding an
// empty grid rather than the stored week, so writing it would replace real
// data with nothing.
if (!menuLoaded) {
console.error('TastyTiles: menu was never loaded; refusing to overwrite stored data.');
return;
}
try {
if (PLATFORM_AVAILABLE) {
await STORAGE.set(MENU_STORAGE_KEY, normalizeMenuData(menuData));
}
} catch (err) {
console.error(err);
}
}
function initializeEmptyMenu() {
menuData = {};
dayNames.forEach((day, index) => {
menuData[index] = [];
});
}
async function checkAndCycleDays() {
const today = new Date().toDateString();
if (!menuData.lastCycleDate) {
menuData.lastCycleDate = today;
await saveMenuData();
return;
}
if (menuData.lastCycleDate !== today) {
await cycleDays();
menuData.lastCycleDate = today;
await saveMenuData();
}
}
function cycleDays() {
// A standing rotation consumes nothing. The caller still stamps
// lastCycleDate, which is what stops this re-running later today.
if (repeatWeekly) return;
// Get yesterday's day index
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const yesterdayIndex = yesterday.getDay();
// Clear yesterday's menu items (they've been "consumed")
if (menuData[yesterdayIndex]) {
menuData[yesterdayIndex] = [];
saveMenuData();
}
}
function renderMenu() {
const container = document.getElementById('menu-days');
const rollingDays = getRollingDayOrder();
container.innerHTML = '';
rollingDays.forEach((day, position) => {
const dayContainer = document.createElement('div');
dayContainer.className = `day-container ${day.isToday ? 'current-day' : ''}`;
const dayItems = menuData[day.index] || [];
dayContainer.innerHTML = `
<div class="day-header">
<span class="day-name">${day.name}</span>
<span class="day-date">${formatDate(day.date)}</span>
</div>
<div class="menu-items" id="items-${day.index}">
${dayItems.length === 0 ?
'<div class="empty-day">No menu items planned</div>' :
dayItems.map((item, itemIndex) => `
<div class="menu-item">
<span class="menu-item-text">${item}</span>
${editMode ? `
<div class="menu-item-actions">
<button class="small-button" onclick="removeItem(${day.index}, ${itemIndex})">×</button>
</div>
` : ''}
</div>
`).join('')
}
</div>
${editMode ? `
<div class="add-item-container" id="add-container-${day.index}">
<input type="text" class="add-item-input" id="add-input-${day.index}"
placeholder="Add menu item..."
onkeypress="handleAddKeyPress(event, ${day.index})">
<div class="add-item-actions">
<button class="small-button" onclick="cancelAdd(${day.index})">Cancel</button>
<button class="small-button" onclick="addItem(${day.index})">Add</button>
</div>
</div>
<button class="custom-button" onclick="showAddItem(${day.index})"
id="add-btn-${day.index}" style="margin-top: 0.5rem; font-size: 0.7rem; padding: 4px 8px;">
+ Add Item
</button>
` : ''}
`;
container.appendChild(dayContainer);
});
}
function toggleEditMode() {
// The button that calls this is removed when editing is hidden, so this is
// a guard against a stray call reaching a label that no longer exists --
// and what keeps editMode false, which is what hides the per-day add and
// remove buttons inside renderMenu().
if (HIDE_EDIT_MENU) return;
editMode = !editMode;
document.getElementById('edit-mode-text').textContent = editMode ? 'View Mode' : 'Edit Mode';
renderMenu();
}
function showAddItem(dayIndex) {
// Hide all other add containers
document.querySelectorAll('.add-item-container').forEach(container => {
container.classList.remove('active');
});
// Show this day's add container
const container = document.getElementById(`add-container-${dayIndex}`);
const button = document.getElementById(`add-btn-${dayIndex}`);
const input = document.getElementById(`add-input-${dayIndex}`);
container.classList.add('active');
button.style.display = 'none';
input.focus();
currentAddingDay = dayIndex;
}
function cancelAdd(dayIndex) {
const container = document.getElementById(`add-container-${dayIndex}`);
const button = document.getElementById(`add-btn-${dayIndex}`);
const input = document.getElementById(`add-input-${dayIndex}`);
container.classList.remove('active');
button.style.display = 'block';
input.value = '';
currentAddingDay = null;
}
function addItem(dayIndex) {
const input = document.getElementById(`add-input-${dayIndex}`);
const text = input.value.trim();
if (text) {
if (!menuData[dayIndex]) {
menuData[dayIndex] = [];
}
menuData[dayIndex].push(text);
saveMenuData();
renderMenu();
}
}
function removeItem(dayIndex, itemIndex) {
if (menuData[dayIndex]) {
menuData[dayIndex].splice(itemIndex, 1);
saveMenuData();
renderMenu();
}
}
function handleAddKeyPress(event, dayIndex) {
if (event.key === 'Enter') {
addItem(dayIndex);
} else if (event.key === 'Escape') {
cancelAdd(dayIndex);
}
}
function resetWeek() {
if (confirm('Are you sure you want to clear all menu items for the week?')) {
menuData = {};
dayNames.forEach((day, index) => {
menuData[index] = [];
});
saveMenuData();
renderMenu();
}
}
</script>
</body>
</html>