Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1263 lines (1104 loc) · 40.1 KB
/
Copy pathapp.js
File metadata and controls
1263 lines (1104 loc) · 40.1 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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
parseIngredient,
createIngredientEntry,
mergeIngredientEntry,
formatIngredientSummary,
groupShoppingItems,
scaleIngredientText,
} from "./ingredients.js";
import { extractRecipeFromHtml } from "./recipe-parser.js";
import { encodeSharedPayload, decodeSharedPayload } from "./share.js";
const STORAGE_KEYS = {
recipes: "tableset-recipes",
planner: "tableset-planner",
selectedRecipeId: "tableset-selected-recipe-id",
shoppingOverrides: "tableset-shopping-overrides",
desiredServings: "tableset-desired-servings",
household: "tableset-household",
};
const WEEK_DAYS = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
];
// crypto.randomUUID() is only defined in secure contexts (HTTPS or
// http://localhost), so plain-HTTP LAN/hosted access needs a fallback.
function generateId() {
if (window.crypto?.randomUUID) {
return crypto.randomUUID();
}
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (char) => {
const random = (Math.random() * 16) | 0;
const value = char === "x" ? random : (random & 0x3) | 0x8;
return value.toString(16);
});
}
const demoRecipes = [
{
id: generateId(),
title: "One-Pan Tomato Basil Gnocchi",
sourceUrl: "https://demo.local/gnocchi",
description: "A quick weeknight pasta-style dinner with soft gnocchi and tomato sauce.",
servings: 4,
ingredients: [
"500g shelf-stable gnocchi",
"28g olive oil",
"3 garlic cloves, minced",
"400g chopped tomatoes",
"120ml vegetable stock",
"80g baby spinach",
"15g basil leaves",
"60g grated parmesan",
],
instructions: [
"Warm the olive oil in a large saute pan and cook the garlic for 30 seconds.",
"Add chopped tomatoes, stock, and gnocchi, then simmer until the gnocchi is tender.",
"Stir in spinach and basil until wilted, then finish with parmesan.",
],
method:
"Use one large pan, add the wet ingredients first, then simmer the gnocchi directly in the sauce so the starch thickens it naturally.",
image: "",
importedAt: new Date().toISOString(),
},
{
id: generateId(),
title: "Coconut Chickpea Curry",
sourceUrl: "https://demo.local/chickpea-curry",
description: "Comforting curry with pantry ingredients and a bright finish.",
servings: 4,
ingredients: [
"1 tbsp coconut oil",
"1 onion, diced",
"2 garlic cloves, minced",
"1 tbsp grated ginger",
"2 tbsp curry paste",
"2 x 400g chickpeas, drained",
"400ml coconut milk",
"200g chopped tomatoes",
"1 lime",
"Fresh coriander",
],
instructions: [
"Cook the onion in coconut oil until soft, then add garlic, ginger, and curry paste.",
"Add chickpeas, coconut milk, and tomatoes; simmer until thickened.",
"Finish with lime juice and coriander before serving.",
],
method:
"Build the flavor base first, then reduce the sauce slowly so it clings to the chickpeas.",
image: "",
importedAt: new Date().toISOString(),
},
];
const elements = {
appShell: document.querySelector("#app-shell"),
authPanel: document.querySelector("#auth-panel"),
authForm: document.querySelector("#auth-form"),
authEmail: document.querySelector("#auth-email"),
authPassword: document.querySelector("#auth-password"),
authStatus: document.querySelector("#auth-status"),
authSubmit: document.querySelector("#auth-submit"),
authHeading: document.querySelector("#auth-heading"),
authToggleMode: document.querySelector("#auth-toggle-mode"),
userBar: document.querySelector("#user-bar"),
userEmail: document.querySelector("#user-email"),
logoutButton: document.querySelector("#logout-button"),
importForm: document.querySelector("#import-form"),
recipeUrl: document.querySelector("#recipe-url"),
recipeHtml: document.querySelector("#recipe-html"),
importStatus: document.querySelector("#import-status"),
shareStatus: document.querySelector("#share-status"),
loadDemoButton: document.querySelector("#load-demo-button"),
shareBoardButton: document.querySelector("#share-board-button"),
recipeSearch: document.querySelector("#recipe-search"),
householdAdults: document.querySelector("#household-adults"),
householdChildren: document.querySelector("#household-children"),
householdChildrenShare: document.querySelector("#household-children-share"),
householdTotal: document.querySelector("#household-total"),
recipeLibrary: document.querySelector("#recipe-library"),
recipeDetail: document.querySelector("#recipe-detail"),
weeklyMenu: document.querySelector("#weekly-menu"),
shoppingList: document.querySelector("#shopping-list"),
shoppingTotal: document.querySelector("#shopping-total"),
recipeCount: document.querySelector("#recipe-count"),
plannedCount: document.querySelector("#planned-count"),
shoppingCount: document.querySelector("#shopping-count"),
recipeCardTemplate: document.querySelector("#recipe-card-template"),
shoppingItemTemplate: document.querySelector("#shopping-item-template"),
};
const IS_HOSTED_APP = window.location.protocol !== "file:";
let state = {
user: null,
recipes: IS_HOSTED_APP ? [] : readJson(STORAGE_KEYS.recipes, []),
planner: IS_HOSTED_APP
? WEEK_DAYS.reduce((days, day) => ({ ...days, [day]: "" }), {})
: readJson(
STORAGE_KEYS.planner,
WEEK_DAYS.reduce((days, day) => ({ ...days, [day]: "" }), {})
),
selectedRecipeId: IS_HOSTED_APP ? "" : localStorage.getItem(STORAGE_KEYS.selectedRecipeId) || "",
editingRecipeId: null,
desiredServingsByRecipe: readJson(STORAGE_KEYS.desiredServings, {}),
household: readJson(STORAGE_KEYS.household, { adults: 0, children: 0, childrenShare: false }),
shoppingOverrides: readJson(STORAGE_KEYS.shoppingOverrides, { signature: "", removed: {}, prices: {} }),
};
// The items currently shown in the shopping list, kept around so a price
// edit can recompute the total without re-rendering (and losing focus on)
// every input on the list.
let currentShoppingItems = [];
let authMode = "login";
let recipeSearchTerm = "";
initializeApp();
async function initializeApp() {
bindEvents();
if (IS_HOSTED_APP) {
const user = await fetchCurrentUser();
if (!user) {
showAuth();
return;
}
state.user = user;
showApp();
await hydrateRemoteState();
} else {
await hydrateSharedState();
}
finishInitialRender();
}
function finishInitialRender() {
if (!Object.keys(state.planner).length) {
state.planner = WEEK_DAYS.reduce((days, day) => ({ ...days, [day]: "" }), {});
}
if (
state.recipes.length &&
!state.recipes.some((recipe) => recipe.id === state.selectedRecipeId)
) {
state.selectedRecipeId = state.recipes[0].id;
}
render();
}
function bindEvents() {
elements.importForm.addEventListener("submit", handleImportSubmit);
elements.loadDemoButton.addEventListener("click", handleLoadDemoRecipes);
elements.shareBoardButton.addEventListener("click", handleShareBoard);
elements.authForm.addEventListener("submit", handleAuthSubmit);
elements.authToggleMode.addEventListener("click", handleAuthToggleMode);
elements.logoutButton.addEventListener("click", handleLogout);
elements.recipeSearch.addEventListener("input", (event) => {
recipeSearchTerm = event.target.value.trim().toLowerCase();
renderRecipeLibrary();
});
elements.householdAdults.addEventListener("change", handleHouseholdChange);
elements.householdChildren.addEventListener("change", handleHouseholdChange);
elements.householdChildrenShare.addEventListener("change", handleHouseholdChange);
}
function showApp() {
elements.appShell.classList.remove("hidden");
elements.authPanel.classList.add("hidden");
elements.userBar.classList.remove("hidden");
elements.userEmail.textContent = state.user?.email || "";
}
function showAuth() {
elements.appShell.classList.add("hidden");
elements.authPanel.classList.remove("hidden");
elements.userBar.classList.add("hidden");
}
async function fetchCurrentUser() {
try {
const response = await fetch("/api/auth/me", { credentials: "same-origin" });
const payload = await response.json().catch(() => ({}));
return payload.user || null;
} catch (error) {
return null;
}
}
async function handleAuthSubmit(event) {
event.preventDefault();
const email = elements.authEmail.value.trim();
const password = elements.authPassword.value;
const endpoint = authMode === "register" ? "/api/auth/register" : "/api/auth/login";
setAuthStatus(authMode === "register" ? "Creating your account..." : "Signing in...");
try {
const response = await fetch(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "same-origin",
body: JSON.stringify({ email, password }),
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(payload.error || "Could not sign in.");
}
state.user = payload.user;
elements.authForm.reset();
setAuthStatus("");
showApp();
await hydrateRemoteState();
finishInitialRender();
} catch (error) {
setAuthStatus(error.message || "Could not sign in.");
}
}
function handleAuthToggleMode() {
authMode = authMode === "login" ? "register" : "login";
const isRegister = authMode === "register";
elements.authHeading.textContent = isRegister
? "Create your meal board account"
: "Sign in to your meal board";
elements.authSubmit.textContent = isRegister ? "Create account" : "Sign in";
elements.authToggleMode.textContent = isRegister
? "Already have an account? Sign in"
: "Need an account? Register";
elements.authPassword.setAttribute("autocomplete", isRegister ? "new-password" : "current-password");
setAuthStatus("");
}
async function handleLogout() {
try {
await fetch("/api/auth/logout", { method: "POST", credentials: "same-origin" });
} catch (error) {
// Fall through and clear local state even if the network call failed.
}
state.user = null;
state.recipes = [];
state.planner = WEEK_DAYS.reduce((days, day) => ({ ...days, [day]: "" }), {});
state.selectedRecipeId = "";
state.editingRecipeId = null;
state.desiredServingsByRecipe = {};
state.shoppingOverrides = { signature: "", removed: {}, prices: {} };
persistDesiredServings();
persistShoppingOverrides();
showAuth();
}
async function hostedFetch(path, options = {}) {
const response = await fetch(path, { ...options, credentials: "same-origin" });
if (response.status === 401) {
state.user = null;
showAuth();
}
return response;
}
async function handleImportSubmit(event) {
event.preventDefault();
const url = elements.recipeUrl.value.trim();
const htmlFallback = elements.recipeHtml.value.trim();
setStatus("Importing recipe...");
try {
const recipe = htmlFallback ? await saveRecipeHtml(htmlFallback, url) : await importRecipeFromUrl(url);
if (!recipe.title || !recipe.ingredients.length) {
throw new Error("The page did not contain enough recipe data to save.");
}
upsertRecipe(recipe);
elements.importForm.reset();
setStatus(`Imported "${recipe.title}".`);
} catch (error) {
setStatus(error.message || "Recipe import failed.");
}
}
async function handleLoadDemoRecipes() {
if (IS_HOSTED_APP) {
try {
const response = await hostedFetch("/api/recipes/bulk", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ recipes: demoRecipes }),
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(payload.error || "Could not load demo recipes.");
}
state.recipes = Array.isArray(payload.recipes) ? payload.recipes : state.recipes;
if (!state.selectedRecipeId && state.recipes[0]) {
state.selectedRecipeId = state.recipes[0].id;
}
persistState();
render();
setStatus("Loaded demo recipes into the shared meal board.");
return;
} catch (error) {
setStatus(error.message || "Could not load demo recipes.");
return;
}
}
let added = 0;
demoRecipes.forEach((recipe) => {
if (!state.recipes.some((entry) => entry.title === recipe.title)) {
state.recipes.unshift(recipe);
added += 1;
}
});
if (!state.selectedRecipeId && state.recipes[0]) {
state.selectedRecipeId = state.recipes[0].id;
}
persistState();
render();
setStatus(added ? `Loaded ${added} demo recipe${added === 1 ? "" : "s"}.` : "Demo recipes are already loaded.");
}
async function handleShareBoard() {
if (!state.recipes.length) {
setShareStatus("Add some recipes first, then create a share link.");
return;
}
try {
const shareUrl = await buildShareUrl();
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(shareUrl);
setShareStatus(
IS_HOSTED_APP
? "Live link copied. Anyone signed in will see the shared meal board."
: "Share link copied. Anyone opening it will see this recipe board."
);
return;
}
setShareStatus(shareUrl);
} catch (error) {
setShareStatus("Could not create a share link from this recipe board.");
}
}
async function importRecipeFromUrl(url) {
if (!url) {
throw new Error("Add a recipe URL first.");
}
if (IS_HOSTED_APP) {
return await importRecipeViaEndpoint(url);
}
const html = await fetchRecipeMarkup(url);
return extractRecipeFromHtml(new DOMParser().parseFromString(html, "text/html"), url);
}
async function importRecipeViaEndpoint(url) {
const response = await hostedFetch("/api/import-recipe", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ url }),
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(
payload.error ||
"The hosted importer could not fetch that recipe. Try pasting the page HTML instead."
);
}
if (Array.isArray(payload.recipes)) {
state.recipes = payload.recipes;
}
return payload.recipe;
}
async function saveRecipeHtml(html, sourceUrl) {
if (!IS_HOSTED_APP) {
const doc = new DOMParser().parseFromString(html, "text/html");
return extractRecipeFromHtml(doc, sourceUrl);
}
const response = await hostedFetch("/api/recipes", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ html, sourceUrl }),
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(payload.error || "Could not save this recipe.");
}
if (Array.isArray(payload.recipes)) {
state.recipes = payload.recipes;
}
return payload.recipe;
}
async function fetchRecipeMarkup(url) {
const directResponse = await fetch(url);
if (directResponse.ok) {
return await directResponse.text();
}
throw new Error(
"Could not fetch that URL directly. Paste the page HTML into the fallback field and import again."
);
}
function upsertRecipe(recipe) {
const existing = state.recipes.find((entry) => entry.sourceUrl === recipe.sourceUrl);
if (existing) {
Object.assign(existing, recipe, { id: existing.id });
state.selectedRecipeId = existing.id;
} else {
state.recipes.unshift(recipe);
state.selectedRecipeId = recipe.id;
}
delete state.desiredServingsByRecipe[state.selectedRecipeId];
persistDesiredServings();
persistState();
render();
}
function handleSelectRecipe(recipeId) {
state.selectedRecipeId = recipeId;
state.editingRecipeId = null;
persistState();
renderRecipeLibrary();
renderRecipeDetail();
}
function handleStartEdit(recipeId) {
state.editingRecipeId = recipeId;
renderRecipeDetail();
}
function handleCancelEdit() {
state.editingRecipeId = null;
renderRecipeDetail();
}
async function handleSaveRecipeEdit(event, recipeId) {
event.preventDefault();
const statusEl = document.querySelector("#edit-status");
const existingRecipe = state.recipes.find((entry) => entry.id === recipeId);
const updated = {
id: recipeId,
title: document.querySelector("#edit-title").value.trim(),
description: document.querySelector("#edit-description").value.trim(),
servings: document.querySelector("#edit-servings").value,
ingredients: splitLines(document.querySelector("#edit-ingredients").value),
instructions: splitLines(document.querySelector("#edit-instructions").value),
method: document.querySelector("#edit-method").value.trim(),
image: existingRecipe?.image || "",
rating: existingRecipe?.rating || 0,
};
if (!updated.title) {
statusEl.textContent = "A title is required.";
return;
}
try {
if (IS_HOSTED_APP) {
const response = await hostedFetch(`/api/recipes/${encodeURIComponent(recipeId)}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updated),
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(payload.error || "Could not save changes.");
}
state.recipes = Array.isArray(payload.recipes) ? payload.recipes : state.recipes;
} else {
const existing = state.recipes.find((entry) => entry.id === recipeId);
if (existing) {
Object.assign(existing, updated, { servings: normalizeServingsInput(updated.servings) });
}
}
state.editingRecipeId = null;
delete state.desiredServingsByRecipe[recipeId];
persistDesiredServings();
persistState();
render();
setStatus(`Saved changes to "${updated.title}".`);
} catch (error) {
statusEl.textContent = error.message || "Could not save changes.";
}
}
async function handleDeleteRecipe(recipeId) {
const recipe = state.recipes.find((entry) => entry.id === recipeId);
if (!recipe) {
return;
}
if (!window.confirm(`Delete "${recipe.title}"? This cannot be undone.`)) {
return;
}
try {
if (IS_HOSTED_APP) {
const response = await hostedFetch(`/api/recipes/${encodeURIComponent(recipeId)}`, {
method: "DELETE",
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(payload.error || "Could not delete this recipe.");
}
state.recipes = Array.isArray(payload.recipes) ? payload.recipes : state.recipes;
state.planner = payload.planner || state.planner;
} else {
state.recipes = state.recipes.filter((entry) => entry.id !== recipeId);
WEEK_DAYS.forEach((day) => {
if (state.planner[day] === recipeId) {
state.planner[day] = "";
}
});
}
if (state.selectedRecipeId === recipeId) {
state.selectedRecipeId = state.recipes[0]?.id || "";
}
state.editingRecipeId = null;
delete state.desiredServingsByRecipe[recipeId];
persistDesiredServings();
persistState();
render();
setStatus(`Deleted "${recipe.title}".`);
} catch (error) {
setStatus(error.message || "Could not delete this recipe.");
}
}
function persistState() {
if (!IS_HOSTED_APP) {
localStorage.setItem(STORAGE_KEYS.selectedRecipeId, state.selectedRecipeId);
localStorage.setItem(STORAGE_KEYS.recipes, JSON.stringify(state.recipes));
localStorage.setItem(STORAGE_KEYS.planner, JSON.stringify(state.planner));
}
}
async function hydrateRemoteState() {
try {
const response = await hostedFetch("/api/state");
if (response.status === 401) {
return;
}
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(payload.error || "Could not load the shared meal board.");
}
state.recipes = Array.isArray(payload.recipes) ? payload.recipes : [];
state.planner = payload.planner || state.planner;
} catch (error) {
setStatus("The shared meal board could not be loaded.");
}
}
async function hydrateSharedState() {
const params = new URLSearchParams(window.location.search);
const shared = params.get("share");
if (!shared) {
return;
}
try {
const decoded = await decodeSharedPayload(shared);
state.recipes = Array.isArray(decoded.recipes) ? decoded.recipes : [];
state.planner = decoded.planner || state.planner;
state.selectedRecipeId = decoded.selectedRecipeId || state.selectedRecipeId;
persistState();
} catch (error) {
setShareStatus("This share link could not be read.");
}
}
async function buildShareUrl() {
if (IS_HOSTED_APP) {
const url = new URL(window.location.href);
url.search = "";
return url.toString();
}
const payload = {
recipes: state.recipes,
planner: state.planner,
selectedRecipeId: state.selectedRecipeId,
};
const encoded = await encodeSharedPayload(payload);
const url = new URL(window.location.href);
url.searchParams.set("share", encoded);
return url.toString();
}
function render() {
renderHouseholdSettings();
renderWeeklyMenu();
renderRecipeLibrary();
renderRecipeDetail();
renderShoppingList();
renderStats();
}
function renderWeeklyMenu() {
elements.weeklyMenu.innerHTML = "";
WEEK_DAYS.forEach((day) => {
const wrapper = document.createElement("label");
wrapper.className = "day-plan";
const dayName = document.createElement("span");
dayName.className = "day-name";
dayName.textContent = day;
const select = document.createElement("select");
select.dataset.day = day;
const placeholder = document.createElement("option");
placeholder.value = "";
placeholder.textContent = "Choose a recipe";
select.appendChild(placeholder);
state.recipes.forEach((recipe) => {
const option = document.createElement("option");
option.value = recipe.id;
option.textContent = recipe.title;
option.selected = state.planner[day] === recipe.id;
select.appendChild(option);
});
select.addEventListener("change", (event) => {
state.planner[day] = event.target.value;
persistState();
if (IS_HOSTED_APP) {
savePlannerToBackend();
}
renderShoppingList();
renderStats();
});
wrapper.append(dayName, select);
elements.weeklyMenu.appendChild(wrapper);
});
}
function renderRecipeLibrary() {
elements.recipeLibrary.className = "recipe-library";
elements.recipeLibrary.innerHTML = "";
if (!state.recipes.length) {
elements.recipeLibrary.classList.add("empty-state");
elements.recipeLibrary.textContent =
"No recipes yet. Import a recipe URL or load the demo set to start planning.";
return;
}
const filteredRecipes = recipeSearchTerm
? state.recipes.filter((recipe) => recipe.title.toLowerCase().includes(recipeSearchTerm))
: state.recipes;
if (!filteredRecipes.length) {
elements.recipeLibrary.classList.add("empty-state");
elements.recipeLibrary.textContent = "No recipes match your search.";
return;
}
filteredRecipes.forEach((recipe) => {
const node = elements.recipeCardTemplate.content.firstElementChild.cloneNode(true);
node.querySelector(".recipe-card-title").textContent = recipe.title;
node.querySelector(".recipe-card-meta").textContent = `${recipe.ingredients.length} ingredients | ${recipe.instructions.length} steps`;
node.classList.toggle("active", recipe.id === state.selectedRecipeId);
node.querySelector(".recipe-card-select").addEventListener("click", () => handleSelectRecipe(recipe.id));
bindStarRating(node.querySelector(".recipe-card-rating"), recipe);
const servingsLabel = node.querySelector(".recipe-card-servings");
const servingsInput = node.querySelector(".recipe-card-servings-input");
if (recipe.servings) {
servingsInput.value = getDesiredServings(recipe) || recipe.servings;
servingsInput.addEventListener("click", (event) => event.stopPropagation());
servingsInput.addEventListener("change", (event) => {
event.stopPropagation();
setDesiredServings(recipe.id, event.target.value);
});
} else {
servingsLabel.hidden = true;
}
elements.recipeLibrary.appendChild(node);
});
}
function renderRecipeDetail() {
const recipe = state.recipes.find((entry) => entry.id === state.selectedRecipeId);
elements.recipeDetail.className = "recipe-detail";
if (!recipe) {
elements.recipeDetail.classList.add("empty-state");
elements.recipeDetail.textContent =
"Import a recipe or choose one from your library to see ingredients, instructions, and method here.";
return;
}
if (state.editingRecipeId === recipe.id) {
renderRecipeEditForm(recipe);
return;
}
const desiredServings = getDesiredServings(recipe);
const factor = recipe.servings && desiredServings ? desiredServings / recipe.servings : 1;
const ingredientsMarkup = recipe.ingredients
.map((ingredient) => `<li>${escapeHtml(scaleIngredientText(ingredient, factor))}</li>`)
.join("");
const instructionsMarkup = recipe.instructions
.map((instruction) => `<li>${escapeHtml(instruction)}</li>`)
.join("");
const sourceLinkMarkup =
recipe.sourceUrl && isSafeHttpUrl(recipe.sourceUrl)
? `<a class="detail-link" href="${escapeAttribute(recipe.sourceUrl)}" target="_blank" rel="noreferrer">
View source recipe
</a>`
: "";
const servingsControlMarkup = recipe.servings
? `<div class="servings-control">
<label>Scale ingredients to
<input type="number" id="servings-input" min="1" value="${desiredServings || recipe.servings}" />
servings
</label>
<span class="servings-base">Recipe as saved serves ${recipe.servings}.</span>
</div>`
: "";
elements.recipeDetail.innerHTML = `
<div class="detail-header">
<div class="detail-header-row">
<h3>${escapeHtml(recipe.title)}</h3>
<div class="detail-actions">
<button id="edit-recipe-button" class="ghost-button" type="button">Edit</button>
<button id="delete-recipe-button" class="ghost-button danger-button" type="button">Delete</button>
</div>
</div>
<div class="star-rating" role="group" aria-label="Rate this recipe">
<button type="button" class="star-button" data-value="1" aria-label="Rate 1 star">★</button>
<button type="button" class="star-button" data-value="2" aria-label="Rate 2 stars">★</button>
<button type="button" class="star-button" data-value="3" aria-label="Rate 3 stars">★</button>
<button type="button" class="star-button" data-value="4" aria-label="Rate 4 stars">★</button>
<button type="button" class="star-button" data-value="5" aria-label="Rate 5 stars">★</button>
</div>
${sourceLinkMarkup}
${servingsControlMarkup}
<p>${escapeHtml(recipe.description || "Saved from the source page and ready for weekly planning.")}</p>
</div>
<div class="detail-grid">
<section class="detail-block">
<h4>Ingredients</h4>
<ul>${ingredientsMarkup || "<li>No ingredients were found.</li>"}</ul>
</section>
<section class="detail-block">
<h4>Instructions</h4>
<ol>${instructionsMarkup || "<li>No instructions were found.</li>"}</ol>
</section>
<section class="detail-block">
<h4>Method</h4>
<p>${escapeHtml(recipe.method || recipe.instructions.join(" ") || "No method summary available.")}</p>
</section>
</div>
`;
elements.recipeDetail
.querySelector("#edit-recipe-button")
.addEventListener("click", () => handleStartEdit(recipe.id));
elements.recipeDetail
.querySelector("#delete-recipe-button")
.addEventListener("click", () => handleDeleteRecipe(recipe.id));
bindStarRating(elements.recipeDetail.querySelector(".star-rating"), recipe);
const servingsInput = elements.recipeDetail.querySelector("#servings-input");
servingsInput?.addEventListener("change", (event) => {
setDesiredServings(recipe.id, event.target.value);
});
}
function renderRecipeEditForm(recipe) {
elements.recipeDetail.innerHTML = `
<form id="recipe-edit-form" class="import-form recipe-edit-form">
<label class="field">
<span>Title</span>
<input id="edit-title" type="text" value="${escapeAttribute(recipe.title)}" required />
</label>
<label class="field">
<span>Description</span>
<textarea id="edit-description" rows="2">${escapeHtml(recipe.description || "")}</textarea>
</label>
<label class="field">
<span>Servings</span>
<input id="edit-servings" type="number" min="1" value="${recipe.servings || ""}" />
</label>
<label class="field">
<span>Ingredients (one per line)</span>
<textarea id="edit-ingredients" rows="8">${escapeHtml(recipe.ingredients.join("\n"))}</textarea>
</label>
<label class="field">
<span>Instructions (one per line)</span>
<textarea id="edit-instructions" rows="8">${escapeHtml(recipe.instructions.join("\n"))}</textarea>
</label>
<label class="field">
<span>Method summary</span>
<textarea id="edit-method" rows="3">${escapeHtml(recipe.method || "")}</textarea>
</label>
<div class="import-actions">
<button class="primary-button" type="submit">Save changes</button>
<button id="cancel-edit-button" class="ghost-button" type="button">Cancel</button>
<p id="edit-status" class="status-text" aria-live="polite"></p>
</div>
</form>
`;
elements.recipeDetail
.querySelector("#recipe-edit-form")
.addEventListener("submit", (event) => handleSaveRecipeEdit(event, recipe.id));
elements.recipeDetail.querySelector("#cancel-edit-button").addEventListener("click", handleCancelEdit);
}
function renderShoppingList() {
ensureShoppingOverridesCurrent();
const selectedRecipes = WEEK_DAYS.map((day) => state.planner[day])
.filter(Boolean)
.map((recipeId) => state.recipes.find((recipe) => recipe.id === recipeId))
.filter(Boolean);
if (!selectedRecipes.length) {
currentShoppingItems = [];
elements.shoppingList.className = "shopping-list empty-state";
elements.shoppingList.textContent =
"Choose recipes in the weekly menu to build a shopping list automatically.";
updateShoppingTotalDisplay();
return;
}
const combined = new Map();
selectedRecipes.forEach((recipe) => {
const desiredServings = getDesiredServings(recipe);
const factor = recipe.servings && desiredServings ? desiredServings / recipe.servings : 1;
recipe.ingredients.forEach((ingredient) => {
const parsed = parseIngredient(scaleIngredientText(ingredient, factor));
const current = combined.get(parsed.key);
if (current) {
mergeIngredientEntry(current, parsed, recipe.title);
return;
}
combined.set(parsed.key, createIngredientEntry(parsed, recipe.title));
});
});
const items = Array.from(combined.values()).sort((left, right) =>
left.label.localeCompare(right.label)
);
currentShoppingItems = items;
elements.shoppingList.className = "shopping-list";
elements.shoppingList.innerHTML = "";
const groupedItems = groupShoppingItems(items);
groupedItems.forEach((group) => {
const section = document.createElement("section");
section.className = "shopping-category";
const heading = document.createElement("h3");
heading.className = "shopping-category-title";
heading.textContent = group.label;
const list = document.createElement("ul");
const sortedItems = [...group.items].sort(
(left, right) => Number(isItemRemoved(left)) - Number(isItemRemoved(right))
);
sortedItems.forEach((item) => {
list.appendChild(buildShoppingItemNode(item));
});
section.append(heading, list);
elements.shoppingList.appendChild(section);
});
updateShoppingTotalDisplay();
}
function buildShoppingItemNode(item) {
const node = elements.shoppingItemTemplate.content.firstElementChild.cloneNode(true);
const removed = isItemRemoved(item);
node.classList.toggle("shopping-item--removed", removed);
node.querySelector(".shopping-item-name").textContent = item.label;
node.querySelector(".shopping-item-count").textContent = formatIngredientSummary(item);
const priceInput = node.querySelector(".price-input");
const existingPrice = state.shoppingOverrides.prices[item.key];
priceInput.value = existingPrice === undefined || existingPrice === null ? "" : existingPrice;
priceInput.disabled = removed;
priceInput.addEventListener("input", (event) => {
const value = event.target.value;
if (value === "") {
delete state.shoppingOverrides.prices[item.key];
} else {
const parsed = Number(value);
if (Number.isFinite(parsed) && parsed >= 0) {
state.shoppingOverrides.prices[item.key] = parsed;
}
}
persistShoppingOverrides();
updateShoppingTotalDisplay();
});
const removeButton = node.querySelector(".remove-item-button");
const restoreButton = node.querySelector(".restore-item-button");
removeButton.hidden = removed;
restoreButton.hidden = !removed;
removeButton.addEventListener("click", () => setItemRemoved(item.key, true));
restoreButton.addEventListener("click", () => setItemRemoved(item.key, false));