-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.js
454 lines (390 loc) · 12.9 KB
/
content.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
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
class TimeMachine {
constructor() {
console.log("Thanks for using the TimeMachine! 🚀");
console.log(
"You can follow me on X at @annedevj and tag me on your first ever tweets!"
);
this.username = null;
this.joinDate = null;
this.createSidebar();
this.createButtons();
this.setupPageChangeListeners();
}
getUsername() {
if (this.username === undefined || this.username === null) {
this.username = this.computeUsername();
}
return this.username;
}
getJoinDate() {
if (this.joinDate === undefined || this.joinDate === null) {
this.joinDate = this.computeJoinDate();
}
return this.joinDate;
}
computeUsername() {
const titleTag = document.querySelector("title");
if (titleTag) {
const titleText = titleTag.textContent;
const matchProfile = titleText.match(/@(\w+)/);
const matchSearch = titleText.match(/from:(\w+)\+since/);
const match = matchProfile
? matchProfile[1]
: matchSearch
? matchSearch[1]
: null;
if (match) {
localStorage.setItem("username", match);
return match;
}
}
if (localStorage.getItem("username") !== null) {
return localStorage.getItem("username");
}
const usernameData = document.querySelector("#profile-info");
if (usernameData) {
return usernameData.getAttribute("data-username");
}
return null; // Return null if no valid handle is found
}
computeJoinDate() {
const joinDateElement = document.querySelector(
'span[data-testid="UserJoinDate"]'
);
if (joinDateElement) {
const joinDateText = joinDateElement.innerHTML;
const match = joinDateText.match(/Joined (\w+) (\d{4})/);
if (match) {
const month = match[1];
const year = match[2];
const joinDate = dayjs(Date.parse(`${month} 1, ${year}`));
localStorage.setItem("joinDate", joinDate);
return joinDate;
}
}
if (localStorage.getItem("joinDate") !== null) {
return dayjs(localStorage.getItem("joinDate"));
}
return null;
}
constructSearchQuery(startDate, endDate) {
const startDateString = startDate.format("YYYY-MM-DD");
const endDateString = endDate.format("YYYY-MM-DD");
const query = `from:${this.username}+since:${startDateString}+until:${endDateString}`;
return `https://x.com/search?q=${encodeURIComponent(
query
)}&src=typed_query&f=live`;
}
getTimeFromNow(date) {
const now = new Date();
const diff = now.valueOf() - date.valueOf();
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const weeks = Math.floor(days / 7);
const months = Math.floor(days / 30.4375);
const years = Math.floor(days / 365.25);
if (seconds < 60) {
return `${seconds} seconds ago`;
} else if (minutes < 60) {
return `${minutes} minutes ago`;
} else if (hours < 24) {
return `${hours} hours ago`;
} else if (days < 7) {
return `${days} days ago`;
} else if (weeks < 4) {
return `${weeks} weeks ago`;
} else if (months < 12) {
return `${months} months ago`;
} else {
return `${years} years ago`;
}
}
toggleSidebar() {
const isSidebarOpen = localStorage.getItem("sidebarOpen") === "true";
const isSearchOrProfilePage =
window.location.pathname === "/search" || this.getUsername() !== null;
if (isSidebarOpen && isSearchOrProfilePage) {
this.sidebar.style.display = "block";
this.openButton.style.display = "none";
this.closeButton.style.display = "block";
} else {
this.sidebar.style.display = "none";
this.openButton.style.display = "block";
this.closeButton.style.display = "none";
}
this.addInfoToSidebar();
}
createSidebar() {
const sidebar = document.createElement("div");
sidebar.id = "first-tweet-sidebar";
sidebar.innerHTML =
'<div class="header-container"><h2 id="main-header">Welcome to the time machine!</h2><div id="profile-info"></div></div><div id="first-tweet-content"></div>';
document.body.appendChild(sidebar);
this.sidebar = sidebar;
const sidebarContent = document.getElementById("first-tweet-content");
this.sidebarContent = sidebarContent;
}
createButtons() {
const button = document.createElement("button");
button.id = "first-tweet-button";
button.textContent = "Time Machine ⏳";
document.body.appendChild(button);
this.openButton = button;
const closeButton = document.createElement("button");
closeButton.id = "close-button";
closeButton.textContent = "X";
document.body.appendChild(closeButton);
this.closeButton = closeButton;
button.addEventListener("click", async () => {
localStorage.setItem("sidebarOpen", true);
this.toggleSidebar();
});
closeButton.addEventListener("click", () => {
localStorage.setItem("sidebarOpen", false);
this.toggleSidebar();
});
this.toggleSidebar();
}
addInfoToSidebar() {
this.appendProfileInfo();
this.fillSearchRanges();
this.fillSearchMonths();
this.fillAboutMe();
}
appendProfileInfo() {
if (this.profileInfo === true) {
return;
}
const targetElement = document.getElementById("profile-info");
if (!this.username || !this.joinDate) {
targetElement.textContent =
"Unable to find a username or join date. Make sure you're on a profile page and try again.";
this.profileInfo = false;
} else {
targetElement.dataset.username = this.username;
targetElement.innerHTML = `<p>@${
this.username
}</p><p>Joined ${this.getTimeFromNow(this.joinDate)}</p>`;
this.profileInfo = true;
}
if (this.resetProfileButton) {
this.resetProfileButton.remove();
this.resetProfileButton = null;
}
const resetProfileButton = document.createElement("button");
resetProfileButton.id = "reset-button";
resetProfileButton.textContent = "Fetch profile again";
targetElement.insertAdjacentElement("afterend", resetProfileButton);
resetProfileButton.addEventListener("click", (e) => {
e.preventDefault();
resetProfileButton.textContent = "Fetched!";
setTimeout(() => {
resetProfileButton.textContent = "Fetch profile again";
}, 2000);
this.reset();
});
this.resetProfileButton = resetProfileButton;
}
fillSearchRanges() {
if (this.searchRangesOptions || this.profileInfo === false) {
return;
}
const searchRangesOptionsData = [
{ months: 1, name: "First month" },
{ months: 3, name: "First 3 months" },
{ months: 6, name: "First 6 months" },
{ months: 12, name: "First year" },
{ months: 24, name: "First 2 years" },
{ months: 36, name: "First 3 years" },
{ months: 60, name: "First 5 years" },
{ months: null, name: "All time" },
];
const searchRangesOptions = document.createElement("div");
searchRangesOptions.id = "search-ranges";
this.sidebarContent.appendChild(searchRangesOptions);
this.searchRangesOptions = searchRangesOptions;
this.searchRangesOptions.innerHTML +=
'<h3 class="header">Choose a time range to view tweets from:</h3>';
this.searchRangesOptions.innerHTML += `
<div class="search-ranges">
<ul id="search-ranges-list">
${searchRangesOptionsData
.map((range) => {
let months = range.months;
let endDate = months
? this.joinDate.add(parseInt(months), "month")
: dayjs();
if (endDate.isAfter(dayjs())) {
return;
}
let url = this.constructSearchQuery(this.joinDate, endDate);
let activeLink = url === window.location.href ? "active" : "";
return `
<li>
<a href="${url}" class="range-link ${activeLink}" data-months="${range.months}">${range.name}</a>
</li>
`;
})
.join("")}
</ul>
</div>
`;
// Add event listeners to range links
document.querySelectorAll(".range-link").forEach((link) => {
link.addEventListener("click", (e) => {
e.preventDefault();
window.location.href = e.target.href;
});
});
}
fillSearchMonths() {
if (this.searchMonthsOptions || this.profileInfo === false) {
return;
}
const searchMonthsOptions = document.createElement("div");
searchMonthsOptions.id = "search-months";
this.sidebarContent.appendChild(searchMonthsOptions);
this.searchMonthsOptions = searchMonthsOptions;
const currentYear = dayjs().year();
const joinYear = this.joinDate.get("year");
const monthNames = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
this.searchMonthsOptions.innerHTML +=
'<h3 class="header">Or pick a month to search for tweets from that month:</h3>';
let yearsHtml = "";
for (let year = joinYear; year <= currentYear; year++) {
let monthsHtml = monthNames
.map((name, index) => {
let startMonth = dayjs(`${year}-${index + 1}-01`);
let endMonth = startMonth.endOf("month");
const url = this.constructSearchQuery(startMonth, endMonth);
return `<li class="month"><a href="${url}" data-year="${year}" data-month="${index}">${name}</a></li>`;
})
.join("");
yearsHtml += `
<div>
<div class="year-header">${year}</div>
<ul class="months" data-year="${year}">
${monthsHtml}
</ul>
</div>
`;
}
this.searchMonthsOptions.innerHTML += yearsHtml;
const yearHeaders = document.querySelectorAll(".year-header");
const monthDivs = document.querySelectorAll(".months");
monthDivs.forEach((div) => {
div.style.display = "none";
});
yearHeaders.forEach((header) => {
header.addEventListener("click", (_e) => {
const monthDiv = header.nextElementSibling;
monthDivs.forEach((div) => {
if (div !== monthDiv) {
div.style.display = "none";
}
});
monthDiv.style.display =
monthDiv.style.display === "block" ? "none" : "block";
});
});
setTimeout(() => {
this.openActiveYear(monthDivs);
}, 400);
}
fillAboutMe() {
if (!this.searchMonthsOptions || this.aboutMeLink) {
return;
}
const aboutMeLink = document.createElement("a");
aboutMeLink.href = "https://x.com/@annedevj";
aboutMeLink.id = "about-me";
aboutMeLink.textContent = "by @annedevj";
this.sidebarContent.appendChild(aboutMeLink);
this.aboutMeLink = aboutMeLink;
}
openActiveYear(monthDivs) {
let activeSearchYear = null;
const titleTag = document.querySelector("title");
if (titleTag) {
const titleText = titleTag.textContent;
const matchSearch = titleText.match(/since:(\d{4})\S+until:(\d{4})/);
if (matchSearch && matchSearch[1] === matchSearch[2]) {
activeSearchYear = matchSearch[1];
}
}
const matchingDiv = Array.from(monthDivs).find(
(div) => div.dataset.year === activeSearchYear
);
if (activeSearchYear && matchingDiv) {
matchingDiv.style.display = "block";
}
}
setupPageChangeListeners() {
// Listen for changes in the URL
let lastUrl = location.href;
new MutationObserver(() => {
const url = location.href;
if (url !== lastUrl) {
lastUrl = url;
this.onPageChange();
}
}).observe(document, { subtree: true, childList: true });
// Listen for clicks on profile links
document.addEventListener("click", (event) => {
const profileLink = event.target.closest('a[href^="/"]');
if (profileLink && profileLink.getAttribute("href").match(/^\/\w+$/)) {
// Wait for the page to load
setTimeout(() => this.onPageChange(), 1000);
}
});
}
onPageChange() {
this.reset();
}
reset() {
localStorage.removeItem("username");
localStorage.removeItem("joinDate");
this.profileInfo = null;
this.username = null;
this.joinDate = null;
this.getUsername();
this.getJoinDate();
if (this.searchRangesOptions) {
this.searchRangesOptions.remove();
}
this.searchRangesOptions = null;
if (this.searchMonthsOptions) {
this.searchMonthsOptions.remove();
}
this.searchMonthsOptions = null;
if (this.aboutMeLink) {
this.aboutMeLink.remove();
}
this.aboutMeLink = null;
this.addInfoToSidebar();
this.toggleSidebar(); // Ensure sidebar visibility is updated
}
}
function init() {
const timeMachine = new TimeMachine();
timeMachine.getUsername();
timeMachine.getJoinDate();
timeMachine.addInfoToSidebar();
}
// Run initialization when the page is fully loaded
window.addEventListener("load", init);