-
Notifications
You must be signed in to change notification settings - Fork 228
/
script.js
450 lines (406 loc) · 12.9 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
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
// copied from excalidraw/excalidraw
const debounce = (fn, timeout) => {
let handle = 0;
let lastArgs = null;
const ret = (...args) => {
lastArgs = args;
clearTimeout(handle);
handle = window.setTimeout(() => {
lastArgs = null;
fn(...args);
}, timeout);
};
ret.flush = () => {
clearTimeout(handle);
if (lastArgs) {
const _lastArgs = lastArgs;
lastArgs = null;
fn(..._lastArgs);
}
};
ret.cancel = () => {
lastArgs = null;
clearTimeout(handle);
};
return ret;
};
const fetchJSONFile = (path, callback) => {
let httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
let data = JSON.parse(httpRequest.responseText);
if (callback) callback(data);
}
}
};
httpRequest.open("GET", path);
httpRequest.send();
};
const getDate = (date) => {
const d = new Date(date);
const MONTHS = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
return `${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}`;
};
const DAY = 24 * 60 * 60 * 1000;
const sortByDate = (property) => (a, b) => {
const aTime = new Date(a[property]);
const bTime = new Date(b[property]);
const today = new Date();
const diffA = today.getTime() - aTime.getTime();
const diffB = today.getTime() - bTime.getTime();
return diffB - diffA;
};
const sortBy = {
default: {
label: "Default",
func: (items) => {
const sortedByNewAsc = sortBy.new.func(items);
const TWO_WEEKS = 12096e5;
const timeTwoWeeksAgo = new Date(Date.now() - TWO_WEEKS);
const indexOfItemOlderThan2WeeksAsc =
sortedByNewAsc.length -
sortedByNewAsc
.slice()
.reverse()
.findIndex((x) => {
return new Date(x.created) <= timeTwoWeeksAgo;
});
const topNewItemsAsc = sortedByNewAsc.slice(
indexOfItemOlderThan2WeeksAsc,
);
const downloadPerWeekAsc = sortBy.downloadsWeek.func(
sortedByNewAsc.slice(0, indexOfItemOlderThan2WeeksAsc),
);
return downloadPerWeekAsc.concat(topNewItemsAsc);
},
},
new: {
label: "New",
func: (items) => items.sort(sortByDate("created")),
},
updates: {
label: "Updated",
func: (items) => items.sort(sortByDate("updated")),
},
downloadsTotal: {
label: "Total Downloads",
func: (items) =>
items.sort((a, b) => {
return a.downloads.total - b.downloads.total;
}),
},
downloadsWeek: {
label: "Downloads This Week",
func: (items) =>
items.sort((a, b) => {
return a.downloads.week - b.downloads.week;
}),
},
author: {
label: "Author",
func: (items) =>
items.sort((a, b) => {
return b.authors[0].name.localeCompare(a.authors[0].name);
}),
},
name: {
label: "Name",
func: (items) =>
items.sort((a, b) => {
return b.name.localeCompare(a.name);
}),
},
};
// -----------------------------------------------------------------------------
const APP_NAMES = {
"Excalidraw+": "https://app.excalidraw.com",
Excalidraw: "https://excalidraw.com",
Excalideck: "https://app.excalideck.com",
};
let appName = "";
const getAppName = (referrer) => {
return (appName =
appName ||
Object.entries(APP_NAMES).find(([appName, domain]) => {
return referrer.includes(domain);
})?.[0] ||
"Excalidraw");
};
// -----------------------------------------------------------------------------
let libraries_ = [];
let currSort = null;
const searchKeys = ["name", "description", "itemNames"];
let IMG_INTERSECTION_OBSERVER = null;
const initImageLazyLoading = () => {
if (IMG_INTERSECTION_OBSERVER) {
IMG_INTERSECTION_OBSERVER.disconnect();
}
const lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
if ("IntersectionObserver" in window) {
const lazyImageObserver = new IntersectionObserver(
function (entries) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.classList.remove("lazy");
lazyImageObserver.unobserve(lazyImage);
}
});
},
{
rootMargin: "0px 0px 500px 0px",
},
);
IMG_INTERSECTION_OBSERVER = lazyImageObserver;
lazyImages.forEach(function (lazyImage) {
lazyImageObserver.observe(lazyImage);
});
} else {
lazyImages.forEach(function (lazyImage) {
lazyImage.src = lazyImage.dataset.src;
});
}
};
const escapeHTMLAttribute = (str) => {
const map = {
"&": "&",
"<": "<",
">": ">",
'"': """,
};
if (typeof str !== "string") return "";
return str.replace(/[&<>"]/g, (char) => map[char]);
};
const populateLibraryList = (filterQuery = "") => {
const items = [
...document.getElementById("template").parentNode.children,
].filter((x) => x.id !== "template");
items.forEach((x) => x.remove());
filterQuery = filterQuery.trim().toLowerCase();
const hasMatch = (haystackStr) =>
haystackStr.toLowerCase().includes(filterQuery);
let libraries = libraries_;
if (filterQuery) {
libraries = libraries.filter((library) =>
searchKeys.some((key) => {
const haystack = library[key] || "";
if (Array.isArray(haystack)) {
return haystack.some((x) => hasMatch(x));
} else {
return hasMatch(haystack);
}
}),
);
}
const template = document.getElementById("template");
const searchParams = new URLSearchParams(location.search);
const referrer = escapeHTMLAttribute(
searchParams.get("referrer") || "https://excalidraw.com",
);
const appName = getAppName(referrer);
const target = decodeURIComponent(
escapeHTMLAttribute(searchParams.get("target")) || "_blank",
);
const useHash = searchParams.get("useHash");
const csrfToken = escapeHTMLAttribute(searchParams.get("token"));
for (let library of libraries) {
const div = document.createElement("div");
div.classList.add("library");
div.setAttribute("id", library.id);
let inner = template.innerHTML;
const source = `libraries/${library.source}`;
let authorsInnerHTML = "";
inner = inner.replace(/\{libraryId\}/g, library.id);
inner = inner.replace(/\{name\}/g, library.name);
const truncate = (str) => {
if (str.length > 300) {
str = str.slice(0, 300);
return str.split(", ").slice(0, -1).join(", ") + "...";
}
return str;
};
let description = library.description || "";
if (library.itemNames) {
description += `<br/><br/><b>Items: </b> <span className="itemNames">${truncate(
library.itemNames.join(", "),
)}</span>`;
}
inner = inner.replace(/\{description\}/g, description);
inner = inner.replace(/\{source\}/g, source);
for (let author of library.authors) {
authorsInnerHTML += `<a href="${author.url}" target="_blank">@${author.name}</a> `;
}
inner = inner.replace(/\{authors\}/g, authorsInnerHTML);
inner = inner.replace(
/\{preview\}/g,
`libraries/${library.preview}?v=${library.updated || 0}`,
);
inner = inner.replace(/\{created\}/g, getDate(library.created));
if (library.created !== library.updated) {
inner = inner.replace(/\{updated\}/g, getDate(library.updated));
} else {
inner = inner.replace('<p class="updated">Updated: {updated}</p>', "");
}
inner = inner.replace(/\{appName\}/g, appName);
const libraryUrl = encodeURIComponent(
`${escapeHTMLAttribute(origin)}/${source}`,
);
inner = inner.replace(
"{addToLib}",
`${referrer}${useHash ? "#" : "?"}addLibrary=${libraryUrl}${
csrfToken ? `&token=${csrfToken}` : ""
}`,
);
inner = inner.replace("{target}", target);
inner = inner.replace(/\{total\}/g, library.downloads.total);
inner = inner.replace(/\{week\}/g, library.downloads.week);
div.innerHTML = inner;
div.setAttribute("data-version", library.version || "1");
template.after(div);
}
initImageLazyLoading();
};
const handleSort = (sortType) => {
const searchParams = new URLSearchParams(location.search);
searchParams.set("sort", sortType);
history.pushState("", "sort", `?` + searchParams.toString() + location.hash);
libraries_ = sortBy[sortType ?? "default"].func(libraries_);
populateLibraryList();
if (currSort) {
const prev = document.getElementById(currSort);
prev.classList.remove("option-selected");
}
const curr = document.getElementById(sortType);
curr?.classList.add("option-selected");
currSort = sortType;
};
const populateSorts = () => {
const sortTemplate = document.getElementById("sort-template");
for ([key, value] of Object.entries(sortBy).filter(
([key]) => key !== "default",
)) {
const spacer = document.createElement("span");
spacer.innerHTML = ` · `;
sortTemplate.before(spacer);
const el = sortTemplate.cloneNode(true);
el.setAttribute("id", key);
el.innerText = el.innerText.replace(/\{label\}/g, value.label);
el.setAttribute("href", "#");
const handler = (sort) => () => {
history.replaceState(null, null, " ");
handleSort(sort);
};
el.onclick = handler(key);
sortTemplate.before(el);
}
};
const scrollToAnchor = () => {
if (location.hash) {
const target = location.hash;
const element = document.querySelector(target);
if (element) {
window.scrollTo(0, element.offsetTop);
}
}
};
const handleTheme = (theme) => {
const searchParams = new URLSearchParams(location.search);
searchParams.set("theme", theme);
history.pushState("", "theme", `?` + searchParams.toString() + location.hash);
if (theme === "dark") {
document.querySelector("html").classList.add("theme--dark");
document.querySelector("#light").classList.remove("is-hidden");
document.querySelector("#dark").classList.add("is-hidden");
} else if (theme === "light") {
document.querySelector("#light").classList.add("is-hidden");
document.querySelector("#dark").classList.remove("is-hidden");
document.querySelector("html").classList.remove("theme--dark");
}
};
// -----------------------------------------------------------------------------
// init
// -----------------------------------------------------------------------------
// Add listeners to handle theme change
const themes = document.querySelectorAll("#theme .option");
themes.forEach((theme) =>
theme.addEventListener("click", () => handleTheme(theme.id)),
);
const urlParams = new URLSearchParams(window.location.search);
const searchInput = document.getElementById("search-input");
searchInput.addEventListener(
"input",
debounce((event) => {
populateLibraryList(event.target.value);
}, 200),
);
document.documentElement.addEventListener("keypress", (event) => {
if (
!event.altKey &&
!event.ctrlKey &&
!event.metaKey &&
/^[a-z0-9]$/i.test(event.key)
) {
if (searchInput !== document.activeElement) {
searchInput.select();
}
}
});
handleTheme(urlParams.get("theme") ?? "light");
populateSorts();
fetchJSONFile("libraries.json", (libraries) => {
fetchJSONFile("stats.json", (stats) => {
for (let library of libraries) {
const replaceText = { "/": "-", ".excalidrawlib": "" };
const libraryId = library.source
.toLowerCase()
.replace(/\/|.excalidrawlib/g, (match) => replaceText[match]);
library["id"] = libraryId;
library["downloads"] = {
total: libraryId in stats ? stats[libraryId].total : 0,
week: libraryId in stats ? stats[libraryId].week : 0,
};
libraries_.push(library);
}
const sort = urlParams.get("sort");
handleSort(sort ?? "default");
scrollToAnchor();
});
});
// update footer with current year
const footer = document.getElementById("footer");
footer.innerHTML = footer.innerHTML.replace(/{currentYear}/g, () =>
new Date().getFullYear(),
);
document.addEventListener("click", (event) => {
if (event.target.closest(".install-library")) {
const libraryItemNode = event.target.closest(".library");
const libraryVersion = parseInt(
libraryItemNode.getAttribute("data-version") || "1",
);
const referrer = urlParams.get("referrer");
const referrerVersion = parseInt(urlParams.get("version") || "1");
if (referrer && referrerVersion < libraryVersion) {
let message =
"It seems the Excalidraw editor's version is older than the library version. Installing this library may not work correctly.";
if (referrer.includes("excalidraw.com")) {
message += `\n\nTo ensure you are on the latest version, hard-reload the excalidraw.com tab (Mac: Cmd-Shift-R, Window: Ctrl-F5). If that doesn't work, ensure you only have a single excalidraw.com tab open.`;
}
window.alert(message);
}
}
});