forked from rslashplace2/rslashplace2.github.io
-
Notifications
You must be signed in to change notification settings - Fork 1
/
posts-manager.js
248 lines (233 loc) · 7.46 KB
/
posts-manager.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
/* eslint-disable jsdoc/require-jsdoc */
/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck
// This script runs on posts.html
/** Like PublicPromise, but limits to only one task being able to await it */
class PublicPromiseSingle {
locked
resolve
reject
#promise
constructor() {
this.#promise = new Promise((resolve, reject) => {
this.resolve = resolve
this.reject = reject
})
this.locked = false
}
async acquireAwaitPromise() {
if (this.locked) {
throw new Error("This promise is already being awaited.")
}
this.locked = true
try {
const result = await this.#promise
this.locked = false
return result
}
catch (error) {
this.locked = false
throw error
}
}
}
class PostElArray {
items
constructor() {
this.items = []
}
orderedInsert(postEl, comparisonFn) {
let insertIndex = this.items.findIndex(existingItem => existingItem.post.id === postEl.post?.id)
if (insertIndex >= 0) {
this.items[insertIndex] = postEl
}
else {
insertIndex = this.items.findIndex(existingItem => comparisonFn(postEl, existingItem) < 0)
if (insertIndex === -1) {
this.items.push(postEl)
insertIndex = this.items.length - 1
}
else {
this.items.splice(insertIndex, 0, postEl)
}
}
return insertIndex
}
delete(postEl) {
this.items = this.items.filter(existingItem => existingItem.post.id !== postEl.post?.id)
}
includes(postEl) {
return this.items.some(existingItem => existingItem.post.id === postEl.post?.id)
}
getById(id) {
return this.items.find(postEl => postEl.post?.id === id)
}
clear() {
this.items.length = 0
}
}
let topUpvotes = 0
let topDate = new Date(0)
let bottomUpvotes = 0xFFFFFFFF
let bottomDate = new Date()
const postEls = new PostElArray()
const contentsBaseLength = contents.childNodes.length
const postLimit = 16
const postLoadCooldown = 1000
let postFinishedLastLoad = null
let filter = postsSortSelect.value // "upvotes" | "date"
let hideSensitive = !!postsHideSensitive.checked
function insertElementAtIndex(parentElement, newElement, index) {
const referenceElement = parentElement.childNodes[index]
if (referenceElement) {
parentElement.insertBefore(newElement, referenceElement)
}
else {
parentElement.appendChild(newElement)
}
}
async function finishPostLoadWithCd() {
await new Promise(resolve => setTimeout(resolve, postLoadCooldown))
postFinishedLastLoad.resolve()
}
async function tryLoadPosts(sortBy, paramsObject) {
paramsObject = Object.assign({limit: postLimit}, paramsObject)
const params = new URLSearchParams(paramsObject)
if (postFinishedLastLoad !== null) {
if (postFinishedLastLoad.locked) {
return false
}
await postFinishedLastLoad.acquireAwaitPromise()
}
postFinishedLastLoad = new PublicPromiseSingle()
const postsUrl = `${localStorage.auth || DEFAULT_AUTH}/posts/?${params.toString()}`
const res = await fetch(postsUrl)
if (!res.ok) {
console.error(`Failed to load top posts, status ${res.status} ${res.statusText}:`, await res.json())
await finishPostLoadWithCd()
return false
}
const postsObject = await res.json()
for (const post of postsObject.posts) {
const postDate = new Date(post.creationDate)
const existingPost = postEls.getById(post.id)
if (existingPost) { // Update the post with new data
existingPost.fromPost(post)
}
else {
const postEl = document.createElement("r-post")
postEl.fromPost(post)
if (hideSensitive && post.hasSensitiveContent) {
postEl.hidden = true
}
let comparisonFn = null
switch (sortBy) {
case "beforeDate": {
comparisonFn = (a, b) => new Date(b.post.creationDate) - new Date(a.post.creationDate)
break
}
case "sinceDate": {
comparisonFn = (a, b) => new Date(a.post.creationDate) - new Date(b.post.creationDate)
break
}
case "beforeUpvotes": {
comparisonFn = (a, b) => b.post.upvotes - a.post.upvotes
break
}
case "sinceUpvotes": {
comparisonFn = (a, b) => a.post.upvotes - b.post.upvotes
break
}
default: {
await finishPostLoadWithCd()
return false
}
}
const insertIndex = postEls.orderedInsert(postEl, comparisonFn)
insertElementAtIndex(contents, postEl, contentsBaseLength + insertIndex)
}
if (sortBy === "beforeDate" || sortBy === "sinceDate") {
if (postDate < bottomDate) {
bottomDate = postDate
}
if (postDate > topDate) {
topDate = postDate
}
}
else if (sortBy === "beforeUpvotes" || sortBy === "sincecUpvotes") {
if (post.upvotes < bottomUpvotes) {
bottomUpvotes = post.upvotes
}
if (post.upvotes > topUpvotes) {
topUpvotes = post.upvotes
}
}
}
await finishPostLoadWithCd()
return true
}
// "date" - Most recent / "upvotes" - highest upvotes
async function tryLoadTopPosts() {
if (filter == "date") {
await tryLoadPosts("sinceDate", { sinceDate: topDate.toISOString() })
}
else if (filter == "upvotes") {
await tryLoadPosts("sinceUpvotes", { sinceUpvotes: topUpvotes })
}
}
// "date" - Most old, "votes" - lowest upvotes
async function tryLoadBottomPosts() {
if (filter == "date") {
await tryLoadPosts("beforeDate", { beforeDate: bottomDate.toISOString() })
}
else if (filter == "upvotes") {
await tryLoadPosts("beforeUpvotes", { beforeUpvotes: bottomUpvotes })
}
}
async function tryLoadKeywordPosts(keyword) {
clearPosts()
let sortBy = null
let sortValue = null
if (filter == "date") {
sortBy = "beforeDate"
sortValue = bottomDate.toISOString()
}
else if (filter == "upvotes") {
sortBy = "beforeUpvotes"
sortValue = bottomUpvotes
}
if (sortBy === null || sortValue === null) {
return
}
await tryLoadPosts(sortBy, { [sortBy]: sortValue, keyword })
}
function clearPosts() {
for (const postEl of postEls.items) {
if (contents.contains(postEl)) {
contents.removeChild(postEl)
}
}
postEls.clear()
topUpvotes = 0
topDate = new Date(0)
bottomUpvotes = 0xFFFFFFF
bottomDate = new Date()
}
postsSortSelect.addEventListener("change", function() {
filter = postsSortSelect.value
clearPosts()
tryLoadBottomPosts()
})
postsHideSensitive.addEventListener("change", function() {
hideSensitive = !!postsHideSensitive.checked
if (hideSensitive) {
for (const postEl of postEls.items) {
postEl.hidden = postEl.post.hasSensitiveContent
}
}
else {
for (const postEl of postEls.items) {
postEl.hidden = false
}
}
})