-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex-newsfeed.js
More file actions
192 lines (158 loc) · 5.65 KB
/
index-newsfeed.js
File metadata and controls
192 lines (158 loc) · 5.65 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
const newsFeed = document.getElementById("news-feed");
const newsList = document.getElementById("news-list");
/** @type {HTMLButtonElement} */
const newsFeedRight = document.getElementById("news-feed-right");
/** @type {HTMLTemplateElement} */
const newsItemTemplate = document.getElementById("news-item-template");
const timeAgoFormatter = new Intl.RelativeTimeFormat(undefined, {
style: "short",
numeric: "auto",
});
async function main() {
newsFeedRight.addEventListener("click", () => {
if (newsFeedRight.dataset.last == "true") {
newsFeedRight.dataset.last = false;
newsList.scrollTo({ left: 0 });
return;
}
const currentItem = currentItemInNewsList();
const nextItem = currentItem?.nextElementSibling;
newsList.scrollTo({ left: nextItem.offsetLeft });
updateNewsFeedRightButton();
});
newsList.addEventListener("scroll", () => {
updateNewsFeedRightButton();
});
await fetchNewsFeed();
}
// updateNewsFeedRightButton updates the news feed right button's
// dataset properties.
function updateNewsFeedRightButton() {
const isScrollEnd =
newsList.scrollLeft + newsList.clientWidth >= newsList.scrollWidth;
const currentItem = currentItemInNewsList();
const nextItem = currentItem?.nextElementSibling;
newsFeedRight.dataset.last = !nextItem || isScrollEnd;
}
// currentItemInNewsList returns the currently shown item in the news feed,
// defined by the scroll position of the newsList. If the scroll position
// is at the end of the list, it returns null.
function currentItemInNewsList() {
const scrollLeft = newsList.scrollLeft;
const children = [...newsList.children];
return children.find((item) => item.offsetLeft >= scrollLeft);
}
// fetchNewsFeed fetches the news feed from the server and appends them to
// newsList.
async function fetchNewsFeed(afterID = null) {
newsFeed.querySelector(".error")?.remove();
newsList.replaceChildren();
try {
const query = afterID ? `?after=${afterID}` : "";
const response = await fetch(`/news.json?${query}`, {
headers: { "Accept": "application/json" },
credentials: "omit",
});
if (!response.ok) {
throw new Error(`http: ${response.status} ${response.statusText}`);
}
const feed = await response.json();
const newsItems = feed.map((item) =>
createNewsItem({
id: item.id,
createdAt: item.created_at,
editedAt: item.edited_at,
username: item.author.username,
content: item.content,
thumbnailURL: item.thumbnail_url,
thumbnailURLSmall: item.thumbnail_url_small,
tracTicketID: item.trac_ticket_id,
})
);
newsList.append(...newsItems);
newsFeed.dataset.initial = false;
newsFeed.dataset.error = false;
} catch (err) {
console.error("Error fetching news feed:", err);
newsFeed.append(createError({
thing: "news feed",
message: `${err}`
}));
newsFeed.dataset.error = true;
}
}
function createNewsItem({
id,
createdAt,
editedAt,
username,
content,
thumbnailURL,
thumbnailURLSmall,
tracTicketID,
}) {
const newsItem = newsItemTemplate.content.firstElementChild.cloneNode(true);
newsItem.id = `news-${id}`;
elem(newsItem, ".news-username", username);
elem(newsItem, ".news-avatar").alt = `${username}'s avatar`;
elem(newsItem, ".news-avatar").src =
`https://members.devhack.net/user/avatar/${username}`;
elem(newsItem, ".news-created-time", createdAgoString(createdAt));
elem(newsItem, ".news-created-time").dateTime = createdAt;
elem(newsItem, ".news-created-time").title = createdAtTimestamp(createdAt);
elem(newsItem, ".news-content", linkAndEscape(content), true);
if (editedAt) {
elem(newsItem, ".news-edited").title = createdAtTimestamp(editedAt);
} else {
elem(newsItem, ".news-edited").setAttribute("hidden", "");
elem(newsItem, ".news-edited").setAttribute("aria-hidden", "true");
}
if (thumbnailURL) {
elem(newsItem, ".news-thumbnail-link").href = thumbnailURL;
elem(newsItem, ".news-thumbnail-link").target = "_blank";
elem(newsItem, ".news-thumbnail-image").src = thumbnailURLSmall ??
thumbnailURL;
elem(newsItem, ".news-thumbnail-image").alt = `thumbnail image for post`;
}
if (tracTicketID) {
elem(newsItem, ".news-trac-ticket-id", `#${tracTicketID}`);
elem(newsItem, ".news-trac-ticket-id").target = "_blank";
elem(newsItem, ".news-trac-ticket-id").href =
`https://bugs.devhack.net/ticket/${tracTicketID}`;
}
return newsItem;
}
function createdAgoString(createdAt) {
const now = new Date();
const createdAtDate = new Date(Date.parse(createdAt));
const diffMs = createdAtDate - now; // Negative for past dates
// Convert to various time units. The following calculates are just heuristics
// and are not accurate for all months/years. This is fine because it is just
// a human-readable approximation.
const diffHours = diffMs / (1000 * 60 * 60);
const diffDays = diffHours / 24;
const diffMonths = diffDays / 30;
const diffYears = diffDays / 365;
if (Math.abs(diffYears) >= 1) {
return timeAgoFormatter.format(Math.round(diffYears), "year");
}
if (Math.abs(diffMonths) >= 1) {
return timeAgoFormatter.format(Math.round(diffMonths), "month");
}
if (Math.abs(diffDays) >= 1) {
return timeAgoFormatter.format(Math.round(diffDays), "day");
}
return timeAgoFormatter.format(Math.round(diffHours), "hour");
}
function createdAtTimestamp(createdAt) {
const createdAtDate = new Date(Date.parse(createdAt));
return createdAtDate.toLocaleString(undefined, {
weekday: "long",
month: "numeric",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "numeric",
});
}
main();