-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
thread-switcher.js
343 lines (322 loc) · 10.8 KB
/
thread-switcher.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
( () => {
/* variables */
let lastLocationHref;
let currentRoom;
let threadHeadersArray;
let showThreadHeadingTimerID;
/* transform text from a thread summary */
/* TODO: L10N */
const formatTitleFromThreadHeading = title => {
return title
//.replace(/Thread by [^\.]*\./, '') /* remove thread creator */
.replace(/\. \d+ (Replies|Reply)\./, '') /* remove number of replies */
.replace(/\. \d+ 件の返信/, '')
.replace(/\. [^\.]*\d+\:\d+( (A|P)M)?/, '') /* remove string with thread start date */
.replace(/. Last updated.*$/, '') /* remove everything after "Last updated */
.replace(/\. 最終更新.*$/, '')
.replace(/\. Now$/, '') /* remove 'Now' that's added for brand new threads */
.replace(/\. たった今$/, '')
.replace(/\. \d+ mins?$/, '') /* remove minute counter for brand new threads */
.replace(/\. \d+ 分前/, '') /* remove minute counter for brand new threads */
//.replace(/\d+ Unread\./, ''); /* remove unread counter */
.replace(/\n.*/gm, '') /* remove the second line and beyond */
.replace(/。.*/gm, '') /* remove 2nd sentence and beyond */
.replace(/\*([^(\*)]+)\*/g, '$1'); /* remove bold markdown */
//.replace(/【([^(【】)]+)】/g, '$1'); /* remove 【】 */
};
/* hide thread heading */
const hideThreadHeading = () => {
const elem = document.getElementById('thread-heading');
if (elem) {
elem.style.display = 'none';
}
};
/* show thread heading */
const showThreadHeading = thread => {
const elem = document.getElementById('thread-heading');
if (elem) {
const titleArr = thread.textContent.split('.');
if (titleArr.length > 0 &&
(titleArr[0].indexOf('Unread') > -1 || titleArr[0].indexOf('未読') > -1)) { // TODO: L10N
titleArr.shift(); // exclude unread count
}
titleArr.shift(); // exclude thread author name
if (titleArr.length > 0 &&
(titleArr[0].indexOf('Space Manager') > -1 || titleArr[0].indexOf('スペースの管理者') > -1)) { // TODO: L10N
titleArr.shift(); // exclude indication of thread author's position in this space
}
elem.textContent = formatTitleFromThreadHeading(titleArr.join('.'));
elem.style.display = 'block';
if (typeof showThreadHeadingTimerID === 'number') {
clearTimeout(showThreadHeadingTimerID);
}
showThreadHeadingTimerID = setTimeout(hideThreadHeading, 1000);
}
};
/* go to the thread selected with the thread selector */
const switchThread = () => {
const select = document.getElementById('thread-selector');
if (select) {
let index = select.selectedIndex;
if (index >= 2) {
index -= 2;
let threadContainer = threadHeadersArray[index].nextElementSibling;
while (threadContainer) {
if (threadContainer.querySelector('[role="button"]')) {
break;
}
threadContainer = threadContainer.nextElementSibling;
}
if (threadContainer) {
let timerID;
const watchScroll = () => {
if (typeof timerID === 'number') {
clearTimeout(timerID);
}
timerID = setTimeout( () => {
window.removeEventListener('scroll', watchScroll, true);
let elem = currentRoom.firstChild;
while (elem) {
if (elem.scrollTop != 0) {
break;
}
elem = elem.nextElementSibling;
}
if (elem) {
elem.scrollTop += 80;
}
}, 100);
};
window.addEventListener('scroll', watchScroll, true);
threadContainer.scrollIntoView({behavior: 'smooth', block: 'end', inline: 'nearest'}); // NOTE: Smooth scrolling will not work unless Chrome's own flag is enabled.
showThreadHeading(threadHeadersArray[index]);
}
else {
console.log('thread container element not found.');
}
} else if (index == 1) { // Go to the upper end (to fetch more threads)
let topThreadHead = threadHeadersArray[0];
if (topThreadHead) {
topThreadHead.scrollIntoView({behavior: 'auto', block: 'start', inline: 'nearest'});
}
}
select.selectedIndex = 0;
}
else {
console.log('#thread-selector not found.');
}
}
/* build the switcher */
const buildSwitcher = () => {
/* query for room */
currentRoom = document.body.querySelector('[role="main"]');
if (!currentRoom) {
//console.log('Room element not found.');
return null;
}
/* query for threads in the room */
const threadHeaders = currentRoom.querySelectorAll('[role="heading"][aria-label]');
threadHeadersArray = Array.from(threadHeaders);
if (threadHeadersArray.length == 0) {
//console.log('No threads.');
return null;
}
/* build thread list (as <option>s for <select>) */
const threadList = threadHeadersArray
.map((thread) => {
const item = document.createElement('option');
item.className = 'thread-list-item';
const titleArr = thread.textContent.split('.');
if (titleArr.length > 0 &&
(titleArr[0].indexOf('Unread') > -1 || titleArr[0].indexOf('未読') > -1)) { // TODO: L10N
item.className = item.className + ' thread-unread';
titleArr.shift(); // exclude unread count
}
titleArr.shift(); // exclude thread author name
if (titleArr.length > 0 &&
(titleArr[0].indexOf('Space Manager') > -1 || titleArr[0].indexOf('スペースの管理者') > -1)) { // TODO: L10N
titleArr.shift(); // exclude indication of thread author's position in this space
}
item.textContent = formatTitleFromThreadHeading(titleArr.join('.'));
return item;
});
/* build <select> DOM */
const selectDOM = document.createElement('select');
//selectDOM.id = `thread-group-${group.label}`;
selectDOM.id = 'thread-selector';
selectDOM.onchange = switchThread;
let item;
/* add 'Go to thread' to <select> DOM */
item = document.createElement('option');
item.hidden = true;
item.disabled = true;
item.className = 'thread-list-header';
item.textContent = chrome.i18n.getMessage('goto_thread');
selectDOM.appendChild(item);
/* add 'Go to the upper end' to <select> DOM */
item = document.createElement('option');
item.className = 'thread-list-fetch';
item.textContent = chrome.i18n.getMessage('goto_upper_end');
selectDOM.appendChild(item);
/* add thread titles to <select> DOM */
threadList.forEach(option => selectDOM.appendChild(option));
selectDOM.selectedIndex = 0;
/* build <div> DOM to show heading */
const headingDOM = document.createElement('div');
headingDOM.id = 'thread-heading';
headingDOM.style.display = 'block';
/* build the switcher DOM */
const switcherDOM = document.createElement('div');
switcherDOM.id = 'thread-switcher';
switcherDOM.appendChild(selectDOM);
switcherDOM.appendChild(headingDOM);
return switcherDOM;
};
/* logic for building the switcher and injecting it into the page */
const insertSwitcher = () => {
/* if we are not in a room, don't build a switcher */
const switcher = buildSwitcher();
if (switcher) {
const target = currentRoom.nextElementSibling;
if (target && target.id == 'thread-switcher') {
/* update switcher that already exists */
switcher.replaceChild(target.childNodes[1], switcher.childNodes[1]);
currentRoom.parentNode.replaceChild(switcher, target);
}
else {
/* switcher doesn't exist yet! add it */
currentRoom.parentNode.insertBefore(switcher, target);
}
}
else {
/* remove switcher if exists */
const switcher = document.getElementById('thread-switcher');
if (switcher) {
switcher.parentNode.removeChild(switcher);
}
}
};
/* css overrides for existing and new controls */
const injectCSS = () => {
const cssOverride = document.createElement('style');
cssOverride.innerHTML = `
#thread-switcher {
}
#thread-selector {
position: absolute;
top: 0px;
right: 0px;
width: 120px;
z-index: 950;
}
#thread-heading {
position: absolute;
top: 0px;
left: 0px;
background: pink;
}
.thread-list-header {}
.thread-list-fetch { color: #2d76e5; }
.thread-list-item {}
.thread-unread { font-weight: bold; }
`;
document.body.appendChild(cssOverride);
};
/* process to be executed when changes occur in the document */
const run = () => {
insertSwitcher();
lastLocationHref = document.location.href;
};
const clickEventHandler = e => {
if (window.getSelection().toString()) {
return;
}
let node = e.target;
switch (node.tagName) {
case 'svg':
case 'path':
case 'INPUT':
return;
}
while (node) {
while (node.previousElementSibling) {
node = node.previousElementSibling;
const role = node.getAttribute('role');
const label = node.getAttribute('aria-label');
if (role == 'heading' && typeof label === 'string') {
showThreadHeading(node);
return;
}
if (role == 'button' && node.getAttribute('title') !== null) {
return;
}
}
node = node.parentNode;
}
};
const setup = () => {
if (!document.location.hash.match(/id=\w*Frame/)) {
return;
}
/* initial run */
injectCSS();
run();
/* call run when the document changes and then settles down */
let runID;
const observer = new MutationObserver( (records) => {
let count = 0;
for (const record of records) {
switch (record.target.id) {
case 'thread-switcher':
case 'thread-selector':
case 'thread-heading':
/* ignore this */
break;
default:
if (record.type === 'childList') {
for (const node of Array.from(record.addedNodes)) {
switch (node.id) {
case 'thread-switcher':
case 'thread-selector':
case 'thread-heading':
/* ignore this */
break;
default:
if (node.tagName == 'DIV' && node.childElementCount == 1 && node.firstElementChild.tagName == 'INPUT') {
/* ignore this */
}
else if (typeof node.getAttribute === 'function' && node.getAttribute('role') == 'menuitem') {
/* ignore this */
}
else {
++count;
}
break;
}
}
}
else {
++count;
}
break;
}
}
if (count == 0) {
return;
}
/*
if (document.location.href == lastLocationHref) {
return;
}
*/
if (typeof runID === 'number') {
clearTimeout(runID);
}
runID = setTimeout(run, 200);
});
observer.observe(document.body, { childList: true, subtree: true });
window.addEventListener('click', clickEventHandler);
};
/* wait for the end of the document loading process before running setup */
window.onload = () => setup();
})();