-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpopup.js
More file actions
393 lines (347 loc) · 10.6 KB
/
popup.js
File metadata and controls
393 lines (347 loc) · 10.6 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
import {
FETCH_ID_TASK_URL,
FETCH_RESULT_ECOINDEX_URL,
FETCH_RESULT_URL,
FETCH_SCREENSHOT_URL,
FETCH_TASK_URL,
getBrowserPolyfill,
} from "../common.js";
let tabUrl;
/** @type {{ showScreenshot: boolean }} */
let options = { showScreenshot: true };
const domTitle = document.getElementById("title");
const currentBrowser = getBrowserPolyfill();
const badgeIntegrationElement = document.getElementById("badge-integration");
const badgeSnippetElement = document.getElementById("badge-snippet");
const badgeThemeElement = document.getElementById("badge-theme");
const badgePreviewLinkElement = document.getElementById("badge-preview-link");
const badgePreviewImgElement = document.getElementById("badge-preview-img");
let shouldRefreshBadgePreview = false;
async function loadOptions() {
const stored = await currentBrowser.storage.local.get({
ecoindex_options: { showScreenshot: true },
});
options = { ...stored.ecoindex_options };
}
/**
* display error message
* @param string title
* @param any detail
*/
function displayError(title, detail) {
document.getElementById("loader").style.display = "none";
const errorTitle = document.querySelector("#error summary");
const errorDetail = document.querySelector("#error code");
errorDetail.textContent = detail;
errorTitle.textContent = title;
document.getElementById("error").style.display = "block";
}
/**
* Display error message if an error occurs while fetching data
* @param Error error
*/
function handleApiError(error) {
console.error(error);
displayError(
"Une erreur est survenue en essayant de récupérer les données de l'API",
error.message,
);
}
/**
* Propose to analyze the current page if no analysis is available
* @param string message
*/
function proposeAnalysis(message) {
const noAnalyzis = document.getElementById("no-analysis");
domTitle.textContent = message;
noAnalyzis.style.display = "block";
domTitle.style.display = "block";
}
/**
* Helper to display date in french
* @param Date date
* @returns string
*/
function convertDate(date) {
return new Date(date).toLocaleDateString("fr-FR", {
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
});
}
/**
* Display the image of the analysis if exists
* @param string id
*/
function displayImage(id) {
fetch(FETCH_SCREENSHOT_URL(id))
.then((response) => {
if (response.status !== 200) {
throw new Error(`Pas de screenshot pour l'analyse ${id}`);
}
return response.blob();
})
.then((imageBlob) => {
const screenshot = document.getElementById("screenshot");
screenshot.setAttribute("src", URL.createObjectURL(imageBlob));
screenshot.style.display = "block";
})
.catch((error) => console.error(error));
}
/**
* Reset list element
* @param Element section
*/
function resetList(section) {
const ul = section.getElementsByTagName("ul")[0];
ul.innerHTML = "";
}
/**
* Display list element for other results
* @param Element section
* @param any ecoindex
*/
function makeList(section, ecoindex) {
const b = document.createElement("button");
b.style.backgroundColor = ecoindex.color;
b.style.color = "#FFF";
b.style.padding = "10px";
b.textContent = ecoindex.grade;
const resultLink = document.createElement("a");
resultLink.appendChild(b);
resultLink.setAttribute("href", FETCH_RESULT_ECOINDEX_URL(ecoindex.id));
resultLink.setAttribute("target", "_blank");
const li = document.createElement("li");
li.style.listStyleType = "none";
li.setAttribute(
"title",
`(${ecoindex.score} / 100) le ${convertDate(ecoindex.date)}`,
);
li.appendChild(resultLink);
const pageLink = document.createElement("a");
pageLink.textContent = ecoindex.url;
pageLink.setAttribute("href", ecoindex.url);
pageLink.style.paddingLeft = "5px";
pageLink.style.textDecoration = "none";
pageLink.setAttribute("target", "_blank");
li.appendChild(pageLink);
const pageLinkDate = document.createElement("span");
pageLinkDate.style.fontSize = "0.8rem";
pageLinkDate.textContent = `(${convertDate(ecoindex.date)})`;
pageLinkDate.style.paddingLeft = "5px";
pageLink.appendChild(pageLinkDate);
const ul = section.getElementsByTagName("ul")[0];
ul.appendChild(li);
}
/**
* Display other results
* @param any ecoindexData
* @param string tag
* @returns null
*/
function setOtherResults(ecoindexData, tag) {
const section = document.getElementById(`${tag}-results`);
const data = ecoindexData[`${tag}-results`];
if ((data?.length || 0) === 0) {
return;
}
resetList(section);
data.slice(-5).forEach((ecoindex) => {
makeList(section, ecoindex);
});
section.style.display = "block";
}
/**
* Display the result of the analysis using data from the API
* @param any ecoindexData results from the BFF API
*/
function displayResult(ecoindexData) {
const latestResult = ecoindexData["latest-result"];
if (latestResult.id !== "") {
const dateResultElement = document.getElementById("result-date");
dateResultElement.textContent = convertDate(latestResult.date);
domTitle.textContent = "Résultat pour cette page";
domTitle.style.display = "block";
const activeLevelChart = document.querySelector(
`[data-grade-result="${latestResult.grade}"]`,
);
activeLevelChart.classList.add("--active");
const resultScore = document.getElementById("result-score");
resultScore.textContent = latestResult.score;
const resultLink = document.getElementById("result-link");
resultLink.setAttribute("href", FETCH_RESULT_ECOINDEX_URL(latestResult.id));
document.getElementById("result").style.display = "block";
badgeIntegrationElement.style.display = "block";
updateBadgeSnippet(tabUrl, getBadgeTheme(), shouldRefreshBadgePreview);
shouldRefreshBadgePreview = false;
if (options.showScreenshot) {
displayImage(latestResult.id);
}
}
if (
ecoindexData["older-results"]?.length > 0 ||
ecoindexData["host-results"]?.length > 0
) {
document.getElementById("other-results").style.display = "block";
setOtherResults(ecoindexData, "older");
setOtherResults(ecoindexData, "host");
}
}
/**
* Update the popup with data from the API
* @param any ecoindexData
*/
function updatePopup(ecoindexData) {
if (
ecoindexData.count === 0 &&
(ecoindexData["older-results"]?.length || 0) === 0
) {
proposeAnalysis("Aucune analyse pour ce site");
} else if (ecoindexData["latest-result"].id === "") {
proposeAnalysis("Aucune analyse pour cette page");
}
displayResult(ecoindexData);
}
/**
* Build and display a reusable Ecoindex badge snippet for the current URL.
* @param {string} url
* @param {"light" | "dark"} theme
* @param {boolean} refreshPreview
*/
function updateBadgeSnippet(url, theme = "light", refreshPreview = false) {
const redirectUrl = `https://bff.ecoindex.fr/redirect/?url=${url}`;
const badgeUrl = `https://bff.ecoindex.fr/badge/?theme=${theme}&url=${url}`;
const previewUrl = refreshPreview
? `${badgeUrl}&refresh=true&_ts=${Date.now()}`
: badgeUrl;
badgeSnippetElement.textContent = `<a href="${redirectUrl}" target="_blank">
<img src="${badgeUrl}" alt="Ecoindex Badge" />
</a>`;
badgePreviewLinkElement.setAttribute("href", redirectUrl);
badgePreviewImgElement.setAttribute("src", previewUrl);
}
function getBadgeTheme() {
return badgeThemeElement.value === "dark" ? "dark" : "light";
}
/**
* Get data from the API and update the popup
* @param string url
*/
function getAndUpdateEcoindexData(url) {
fetch(FETCH_RESULT_URL(url, true))
.then((r) => r.json())
.then(updatePopup)
.catch(handleApiError);
}
const fetchWithRetries = async (url, options, retryCount = 0) => {
const { maxRetries = 30, ...remainingOptions } = options;
fetch(url, remainingOptions)
.then(async (r) => {
if (retryCount < maxRetries && r.status === 425) {
// eslint-disable-next-line no-promise-executor-return
await new Promise((t) => setTimeout(t, 2000));
await fetchWithRetries(url, options, retryCount + 1);
}
return r.json();
})
.then((taskResult) => {
if (taskResult === undefined) {
return;
}
const ecoindex = taskResult.ecoindex_result;
if (taskResult.status === "SUCCESS" && ecoindex.status === "SUCCESS") {
document.getElementById("loader").style.display = "none";
document.getElementById("no-analysis").style.display = "none";
getAndUpdateEcoindexData(tabUrl);
}
if (taskResult.status === "SUCCESS" && ecoindex.status === "FAILURE") {
const e = taskResult.ecoindex_result.error;
displayError(e.message, e.detail);
}
if (taskResult.status === "FAILURE") {
displayError(
"Erreur lors de l'analyse de la page",
taskResult.task_error,
);
}
})
.catch(async (err) => {
if (retryCount < maxRetries && err.status === 425) {
// eslint-disable-next-line no-promise-executor-return
await new Promise((r) => setTimeout(r, 2000));
await fetchWithRetries(url, options, retryCount + 1);
}
displayError("Erreur lors de l'analyse de la page", err);
});
};
/**
* Reset the display
* @returns null
*/
function resetDisplay() {
document.getElementById("loader").style.display = "none";
document.getElementById("title").style.display = "none";
document.getElementById("no-analysis").style.display = "none";
document.getElementById("result").style.display = "none";
document.getElementById("screenshot").style.display = "none";
document.getElementById("other-results").style.display = "none";
document.getElementById("older-results").style.display = "none";
document.getElementById("host-results").style.display = "none";
document.getElementById("error").style.display = "none";
badgeIntegrationElement.style.display = "none";
}
/**
* Call the API to run an analysis
*/
async function runAnalysis() {
resetDisplay();
document.getElementById("loader").style.display = "block";
shouldRefreshBadgePreview = true;
fetch(FETCH_TASK_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
web_page: {
width: 1920,
height: 1080,
url: tabUrl,
},
}),
})
.then((r) => r.json())
.then(async (id) => {
await fetchWithRetries(FETCH_ID_TASK_URL(id), {
headers: {
"Content-Type": "application/json",
},
method: "GET",
});
});
}
resetDisplay();
loadOptions()
.then(() => {
document
.querySelector("#no-analysis button")
.addEventListener("click", runAnalysis);
document.getElementById("retest").addEventListener("click", runAnalysis);
badgeThemeElement.addEventListener("change", () => {
updateBadgeSnippet(tabUrl, getBadgeTheme());
});
currentBrowser.tabs.query(
{
active: true,
lastFocusedWindow: true,
},
(tabs) => {
tabUrl = tabs[0].url;
updateBadgeSnippet(tabUrl, getBadgeTheme());
getAndUpdateEcoindexData(tabUrl);
},
);
})
.catch(console.error);