-
Notifications
You must be signed in to change notification settings - Fork 2
/
script.js
258 lines (213 loc) · 6.89 KB
/
script.js
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
/**
* Given a date,
* write "Xd Yh Zm"
*
* https://stackoverflow.com/a/13904120
*/
const dateToEndsInXdYhZm = (date) => {
const currentDate = new Date();
const givenDate = new Date(date);
let delta = (givenDate - currentDate) / 1000;
let daysLeft = Math.floor(delta / 86400);
delta -= daysLeft * 86400;
let hoursLeft = Math.floor(delta / 3600) % 24;
delta -= hoursLeft * 3600;
let minutesLeft = Math.floor(delta / 60) % 60;
delta -= minutesLeft * 60;
if (daysLeft < 0) {
return { endsIn: null, daysLeft, hoursLeft, minutesLeft };
}
const daysStr = daysLeft ? `${daysLeft}d` : "";
const hoursStr = hoursLeft ? `${hoursLeft}h` : "";
const minutesStr = minutesLeft ? `${minutesLeft}m` : "";
const lessThanAMinute = !daysLeft && !hoursLeft && !minutesLeft;
const endsIn = lessThanAMinute
? ">1min left"
: `${daysStr} ${hoursStr} ${minutesStr} left`;
return { endsIn, daysLeft, hoursLeft, minutesLeft };
};
const variantFromDaysLeft = (days) => {
let variant = "primary";
if (2 < days && days <= 5) {
variant = "warning";
}
if (days <= 2) {
variant = "danger";
}
return variant;
};
const generateCard = (item) => {
const slCard = document.createElement("sl-card");
slCard.classList.add("item-card");
slCard.id = item.id;
slCard.addEventListener("click", () => {
window.open(item.link, "_blank").focus();
});
const img = document.createElement("img");
img.slot = "image";
img.src = item.img_link;
img.alt = item.title;
const link = document.createElement("a");
link.classList.add("item-title");
link.innerText = item.title;
link.href = item.link;
const description = document.createElement("span");
description.innerText = item.description;
description.classList.add("item-description");
const author = document.createElement("small");
author.innerText = item.author;
const itemCategory = document.createElement("sl-badge");
itemCategory.classList.add("item-category");
itemCategory.variant = "success";
itemCategory.innerText = item.category;
const endDate = document.createElement("sl-badge");
endDate.classList.add("item-end-date");
const { endsIn, daysLeft } = dateToEndsInXdYhZm(item.end_date);
endDate.variant = variantFromDaysLeft(daysLeft);
// consider that the date is in the past
if (!endsIn) {
return null;
}
endDate.innerText = endsIn;
slCard.appendChild(img);
slCard.appendChild(link);
slCard.appendChild(description);
slCard.appendChild(itemCategory);
slCard.appendChild(endDate);
return slCard;
};
const getItemsWithCategory = (itemsByCategory) => {
const newItems = [];
for (const [category, items] of Object.entries(itemsByCategory)) {
for (const item of items) {
newItems.push({ ...item, category });
}
}
return newItems;
};
const generateCards = (container, items) => {
container.innerHTML = "";
for (const item of items) {
const card = generateCard(item);
if (card) {
container.appendChild(card);
}
}
};
const setTheme = (theme, element) => {
const iconTheme = element.querySelector("sl-icon");
if (theme === "dark") {
iconTheme.name = "moon-fill";
element.className = "sl-theme-dark";
} else {
iconTheme.name = "sun-fill";
element.className = "sl-theme-light";
}
};
const toggleTheme = () => {
const currentTheme = document.documentElement.className;
if (currentTheme === "sl-theme-dark") {
setTheme("light", document.documentElement);
localStorage.setItem("theme", "light");
} else {
setTheme("dark", document.documentElement);
localStorage.setItem("theme", "dark");
}
};
const loadTheme = () => {
const theme = localStorage.getItem("theme");
if (theme) {
setTheme(theme, document.documentElement);
} else {
localStorage.setItem("theme", "light");
}
};
const getSavedFilters = () => {
const sortByDate = localStorage.getItem("sort-by-date") === "true";
const categoriesStr = localStorage.getItem("filter-by-categories") ?? "[]";
const categories = JSON.parse(categoriesStr);
return [sortByDate, categories];
};
const setSortByFilter = (isEnabled) => {
localStorage.setItem("sort-by-date", isEnabled);
};
const setCategoriesFilter = (categories) => {
localStorage.setItem("filter-by-categories", JSON.stringify(categories));
};
const getNewSortedItems = (items, isEnabled = true) => {
if (!isEnabled) {
return items;
}
const sortedItems = [...items];
sortedItems.sort((a, b) => {
const aDate = new Date(a.end_date);
const bDate = new Date(b.end_date);
return aDate - bDate;
});
return sortedItems;
};
const getNewFilteredItems = (items, categories) => {
if (categories.length === 0) {
return items;
}
return [...items.filter((item) => categories.includes(item.category))];
};
// initialize the page
// the "?" after the filename is to specify a version of the file
// this tricks the browser to ignore the cache & effectively reload the file
const itemsByCategory = await fetch(
`assets/items.json?${new Date().getTime()}`
).then((response) => response.json());
const originalItems = getItemsWithCategory(itemsByCategory);
const [savedSortBy, savedCategories] = getSavedFilters();
let items = getNewSortedItems(
getNewFilteredItems(originalItems, savedCategories),
savedSortBy
);
const cards = document.querySelector("#cards");
// generate for the first time the cards
generateCards(cards, items);
const sortByDate = document.querySelector("#sort-by-date");
sortByDate.checked = savedSortBy;
sortByDate.addEventListener("click", () => {
const checked = sortByDate.checked;
if (checked) {
generateCards(cards, getNewSortedItems(items));
} else {
generateCards(cards, items);
}
setSortByFilter(checked);
});
const openInfoBtn = document.querySelector("#open-info");
openInfoBtn.addEventListener("click", () => {
const infoDrawer = document.querySelector("#info-drawer");
infoDrawer.show();
});
loadTheme();
const toggleThemeBtn = document.querySelector("#toggle-theme");
toggleThemeBtn.addEventListener("click", toggleTheme);
const selectCategories = document.querySelector("#select-category");
selectCategories.value = savedCategories;
selectCategories.addEventListener("sl-change", (ev) => {
const categories = ev.target.value;
items = getNewFilteredItems(originalItems, categories);
// don't forget to sort the filtered items if enabled
generateCards(cards, getNewSortedItems(items, sortByDate.checked));
setCategoriesFilter(categories);
});
/**
* Wait for all shoelace elements to be defined
* to display them.
*/
await Promise.allSettled([
customElements.whenDefined("sl-switch"),
customElements.whenDefined("sl-select"),
customElements.whenDefined("sl-button"),
customElements.whenDefined("sl-icon"),
customElements.whenDefined("sl-drawer"),
customElements.whenDefined("sl-card"),
customElements.whenDefined("sl-badge"),
]);
document
.querySelectorAll(".contain-shoelace")
.forEach((el) => el.classList.add("ready"));