-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
381 lines (323 loc) · 11.4 KB
/
Copy pathpopup.js
File metadata and controls
381 lines (323 loc) · 11.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
const RECIPES_KEY = "savedRecipes";
const MAX_SUGGESTIONS = 5;
const SEASON_LABELS = {
all: "Toutes saisons",
winter: "Hiver",
spring: "Printemps",
summer: "Ete",
autumn: "Automne"
};
const state = {
recipes: [],
activeTab: null,
activeRecipePreview: null,
selectedTab: "active"
};
const elements = {
tabButtons: Array.from(document.querySelectorAll(".tab-button")),
tabPanels: Array.from(document.querySelectorAll(".tab-panel")),
saveButton: document.getElementById("save-current-recipe"),
refreshSuggestionsButton: document.getElementById("refresh-suggestions"),
activeTabStatus: document.getElementById("active-tab-status"),
activeTabPreview: document.getElementById("active-tab-preview"),
seasonFilter: document.getElementById("season-filter"),
recipeCount: document.getElementById("recipe-count"),
libraryCount: document.getElementById("library-count"),
randomRecipes: document.getElementById("random-recipes"),
allRecipes: document.getElementById("all-recipes"),
cardTemplate: document.getElementById("recipe-card-template")
};
document.addEventListener("DOMContentLoaded", init);
for (const button of elements.tabButtons) {
button.addEventListener("click", () => switchTab(button.dataset.tab));
}
elements.saveButton.addEventListener("click", handleSaveCurrentRecipe);
elements.refreshSuggestionsButton.addEventListener("click", renderSuggestions);
elements.seasonFilter.addEventListener("change", () => {
renderSuggestions();
renderAllRecipes();
});
async function init() {
await Promise.all([loadRecipes(), inspectActiveTab()]);
switchTab(state.selectedTab);
renderSuggestions();
renderAllRecipes();
}
async function loadRecipes() {
state.recipes = await getFromStorage(RECIPES_KEY, []);
elements.libraryCount.textContent = `${state.recipes.length} recette(s) uniques memorisee(s)`;
}
async function inspectActiveTab() {
const [activeTab] = await queryActiveTab();
state.activeTab = activeTab || null;
state.activeRecipePreview = null;
if (!activeTab?.id || !isJowRecipeUrl(activeTab.url || "")) {
elements.saveButton.disabled = true;
elements.activeTabStatus.textContent = "Aucune recette compatible active dans l'onglet courant.";
elements.activeTabPreview.classList.add("hidden");
return;
}
try {
const response = await sendTabMessage(activeTab.id, { type: "extractRecipe" });
if (!response?.ok || !response.recipe) {
throw new Error(response?.error || "Impossible d'analyser cette page.");
}
state.activeRecipePreview = response.recipe;
elements.saveButton.disabled = false;
elements.activeTabStatus.textContent = "Recette detectee dans l'onglet courant.";
renderActiveTabPreview(response.recipe);
} catch (error) {
elements.saveButton.disabled = true;
elements.activeTabStatus.textContent = error.message;
elements.activeTabPreview.classList.add("hidden");
}
}
async function handleSaveCurrentRecipe() {
if (!state.activeTab?.id) {
return;
}
elements.saveButton.disabled = true;
elements.activeTabStatus.textContent = "Enregistrement en cours...";
try {
const extracted = state.activeRecipePreview
? { ok: true, recipe: state.activeRecipePreview }
: await sendTabMessage(state.activeTab.id, { type: "extractRecipe" });
if (!extracted?.ok || !extracted.recipe) {
throw new Error(extracted?.error || "Impossible d'extraire la recette.");
}
const saveResponse = await sendRuntimeMessage({
type: "saveRecipe",
tabId: state.activeTab.id,
recipe: extracted.recipe
});
if (!saveResponse?.ok) {
throw new Error(saveResponse?.error || "Erreur lors de la sauvegarde.");
}
state.activeRecipePreview = extracted.recipe;
elements.activeTabStatus.textContent = saveResponse.alreadyTracked
? "Cette recette est deja suivie pour cet onglet."
: "Recette enregistree. Sa date de fermeture sera memorisee quand l'onglet changera ou sera ferme.";
await loadRecipes();
renderSuggestions();
renderAllRecipes();
} catch (error) {
elements.activeTabStatus.textContent = error.message;
} finally {
elements.saveButton.disabled = !state.activeRecipePreview;
}
}
function renderActiveTabPreview(recipe) {
elements.activeTabPreview.innerHTML = "";
elements.activeTabPreview.classList.remove("hidden");
elements.activeTabPreview.appendChild(createRecipeCard(recipe, { compact: true }));
}
function switchTab(tabId) {
state.selectedTab = tabId;
for (const button of elements.tabButtons) {
button.classList.toggle("is-active", button.dataset.tab === tabId);
}
for (const panel of elements.tabPanels) {
panel.classList.toggle("hidden", panel.dataset.panel !== tabId);
}
}
function renderSuggestions() {
const season = elements.seasonFilter.value;
const pool = getFilteredRecipes(season);
const picked = shuffle(pool).slice(0, MAX_SUGGESTIONS);
elements.recipeCount.textContent = `${pool.length} recette(s) disponible(s) pour ${SEASON_LABELS[season].toLowerCase()}`;
renderRecipeList(elements.randomRecipes, picked, {
emptyMessage:
season === "all"
? "Aucune recette enregistree pour le moment."
: `Aucune recette n'a encore ete enregistree pour ${SEASON_LABELS[season].toLowerCase()}.`
});
}
function renderAllRecipes() {
const recipes = [...state.recipes].sort((left, right) => {
return getLastOccurrenceTimestamp(right) - getLastOccurrenceTimestamp(left);
});
renderRecipeList(elements.allRecipes, recipes, {
emptyMessage: "Aucune recette enregistree pour le moment."
});
}
function renderRecipeList(container, recipes, { emptyMessage }) {
container.innerHTML = "";
if (recipes.length === 0) {
const emptyState = document.createElement("p");
emptyState.className = "empty-state";
emptyState.textContent = emptyMessage;
container.appendChild(emptyState);
return;
}
for (const recipe of recipes) {
container.appendChild(createRecipeCard(recipe));
}
}
function createRecipeCard(recipe, options = {}) {
const template = elements.cardTemplate.content.firstElementChild.cloneNode(true);
const img = template.querySelector("img");
const title = template.querySelector("h3");
const description = template.querySelector(".recipe-description");
const meta = template.querySelector(".recipe-meta");
const seasonPill = template.querySelector(".pill-season");
const countPill = template.querySelector(".pill-count");
const chips = template.querySelector(".chips");
const link = template.querySelector(".recipe-link");
const lastOccurrence = getLastOccurrence(recipe);
const lastDate = lastOccurrence?.closedAt || lastOccurrence?.savedAt || recipe.updatedAt || recipe.createdAt;
const lastSeason = lastDate ? getSeasonFromDate(lastDate) : "all";
const occurrenceCount = Array.isArray(recipe.occurrences) ? recipe.occurrences.length : 0;
if (recipe.imageUrl) {
img.src = recipe.imageUrl;
img.alt = recipe.title;
} else {
template.querySelector(".recipe-card-media").classList.add("hidden");
template.style.gridTemplateColumns = "1fr";
}
title.textContent = recipe.title || "Recette sans titre";
description.textContent = recipe.description || "Aucune description disponible.";
seasonPill.textContent = `Derniere saison: ${SEASON_LABELS[lastSeason]}`;
countPill.textContent = occurrenceCount > 1 ? `${occurrenceCount} passages` : "1 passage";
meta.textContent = buildMetaText(recipe, lastOccurrence);
if (recipe.canonicalUrl && !options.compact) {
link.href = recipe.canonicalUrl;
link.classList.remove("hidden");
}
const ingredientNames = (recipe.ingredients || [])
.map((ingredient) => ingredient.name || ingredient.raw)
.filter(Boolean)
.slice(0, options.compact ? 3 : 4);
for (const ingredientName of ingredientNames) {
const chip = document.createElement("span");
chip.className = "chip";
chip.textContent = ingredientName;
chips.appendChild(chip);
}
if (ingredientNames.length === 0) {
chips.remove();
}
if (options.compact) {
description.remove();
}
return template;
}
function buildMetaText(recipe, lastOccurrence) {
const parts = [];
if (lastOccurrence?.closedAt) {
parts.push(`Derniere fermeture: ${formatDate(lastOccurrence.closedAt)}`);
} else if (lastOccurrence?.savedAt) {
parts.push(`Sauvegardee le: ${formatDate(lastOccurrence.savedAt)}`);
}
if (recipe.canonicalUrl) {
try {
const domain = new URL(recipe.canonicalUrl).hostname.replace(/^www\./, "");
parts.push(domain);
} catch (_error) {
// Ignore malformed URLs in the UI.
}
}
return parts.join(" | ");
}
function getFilteredRecipes(season) {
if (season === "all") {
return [...state.recipes];
}
return state.recipes.filter((recipe) => {
return (recipe.occurrences || []).some((occurrence) => {
const referenceDate = occurrence.closedAt || occurrence.savedAt;
return referenceDate && getSeasonFromDate(referenceDate) === season;
});
});
}
function getLastOccurrence(recipe) {
return [...(recipe.occurrences || [])].sort((left, right) => {
return getOccurrenceTimestamp(right) - getOccurrenceTimestamp(left);
})[0];
}
function getLastOccurrenceTimestamp(recipe) {
return getOccurrenceTimestamp(getLastOccurrence(recipe));
}
function getOccurrenceTimestamp(occurrence) {
if (!occurrence) {
return 0;
}
const value = occurrence.closedAt || occurrence.savedAt;
return value ? new Date(value).getTime() : 0;
}
function getSeasonFromDate(value) {
const date = new Date(value);
const month = date.getMonth();
if ([11, 0, 1].includes(month)) {
return "winter";
}
if ([2, 3, 4].includes(month)) {
return "spring";
}
if ([5, 6, 7].includes(month)) {
return "summer";
}
return "autumn";
}
function formatDate(value) {
const date = new Date(value);
return new Intl.DateTimeFormat("fr-FR", {
day: "2-digit",
month: "short",
year: "numeric"
}).format(date);
}
function isJowRecipeUrl(url) {
return /https:\/\/(?:www\.)?jow\.(?:fr|com)\/(?:[a-z]{2}\/)?recipes?\//i.test(url);
}
function shuffle(items) {
const copy = [...items];
for (let index = copy.length - 1; index > 0; index -= 1) {
const swapIndex = Math.floor(Math.random() * (index + 1));
[copy[index], copy[swapIndex]] = [copy[swapIndex], copy[index]];
}
return copy;
}
function queryActiveTab() {
return new Promise((resolve, reject) => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve(tabs);
});
});
}
function sendTabMessage(tabId, message) {
return new Promise((resolve, reject) => {
chrome.tabs.sendMessage(tabId, message, (response) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve(response);
});
});
}
function sendRuntimeMessage(message) {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage(message, (response) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve(response);
});
});
}
function getFromStorage(key, fallbackValue) {
return new Promise((resolve, reject) => {
chrome.storage.local.get(key, (result) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve(result[key] ?? fallbackValue);
});
});
}