-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
417 lines (359 loc) · 13.2 KB
/
main.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
const siteConfigs = {
"oldReddit": {
"site": "oldReddit",
"enabled": oldRedditEnabled,
"usernameSelector": ".author",
"detailsPlacement": function (el) { return el.parentNode },
"detailsStyle": "",
"linkStyle": "",
"postProcess": function (el, dp) { return },
"delay": 1000,
"interval": 4000
},
"newReddit": {
"site": "newReddit",
"enabled": newRedditEnabled,
"usernameSelector": "[noun='comment_author'] a",
"detailsPlacement": function (el) { return el.parentNode.parentNode.parentNode.parentNode },
"detailsStyle": "font-size:.75rem;color:var(--color-neutral-content-weak);",
"linkStyle": "",
"postProcess": function (el, dp) { dp.innerHTML += `<style>time:first-child{display:none}</style>` },
"delay": 1000,
"interval": 4000
},
"kbin": {
"site": "kbin",
"enabled": kbinEnabled,
"usernameSelector": "a.user-inline",
"detailsPlacement": function(el) { return el.parentNode },
"detailsStyle": "font-family: Noto Sans,Arial,sans-serif; font-size:12px; line-height:18px;",
"linkStyle": "",
"delay": 1000,
"interval": false
}
};
// set settings for current site
let config = siteConfigs.newReddit;
let url = window.location.href;
if (url.includes("old.reddit")) {
config = siteConfigs.oldReddit;
}
if (url.includes("kbin.social")) {
config = siteConfigs.kbin;
}
if (extensionEnabled && config.enabled) {
window.onload = run();
}
async function run() {
if (config.site == "kbin" && kbinEnabled) {
loadKbinUpgrades();
}
if (dootCountEnabled || profilesEnabled) {
let data = await loadData();
let doots = data["doots"];
let profiles = data["profiles"];
// delay to let comments load
setTimeout(() => {
showDetails(doots, profiles)
}, config.delay);
// continously update to include newly loaded comments
if (config.interval) {
setInterval(() => {
showDetails(doots, profiles);
}, config.interval);
}
}
}
// load doot count and profile data
function loadData() {
let data;
if (localStorage.getItem("ethfinance-buddy") === null) {
data = getData();
} else {
data = JSON.parse(localStorage.getItem("ethfinance-buddy"));
if (data["expirationTime"] < Date.now()) {
data = getData();
}
}
return data; // object
}
// fetch doot count and profile data
async function getData() {
let data = {};
let dootsUrl = "https://dailydoots.com/doots.json";
let profilesUrl = "https://dailydoots.com/profiles.json";
const [dootsRes, profilesRes] = await Promise.all([
fetch(dootsUrl),
fetch(profilesUrl)
]);
doots = await dootsRes.json();
profiles = await profilesRes.json();
let currentTime = Date.now(); // epoch in milliseconds
let expirationTime = currentTime + 3600000; // data expires after an hour
data["doots"] = doots;
data["profiles"] = profiles;
data["expirationTime"] = expirationTime;
localStorage.setItem("ethfinance-buddy", JSON.stringify(data));
return data; // object
}
// show user doot count and profiles
function showDetails(doots, profiles) {
// console.log(document.querySelectorAll(config.usernameSelector).length);
document.querySelectorAll(config.usernameSelector).forEach(element => {
if (element.getAttribute('data-eb-details') == "true") {
// already set, do nothing
} else {
element.setAttribute("data-eb-details", "true");
let username = element.innerText.toLowerCase();
let detailsPlacement = config.detailsPlacement(element);
let detailsStyle = config.detailsStyle;
let separator = " •";
let dootDetails = "";
let profileDetails = "";
if (dootCountEnabled) {
let dootsObj = doots.filter(entry => entry["username"].toLowerCase() == username);
let dootCount = dootsObj[0] ? dootsObj[0]["doots"] : "0";
let heart = `🤍`;
let plural = (dootCount == "1") ? "" : "s";
dootDetails = (dootCount == "0") ? "" : `${separator} ${heart} ${dootCount} doot${plural}`;
}
if (profilesEnabled) {
let profileObj = profiles.filter(entry => entry["Username"].toLowerCase() == `${username}`);
let profile = profileObj[0] ? profileObj[0]["Description"] : "";
// replace the linebreaks with |
profile = profile.replace(/(?:\r\n|\r|\n)/g, ' | ');
// convert markdown links to html
let links = profile.match(/\[.*?\)/g);
if (links != null && links.length > 0) {
for (link of links) {
let linkText = link.match(/\[(.*?)\]/)[1];
let linkUrl = link.match(/\((.*?)\)/)[1];
profile = profile.replace(link,
`<u><a href="${linkUrl}" target="_blank" style="${config.linkStyle}">${linkText}</a></u>`);
}
}
profileDetails = (profile == "") ? "" : `${separator} ${profile}`;
}
detailsPlacement.innerHTML += `<span style="${detailsStyle}">${dootDetails}${profileDetails}</span>`;
config.postProcess(element, detailsPlacement);
}
});
}
// load kbin features
function loadKbinUpgrades() {
kbinSortNew();
kbinCommentTop();
kbinCollapsibleComments();
kbinCommentHighlight();
kbinNewTabLinks();
}
// sort comments by new as default
function kbinSortNew() {
if (kbinSortNewEnabled) {
document.querySelector("#options .options__main li a").href += "/hot";
let url = document.location.href;
let filterSpecified = url.includes("/hot") || url.includes("/active") || url.includes("/newest") || url.includes("/oldest");
if (!filterSpecified && url.includes("/m/")) {
if (url.includes("#")) {
document.location.href = url.split("#").join("/newest#");
} else {
document.location.href += "/newest";
}
}
}
}
// bring the comment box to the top of the comments
function kbinCommentTop() {
if (kbinCommentTopEnabled) {
'use strict';
var container = document.querySelector("#content");
var comment_form = document.querySelector("#content > div#comment-add");
var comments_block = document.querySelector("#content > div#comments");
container.insertBefore(comment_form, comments_block);
}
}
// make comments collapsible
function kbinCollapsibleComments() {
if (kbinCollapsibleCommentsEnabled) {
'use strict';
const COLLAPSE_PARENTS_BY_DEFAULT = false;
const isMobileUser = function () {
if (navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)) {
return true;
} else {
return false;
}
};
const getNumericId = function (comment) {
return comment.id.split("-").reverse()[0];
};
const getComment = function (numericId) {
return document.querySelector('#comments blockquote#entry-comment-' + numericId);
};
const getChildrenOf = function (numericId) {
return document.querySelectorAll('#comments blockquote[data-subject-parent-value="' + numericId + '"]');
}
const getDescendentsOf = function (numericId) {
var parent = getComment(numericId);
var children = getChildrenOf(numericId);
var descendents = [];
children.forEach(function (child) {
descendents.push(child);
var childDescendents = getDescendentsOf(getNumericId(child));
childDescendents.forEach (function (cd) {
descendents.push(cd);
});
});
return descendents;
};
const makeCollapseLabel = function (isVisible, childrenCount) {
var upDown = (isVisible ? '<i class="fa-solid fa-chevron-up"></i>' : '<i class="fa-solid fa-chevron-down"></i>');
if (!isMobileUser()) {
var label = (isVisible ? ' hide ' : ' show ')
return (childrenCount > 0 ?
(label + ' [' + childrenCount + '] ' + upDown) :
(label + upDown)
);
} else {
return upDown;
}
};
window.toggleChildren = function (numericId) {
var parent = getComment(numericId);
// get visibility status
var childrenVisible = (parent.dataset['childrenVisible'] === 'true');
var toggledStatus = !childrenVisible;
// update dataset
parent.setAttribute('data-children-visible', toggledStatus);
if (!COLLAPSE_PARENTS_BY_DEFAULT) {
var figure = parent.querySelector('figure');
var footer = parent.querySelector('footer');
var content = parent.querySelector('.content');
var more = parent.querySelector('.more');
if (toggledStatus) {
content.style.display = '';
footer.style.display = '';
figure.style.display = '';
parent.style.height = '';
if (more) { more.style.display = ''; }
} else {
content.style.display = 'none';
footer.style.display = 'none';
figure.style.display = 'none';
parent.style.height = '43px';
parent.style.paddingTop = '0.53rem';
if (more) { more.style.display = 'none'; }
}
}
// toggle visibility of the descendents
var descendents = getDescendentsOf(numericId);
descendents.forEach(function(c) {
c.style.display = (toggledStatus ? 'grid' : 'none');
});
// update the link text
var childrenCount = parent.dataset['childrenCount'];
var button = document.querySelector('#comment-'+numericId+'-collapse-button');
console.debug(button);
button.innerHTML = makeCollapseLabel(toggledStatus, childrenCount);
};
const comments = document.querySelectorAll('#comments blockquote.comment');
comments.forEach(function (comment) {
var numericId = getNumericId(comment);
var children = getChildrenOf(numericId);
var childrenCount = children.length;
// add some metadata
comment.setAttribute('data-children-visible', true);
comment.setAttribute('data-children-count', childrenCount);
var header = comment.querySelector('header');
header.style.height = '40px';
header.style.textWrap = 'nowrap';
header.style.textOverflowX = 'ellipsis';
header.style.overflowX = 'hidden';
header.style.display = 'inline-flex';
var content = comment.querySelector('.content');
var footer = comment.querySelector('footer');
var timeAgo = comment.querySelector('.timeago');
timeAgo.style.overflow = 'hidden';
var elements = [header];
if (isMobileUser()) {
elements.push(content);
}
var toggleFn = function(ev) {
ev.stopPropagation();
window.toggleChildren(numericId);
return false;
};
elements.forEach(function (it) {
if (it) {
it.addEventListener('click', toggleFn);
it.style.cursor = 'pointer';
}
});
// Create the collapse/expand button
var button = document.createElement("a");
button.id = 'comment-'+numericId+'-collapse-button';
button.innerHTML = makeCollapseLabel(true, childrenCount);
button.style.cursor = "pointer";
button.style.marginLeft = "0.5rem";
header.appendChild(button);
});
if (COLLAPSE_PARENTS_BY_DEFAULT) {
comments.forEach(function (comment) {
var numericId = getNumericId(comment);
var isTopLevel = (typeof comment.dataset['subject-parent-value'] !== 'string');
if (isTopLevel) {
window.toggleChildren(numericId);
}
});
}
}
}
// opens links in new tabs
function kbinNewTabLinks() {
if (kbinNewTabLinksEnabled) {
document.querySelectorAll('.comment .content a').forEach(el => {
// if (el.href.indexOf('kbin.social') == -1 && el.href.slice(0,1) != '/') {
// if (el.href.slice(0,1) != '/') {
el.target = "_blank";
// }
});
}
}
// highlight linked comment
function kbinCommentHighlight() {
if (kbinCommentHighlightEnabled) {
'use strict';
// Get page url
let url = window.location.href;
let bgcolor = "";
// Get theme from body classes
let theme = document.body.classList[0];
if (theme == "theme--kbin" || theme == "theme--dark") {
// Dark green background color
bgcolor = "#2b4b34";
} else if (theme == "theme--solarized-dark") {
bgcolor = "#073642"
} else {
// Light green background color
bgcolor = "#d0e8d6";
}
// Get comment anchor id from url
let comment = url.split("#")[1];
// Check if comment anchor id exists
if (comment && comment !="settings") {
// Get comment element
let commentElement = document.getElementById(comment);
// Scroll to comment
commentElement.scrollIntoView();
window.scrollBy(0, -50); // Account for header
// Give comment a background
commentElement.style.backgroundColor = bgcolor;
}
}
}