Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
595 lines (488 loc) · 17.9 KB
/
Copy pathscript.js
File metadata and controls
595 lines (488 loc) · 17.9 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
const DATABASE_NAME = "asocial-network";
const DATABASE_VERSION = 3;
const POSTS_STORE_NAME = "posts";
const JSONL_MIME_TYPE = "application/x-ndjson";
let timestampRefreshTimeoutId = null;
let database = null;
const relativeTimeFormatter = new Intl.RelativeTimeFormat(navigator.language, {
numeric: "auto",
style: "long",
});
const absoluteTimeFormatter = new Intl.DateTimeFormat(navigator.language, {
dateStyle: "medium",
timeStyle: "short",
});
const CONTENT_URL_PATTERN = /(https?:\/\/[^\s<]+)/gu;
const TRAILING_URL_PUNCTUATION = /[),.!?:;]+$/u;
function formatRelativeWithTemporal(timestamp) {
if (!globalThis.Temporal?.Instant) {
return null;
}
let timeZone = Temporal.Now.zonedDateTimeISO().timeZoneId;
let postTime = Temporal.Instant.fromEpochMilliseconds(timestamp).toZonedDateTimeISO(timeZone);
let now = Temporal.Now.zonedDateTimeISO(timeZone);
let units = ["year", "month", "week", "day", "hour", "minute"];
for (let unit of units) {
let diff = now.since(postTime, { largestUnit: unit, smallestUnit: unit });
let value = Math.trunc(diff[`${unit}s`]);
if (value !== 0) {
return relativeTimeFormatter.format(-value, unit);
}
}
return relativeTimeFormatter.format(0, "second");
}
function formatRelativeWithDate(timestamp) {
let elapsedSeconds = Math.round((timestamp - Date.now()) / 1000);
let units = [
["year", 31_536_000],
["month", 2_592_000],
["week", 604_800],
["day", 86_400],
["hour", 3_600],
["minute", 60],
];
for (let [unit, seconds] of units) {
let value = Math.round(elapsedSeconds / seconds);
if (Math.abs(value) >= 1) {
return relativeTimeFormatter.format(value, unit);
}
}
return relativeTimeFormatter.format(0, "second");
}
function formatPostTimestamp(timestamp) {
return {
relative: formatRelativeWithTemporal(timestamp) ?? formatRelativeWithDate(timestamp),
absolute: absoluteTimeFormatter.format(timestamp),
iso: new Date(timestamp).toISOString(),
};
}
function getRelativeRefreshDelay(timestamp, now = Date.now()) {
let elapsedSeconds = Math.abs(Math.round((now - timestamp) / 1000));
if (elapsedSeconds < 60) {
return 1_000 - (now % 1_000);
}
if (elapsedSeconds < 3_600) {
return 60_000 - (now % 60_000);
}
if (elapsedSeconds < 86_400) {
return 3_600_000 - (now % 3_600_000);
}
if (elapsedSeconds < 604_800) {
return 86_400_000 - (now % 86_400_000);
}
if (elapsedSeconds < 2_592_000) {
return 604_800_000 - (now % 604_800_000);
}
if (elapsedSeconds < 31_536_000) {
return 2_592_000_000 - (now % 2_592_000_000);
}
return 31_536_000_000 - (now % 31_536_000_000);
}
function updateTimestampElement(timestampElement, timestamp) {
let formattedTimestamp = formatPostTimestamp(timestamp);
timestampElement.textContent = formattedTimestamp.relative;
timestampElement.setAttribute("title", formattedTimestamp.absolute);
timestampElement.setAttribute("datetime", formattedTimestamp.iso);
timestampElement.dataset.timestamp = String(timestamp);
}
function refreshTimestamps() {
let timestampElements = document.querySelectorAll(".timestamp[data-timestamp]");
timestampElements.forEach((timestampElement) => {
let timestamp = Number(timestampElement.dataset.timestamp);
if (!Number.isNaN(timestamp)) {
updateTimestampElement(timestampElement, timestamp);
}
});
scheduleTimestampRefresh();
}
function scheduleTimestampRefresh() {
if (timestampRefreshTimeoutId !== null) {
window.clearTimeout(timestampRefreshTimeoutId);
timestampRefreshTimeoutId = null;
}
let timestampElements = document.querySelectorAll(".timestamp[data-timestamp]");
let timestamps = Array.from(timestampElements, (timestampElement) => Number(timestampElement.dataset.timestamp))
.filter((timestamp) => !Number.isNaN(timestamp));
if (timestamps.length === 0) {
return;
}
let now = Date.now();
let nextRefreshDelay = Math.min(...timestamps.map((timestamp) => getRelativeRefreshDelay(timestamp, now)));
timestampRefreshTimeoutId = window.setTimeout(refreshTimestamps, Math.max(250, nextRefreshDelay));
}
function displayError(error) {
let errorTemplate = document.getElementById("errorTemplate");
let errorElement = errorTemplate.content.cloneNode(true);
let errorDialog = errorElement.querySelector("dialog");
errorDialog.querySelector(".content").textContent = error;
document.body.appendChild(errorDialog);
errorDialog.showModal();
}
function openPostsStore(db, mode) {
if (!db.objectStoreNames.contains(POSTS_STORE_NAME)) {
displayError("Your local database is missing the posts store. Reloading should migrate it.");
console.error("Missing object store", Array.from(db.objectStoreNames));
return null;
}
try {
let transaction = db.transaction([POSTS_STORE_NAME], mode);
return transaction.objectStore(POSTS_STORE_NAME);
} catch (error) {
displayError("An error occurred while opening your posts.");
console.error("Error opening object store", error);
return null;
}
}
function normalizePost(post) {
let timestamp = Number(post.timestamp);
return {
...post,
content: typeof post.content === "string" ? post.content : String(post.content ?? ""),
timestamp: Number.isFinite(timestamp) ? timestamp : Date.now(),
liked: Boolean(post.liked),
minimized: Boolean(post.minimized),
};
}
function preparePostForStorage(post) {
let normalizedPost = normalizePost(post);
return {
content: normalizedPost.content,
timestamp: normalizedPost.timestamp,
liked: normalizedPost.liked,
minimized: normalizedPost.minimized,
};
}
function requestToPromise(request) {
return new Promise((resolve, reject) => {
request.addEventListener("success", () => resolve(request.result), { once: true });
request.addEventListener("error", () => reject(request.error), { once: true });
});
}
function updatePostActions(postElement, post) {
let likeButton = postElement.querySelector(".likedislike");
let minimizeButton = postElement.querySelector(".minimize");
let contentElement = postElement.querySelector(".content");
likeButton.textContent = post.liked ? "Never mind" : "Self-like";
minimizeButton.textContent = post.minimized ? "[+]" : "[-]";
contentElement.hidden = post.minimized;
postElement.dataset.liked = String(post.liked);
postElement.dataset.minimized = String(post.minimized);
}
function trimTrailingUrlPunctuation(rawUrl) {
let trimmedUrl = rawUrl;
while (TRAILING_URL_PUNCTUATION.test(trimmedUrl)) {
trimmedUrl = trimmedUrl.replace(TRAILING_URL_PUNCTUATION, "");
}
return {
url: trimmedUrl,
trailingText: rawUrl.slice(trimmedUrl.length),
};
}
function createContentFragment(content) {
let contentFragment = document.createDocumentFragment();
let lastIndex = 0;
for (let match of content.matchAll(CONTENT_URL_PATTERN)) {
let matchedUrl = match[0];
let matchIndex = match.index ?? 0;
if (matchIndex > lastIndex) {
contentFragment.append(content.slice(lastIndex, matchIndex));
}
let { url, trailingText } = trimTrailingUrlPunctuation(matchedUrl);
if (url) {
let linkElement = document.createElement("a");
linkElement.href = url;
linkElement.textContent = url;
linkElement.target = "_blank";
linkElement.rel = "noreferrer noopener";
linkElement.referrerPolicy = "no-referrer";
contentFragment.append(linkElement);
} else {
contentFragment.append(matchedUrl);
}
if (trailingText) {
contentFragment.append(trailingText);
}
lastIndex = matchIndex + matchedUrl.length;
}
if (lastIndex < content.length) {
contentFragment.append(content.slice(lastIndex));
}
return contentFragment;
}
function setPostContent(contentElement, content) {
contentElement.replaceChildren(createContentFragment(content));
}
async function savePost(post) {
let postsStore = openPostsStore(database, "readwrite");
if (!postsStore) {
throw new Error("Could not open posts store for saving.");
}
await requestToPromise(postsStore.put(post));
}
async function deletePost(postId) {
let postsStore = openPostsStore(database, "readwrite");
if (!postsStore) {
throw new Error("Could not open posts store for deletion.");
}
await requestToPromise(postsStore.delete(postId));
}
async function getAllPosts() {
let postsStore = openPostsStore(database, "readonly");
if (!postsStore) {
throw new Error("Could not open posts store for reading.");
}
let posts = await requestToPromise(postsStore.getAll());
return posts.map(normalizePost).toSorted((left, right) => right.timestamp - left.timestamp);
}
function downloadTextFile(content, fileName, mimeType) {
let blob = new Blob([content], { type: mimeType });
let downloadUrl = URL.createObjectURL(blob);
let link = document.createElement("a");
link.href = downloadUrl;
link.download = fileName;
link.hidden = true;
document.body.append(link);
link.click();
link.remove();
window.setTimeout(() => {
URL.revokeObjectURL(downloadUrl);
}, 0);
}
function serializePostsAsJsonl(posts) {
return posts
.map((post) => JSON.stringify({
content: post.content,
timestamp: post.timestamp,
liked: post.liked,
minimized: post.minimized,
}))
.join("\n");
}
function parsePostsJsonl(jsonlText) {
let lines = jsonlText
.split(/\r?\n/u)
.map((line) => line.trim())
.filter((line) => line !== "");
if (lines.length === 0) {
throw new Error("The selected file is empty.");
}
return lines.map((line, index) => {
let parsedLine;
try {
parsedLine = JSON.parse(line);
} catch (error) {
throw new Error(`Line ${index + 1} is not valid JSON.`);
}
if (typeof parsedLine !== "object" || parsedLine === null || Array.isArray(parsedLine)) {
throw new Error(`Line ${index + 1} must contain a post object.`);
}
if (typeof parsedLine.content !== "string" || parsedLine.content.trim() === "") {
throw new Error(`Line ${index + 1} is missing post content.`);
}
if (!Number.isFinite(Number(parsedLine.timestamp))) {
throw new Error(`Line ${index + 1} has an invalid timestamp.`);
}
return preparePostForStorage(parsedLine);
});
}
async function replaceAllPosts(posts) {
let transaction = database.transaction([POSTS_STORE_NAME], "readwrite");
let postsStore = transaction.objectStore(POSTS_STORE_NAME);
await requestToPromise(postsStore.clear());
for (let post of posts) {
await requestToPromise(postsStore.add(post));
}
await new Promise((resolve, reject) => {
transaction.addEventListener("complete", resolve, { once: true });
transaction.addEventListener("error", () => reject(transaction.error), { once: true });
transaction.addEventListener("abort", () => reject(transaction.error), { once: true });
});
}
async function handleDownloadClick() {
try {
let posts = await getAllPosts();
let jsonl = serializePostsAsJsonl(posts);
let dateStamp = new Date().toISOString().replaceAll(":", "-");
downloadTextFile(jsonl, `asocial-network-${dateStamp}.jsonl`, JSONL_MIME_TYPE);
} catch (error) {
displayError("An error occurred while downloading your posts.");
console.error("Error downloading posts", error);
}
}
async function handleRestoreFileChange(event) {
let restoreInput = event.target;
let file = restoreInput.files?.[0];
if (!file) {
return;
}
try {
let fileContent = await file.text();
let posts = parsePostsJsonl(fileContent);
if (!window.confirm(`Restore ${posts.length} posts? This replaces your current local posts.`)) {
return;
}
await replaceAllPosts(posts);
loadPosts(database);
} catch (error) {
displayError(error instanceof Error ? error.message : "An error occurred while restoring your posts.");
console.error("Error restoring posts", error);
} finally {
restoreInput.value = "";
}
}
function renderPost(post, placement = "prepend") {
let postTemplate = document.getElementById("postTemplate");
let postElement = postTemplate.content.cloneNode(true);
let postContainer = postElement.querySelector(".post");
let normalizedPost = normalizePost(post);
let contentElement = postElement.querySelector(".content");
let timestampElement = postElement.querySelector(".timestamp");
postContainer.dataset.postId = String(normalizedPost.id);
setPostContent(contentElement, normalizedPost.content);
updateTimestampElement(timestampElement, normalizedPost.timestamp);
updatePostActions(postContainer, normalizedPost);
postElement.querySelector(".likedislike").addEventListener("click", async () => {
try {
normalizedPost.liked = !normalizedPost.liked;
await savePost(normalizedPost);
updatePostActions(postContainer, normalizedPost);
} catch (error) {
normalizedPost.liked = !normalizedPost.liked;
displayError("An error occurred while updating your post.");
console.error("Error updating post like state", error);
}
});
postElement.querySelector(".minimize").addEventListener("click", async () => {
try {
normalizedPost.minimized = !normalizedPost.minimized;
await savePost(normalizedPost);
updatePostActions(postContainer, normalizedPost);
} catch (error) {
normalizedPost.minimized = !normalizedPost.minimized;
displayError("An error occurred while updating your post.");
console.error("Error updating post minimized state", error);
}
});
postElement.querySelector(".delete").addEventListener("click", async () => {
if (!window.confirm("Delete this post?")) {
return;
}
try {
await deletePost(normalizedPost.id);
postContainer.remove();
scheduleTimestampRefresh();
} catch (error) {
displayError("An error occurred while deleting your post.");
console.error("Error deleting post", error);
}
});
let main = document.querySelector("main");
if (placement === "append") {
main.append(postElement);
} else {
main.prepend(postElement);
}
scheduleTimestampRefresh();
}
function loadPosts(db) {
let postsStore = openPostsStore(db, "readonly");
if (!postsStore) return;
let postsRequest = postsStore.getAll();
postsRequest.addEventListener("success", () => {
let posts = postsRequest.result
.map(normalizePost)
.toSorted((left, right) => right.timestamp - left.timestamp);
let main = document.querySelector("main");
main.replaceChildren();
posts.forEach((post) => renderPost(post, "append"));
scheduleTimestampRefresh();
});
postsRequest.addEventListener("error", (event) => {
displayError("An error occurred while loading your posts.");
console.error("Error loading posts", event);
});
}
function migratePosts(store) {
let cursorRequest = store.openCursor();
cursorRequest.addEventListener("success", (event) => {
let cursor = event.target.result;
if (!cursor) {
return;
}
let post = cursor.value;
let normalizedPost = normalizePost(post);
if (post.liked !== normalizedPost.liked || post.minimized !== normalizedPost.minimized) {
cursor.update(normalizedPost);
}
cursor.continue();
});
cursorRequest.addEventListener("error", (event) => {
displayError("An error occurred while migrating your posts.");
console.error("Error migrating posts", event);
});
}
document.addEventListener("DOMContentLoaded", () => {
let dbOpenRequest = window.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
dbOpenRequest.addEventListener("error", (event) => {
displayError("Failed to open database. You need a somewhat recent browser.");
console.error("Error opening database", event);
});
dbOpenRequest.addEventListener("upgradeneeded", (event) => {
try {
let db = event.target.result;
let transaction = event.target.transaction;
let postsStore;
if (!db.objectStoreNames.contains(POSTS_STORE_NAME)) {
postsStore = db.createObjectStore(POSTS_STORE_NAME, { keyPath: "id", autoIncrement: true });
} else {
postsStore = transaction.objectStore(POSTS_STORE_NAME);
}
if (event.oldVersion < 3) {
migratePosts(postsStore);
}
} catch (error) {
displayError("An error occurred while setting up the database.");
console.error("Error during database setup", error);
}
});
dbOpenRequest.addEventListener("success", (event) => {
database = event.target.result;
loadPosts(database);
let downloadButton = document.getElementById("download");
let postForm = document.getElementById("postForm");
let postTextarea = postForm.elements["content"];
let restoreInput = document.getElementById("restoreFile");
downloadButton.addEventListener("click", handleDownloadClick);
restoreInput.addEventListener("change", handleRestoreFileChange);
postTextarea.addEventListener("keydown", (event) => {
if (event.key === "Enter" && (event.ctrlKey || event.metaKey) && !event.altKey) {
event.preventDefault();
postForm.requestSubmit();
}
});
postForm.addEventListener("submit", (event) => {
try {
event.preventDefault();
let content = postTextarea.value;
if (content.trim() === "") return;
let post = preparePostForStorage({ content, timestamp: Date.now(), liked: false, minimized: false });
let postsStore = openPostsStore(database, "readwrite");
if (!postsStore) return;
let addPostRequest = postsStore.add(post);
addPostRequest.addEventListener("success", () => {
post.id = addPostRequest.result;
renderPost(post);
postTextarea.value = "";
postTextarea.focus();
});
addPostRequest.addEventListener("error", (requestEvent) => {
displayError("An error occurred while saving your post.");
console.error("Error saving post", requestEvent);
});
} catch (error) {
displayError("An error occurred while saving your post.");
console.error("Error saving post", error);
}
});
});
});