-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
349 lines (332 loc) · 9.79 KB
/
Copy pathcontent.js
File metadata and controls
349 lines (332 loc) · 9.79 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
;(function () {
/** Default extension settings keys and values */
const defaultSettings = {
delaySeconds: 10,
enabled: false,
scrollEnabled: false,
scrollIntervalSeconds: 5
}
/** CSS selector for like button in timeline */
const likeButtonSelector = '[data-testid="like"]'
/** Browser or Chrome runtime API */
const runtime = typeof browser !== 'undefined' ? browser.runtime : chrome.runtime
/** Browser or Chrome storage API */
const storage = typeof browser !== 'undefined' ? browser.storage : chrome.storage
/** Local storage area for extension settings */
const local = storage.local
/** Runtime state for delay, intervals, timers, queue, observer */
let delayMs = 10000
let enabled = false
let observer = null
let queue = []
let queued = new WeakSet()
let queueTimer = null
let scrollEnabled = false
let scrollIntervalMs = 5000
let scrollTimer = null
/**
* Clamp milliseconds to min-max range.
* @description Returns value bounded by min and max milliseconds.
* @param valueMs - Value in milliseconds
* @param minMs - Minimum milliseconds
* @param maxMs - Maximum milliseconds
* @returns Clamped value in milliseconds
*/
function clampMs(valueMs, minMs, maxMs) {
return Math.max(minMs, Math.min(maxMs, valueMs))
}
/**
* Check if element can scroll vertically.
* @description Has overflow scroll/auto and content taller than view.
* @param element - DOM element to test
* @returns True when element is scrollable
*/
function isScrollable(element) {
if (!element || element.nodeType !== 1) {
return false
}
const computedStyle = getComputedStyle(element)
const overflowY = computedStyle.overflowY
return (
(overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'overlay') &&
element.scrollHeight > element.clientHeight
)
}
/**
* Detect X/Twitter home timeline page.
* @description Path /home and host x.com or twitter.com.
* @returns True when on home page
*/
function isHomePage() {
const locationPath = location.pathname
const locationHost = location.hostname
return (
(locationPath === '/home' || locationPath.startsWith('/home?')) &&
(locationHost === 'x.com' ||
locationHost === 'www.x.com' ||
locationHost === 'twitter.com' ||
locationHost === 'www.twitter.com')
)
}
/**
* Apply stored settings to module state.
* @description Writes each defined key into module state.
* @param storedItems - Storage result with delay, enabled, scroll keys
*/
function applySettings(storedItems) {
if (storedItems.delaySeconds !== undefined) {
delayMs = clampMs(storedItems.delaySeconds * 1000, 1000, 10000)
}
if (storedItems.enabled !== undefined) {
enabled = !!storedItems.enabled
}
if (storedItems.scrollEnabled !== undefined) {
scrollEnabled = !!storedItems.scrollEnabled
}
if (storedItems.scrollIntervalSeconds !== undefined) {
scrollIntervalMs = clampMs(storedItems.scrollIntervalSeconds * 1000, 2000, 15000)
}
}
/**
* Find first scrollable descendant.
* @description Recursively checks element then children for scrollable.
* @param element - Root DOM element to search
* @returns Scrollable element or null
*/
function findScrollable(element) {
if (!element || element.nodeType !== 1) {
return null
}
if (isScrollable(element)) {
return element
}
for (let childIndex = 0; childIndex < element.children.length; childIndex++) {
const scrollableChild = findScrollable(element.children[childIndex])
if (scrollableChild) {
return scrollableChild
}
}
return null
}
/**
* Resolve scroll container for timeline.
* @description Prefers primaryColumn scrollable, else document root.
* @returns Scrollable container element or null
*/
function getScrollContainer() {
const primaryColumn = document.querySelector('[data-testid="primaryColumn"]')
if (primaryColumn) {
const scrollableInside = findScrollable(primaryColumn)
if (scrollableInside) {
return scrollableInside
}
let currentElement = primaryColumn.parentElement
while (currentElement && currentElement !== document.body) {
if (isScrollable(currentElement)) {
return currentElement
}
currentElement = currentElement.parentElement
}
}
const rootElement = document.scrollingElement || document.documentElement
return rootElement.scrollHeight > rootElement.clientHeight ? rootElement : null
}
/**
* Perform one smooth scroll step.
* @description Scrolls window or timeline container by fixed amount.
*/
function doScroll() {
const scrollAmount = 500
const scrollOptions = { top: scrollAmount, behavior: 'smooth' }
const scrollContainer = getScrollContainer()
if (!scrollContainer) {
window.scrollBy(scrollOptions)
return
}
if (
scrollContainer === document.documentElement ||
scrollContainer === document.body ||
scrollContainer === document.scrollingElement
) {
window.scrollBy(scrollOptions)
} else {
const targetTop = Math.min(
scrollContainer.scrollHeight - scrollContainer.clientHeight,
scrollContainer.scrollTop + scrollAmount
)
scrollContainer.scrollTo({ top: targetTop, behavior: 'smooth' })
}
}
/**
* Start periodic auto-scroll timer.
* @description Clears old timer then sets interval from scrollIntervalMs.
*/
function startScroll() {
stopScroll()
scrollTimer = setInterval(() => {
if (scrollEnabled) {
doScroll()
}
}, scrollIntervalMs)
}
/**
* Stop auto-scroll interval.
* @description Clears scroll timer and resets handle.
*/
function stopScroll() {
if (scrollTimer) {
clearInterval(scrollTimer)
scrollTimer = null
}
}
/**
* Write current queue length to storage.
* @description Lets popup show queue stat without messaging.
*/
function syncQueueLength() {
local.set({ queueLength: queue.length })
}
/**
* Process next like button in queue.
* @description Shifts one button, clicks if valid, reschedules or clears.
*/
function processQueue() {
if (queue.length === 0) {
queueTimer = null
local.set({ queueLength: 0 })
return
}
const likeButton = queue.shift()
syncQueueLength()
if (
likeButton &&
document.contains(likeButton) &&
likeButton.getAttribute('data-testid') === 'like'
) {
likeButton.click()
}
queueTimer = setTimeout(processQueue, delayMs)
}
/**
* Queue like button for delayed click.
* @description Skips invalid or queued; pushes and starts processor.
* @param likeButtonEl - Like button element
*/
function scheduleLike(likeButtonEl) {
if (
!likeButtonEl ||
likeButtonEl.getAttribute('data-testid') !== 'like' ||
queued.has(likeButtonEl)
) {
return
}
queued.add(likeButtonEl)
queue.push(likeButtonEl)
syncQueueLength()
if (!queueTimer) {
queueTimer = setTimeout(processQueue, delayMs)
}
}
/**
* Queue like buttons under root element.
* @description Queries likeButtonSelector and schedules each if enabled.
* @param root - Container to search (defaults to body)
*/
function scanLikeButtons(root) {
if (!enabled) {
return
}
const scanTarget = root || document.body
if (!scanTarget) {
return
}
const likeButtons = scanTarget.querySelectorAll(likeButtonSelector)
likeButtons.forEach(likeButtonEl => scheduleLike(likeButtonEl))
}
/**
* Start observer for new like buttons.
* @description Observes body subtree and scans added nodes.
*/
function startObserving() {
if (observer) {
return
}
observer = new MutationObserver(mutationsList => {
for (const mutationRecord of mutationsList) {
if (mutationRecord.addedNodes.length) {
mutationRecord.addedNodes.forEach(addedNode => {
if (addedNode.nodeType === 1) {
scanLikeButtons(addedNode)
}
})
}
}
})
observer.observe(document.body, { childList: true, subtree: true })
scanLikeButtons()
}
/**
* Stop observer and clear like queue.
* @description Disconnects MutationObserver and clears queue timer.
*/
function stopObserving() {
if (observer) {
observer.disconnect()
observer = null
}
if (queueTimer) {
clearTimeout(queueTimer)
queueTimer = null
}
queue = []
local.set({ queueLength: 0 })
}
/**
* Load settings and start features.
* @description Gets settings from storage; starts observers and timers.
*/
function init() {
local.get(defaultSettings, storedItems => {
applySettings(storedItems)
if (enabled) {
startObserving()
}
if (scrollEnabled) {
startScroll()
}
})
}
/**
* Reapply settings on storage change.
* @description Fetches storage then applySettings and start/stop timers.
* @param storageChanges - Map of key to { oldValue, newValue }
* @param areaName - Storage area; we only handle local
*/
runtime.onMessage.addListener(msg => {
if (msg && msg.type === 'X_BOOST_DO_REFRESH' && isHomePage()) {
location.reload()
}
})
storage.onChanged.addListener((_storageChanges, areaName) => {
if (areaName !== 'local') {
return
}
local.get(defaultSettings, storedItems => {
applySettings(storedItems)
if (enabled) {
startObserving()
} else {
stopObserving()
}
stopScroll()
if (scrollEnabled) {
startScroll()
}
})
})
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init)
} else {
init()
}
})()