blob: dc3e270f77c19bc63bea1f07847c354449bf2ad0 [file] [log] [blame]
avm9996311707032021-02-05 19:11:25 +01001var mutationObserver, intersectionObserver, intersectionOptions, options,
2 authuser;
avm99963cbea3142019-03-28 00:48:15 +01003
avm99963f5923962020-12-07 16:44:37 +01004function removeChildNodes(node) {
5 while (node.firstChild) {
6 node.removeChild(node.firstChild);
avm99963af7860e2019-06-04 03:33:26 +02007 }
avm99963f5923962020-12-07 16:44:37 +01008}
avm99963af7860e2019-06-04 03:33:26 +02009
avm9996390cc2e32021-02-05 18:14:16 +010010function getNParent(node, n) {
11 if (n <= 0) return node;
12 if (!('parentNode' in node)) return null;
13 return getNParent(node.parentNode, n - 1);
14}
15
avm999633eae4522021-04-22 01:14:27 +020016function parseUrl(url) {
17 var forum_a = url.match(/forum\/([0-9]+)/i);
18 var thread_a = url.match(/thread\/([0-9]+)/i);
19
20 if (forum_a === null || thread_a === null) {
21 return false;
22 }
23
24 return {
25 'forum': forum_a[1],
26 'thread': thread_a[1],
27 };
28}
29
avm99963f5923962020-12-07 16:44:37 +010030function createExtBadge() {
31 var badge = document.createElement('div');
32 badge.classList.add('TWPT-badge');
33 badge.setAttribute(
34 'title', chrome.i18n.getMessage('inject_extension_badge_helper', [
35 chrome.i18n.getMessage('appName')
36 ]));
37
38 var badgeI = document.createElement('i');
39 badgeI.classList.add('material-icon-i', 'material-icons-extended');
40 badgeI.textContent = 'repeat';
41
42 badge.append(badgeI);
43 return badge;
avm99963af7860e2019-06-04 03:33:26 +020044}
45
avm99963943b8492020-08-31 23:40:43 +020046function addProfileHistoryLink(node, type, query) {
47 var urlpart = encodeURIComponent('query=' + query);
avm99963a2945b62020-11-27 00:32:02 +010048 var authuserpart =
49 (authuser == '0' ? '' : '?authuser=' + encodeURIComponent(authuser));
avm99963943b8492020-08-31 23:40:43 +020050 var container = document.createElement('div');
51 container.style.margin = '3px 0';
52
53 var link = document.createElement('a');
54 link.setAttribute(
avm99963a2945b62020-11-27 00:32:02 +010055 'href',
56 'https://support.google.com/s/community/search/' + urlpart +
57 authuserpart);
avm99963943b8492020-08-31 23:40:43 +020058 link.innerText = chrome.i18n.getMessage('inject_previousposts_' + type);
59
60 container.appendChild(link);
avm9996306167752020-09-08 00:50:36 +020061 node.appendChild(container);
avm99963943b8492020-08-31 23:40:43 +020062}
63
avm999638e0c1002020-12-03 16:54:20 +010064function applyDragAndDropFix(node) {
65 console.debug('Adding link drag&drop fix to ', node);
66 node.addEventListener('drop', e => {
67 if (e.dataTransfer.types.includes('text/uri-list')) {
68 e.stopImmediatePropagation();
69 console.debug('Stopping link drop event propagation.');
70 }
71 }, true);
72}
73
avm99963f5923962020-12-07 16:44:37 +010074function nodeIsReadToggleBtn(node) {
75 return ('tagName' in node) && node.tagName == 'MATERIAL-BUTTON' &&
76 node.getAttribute('debugid') !== null &&
77 (node.getAttribute('debugid') == 'mark-read-button' ||
78 node.getAttribute('debugid') == 'mark-unread-button') &&
79 ('parentNode' in node) && node.parentNode !== null &&
80 ('parentNode' in node.parentNode) &&
81 node.parentNode.querySelector('[debugid="batchlock"]') === null &&
82 node.parentNode.parentNode !== null &&
83 ('tagName' in node.parentNode.parentNode) &&
84 node.parentNode.parentNode.tagName == 'EC-BULK-ACTIONS';
85}
86
avm9996328fddc62021-02-05 20:33:48 +010087function injectDarkModeButton(rightControl) {
88 var darkThemeSwitch = document.createElement('material-button');
89 darkThemeSwitch.classList.add('TWPT-dark-theme', 'TWPT-btn--with-badge');
90 darkThemeSwitch.setAttribute('button', '');
91 darkThemeSwitch.setAttribute(
92 'title', chrome.i18n.getMessage('inject_ccdarktheme_helper'));
93
94 darkThemeSwitch.addEventListener('click', e => {
95 chrome.storage.sync.get(null, currentOptions => {
96 currentOptions.ccdarktheme_switch_status =
97 !options.ccdarktheme_switch_status;
98 chrome.storage.sync.set(currentOptions, _ => {
99 location.reload();
100 });
101 });
102 });
103
104 var switchContent = document.createElement('div');
105 switchContent.classList.add('content');
106
107 var icon = document.createElement('material-icon');
108
109 var i = document.createElement('i');
110 i.classList.add('material-icon-i', 'material-icons-extended');
111 i.textContent = 'brightness_4';
112
113 icon.appendChild(i);
114 switchContent.appendChild(icon);
115 darkThemeSwitch.appendChild(switchContent);
116
117 var badgeContent = createExtBadge();
118
119 darkThemeSwitch.appendChild(badgeContent);
120
121 rightControl.style.width =
122 (parseInt(window.getComputedStyle(rightControl).width) + 58) + 'px';
123 rightControl.insertAdjacentElement('afterbegin', darkThemeSwitch);
124}
125
avm99963f5923962020-12-07 16:44:37 +0100126function addBatchLockBtn(readToggle) {
127 var clone = readToggle.cloneNode(true);
128 clone.setAttribute('debugid', 'batchlock');
129 clone.classList.add('TWPT-btn--with-badge');
130 clone.setAttribute('title', chrome.i18n.getMessage('inject_lockbtn'));
131 clone.querySelector('material-icon').setAttribute('icon', 'lock');
132 clone.querySelector('i.material-icon-i').textContent = 'lock';
133
134 var badge = createExtBadge();
135 clone.append(badge);
136
137 clone.addEventListener('click', function() {
138 var modal = document.querySelector('.pane[pane-id="default-1"]');
139
140 var dialog = document.createElement('material-dialog');
141 dialog.setAttribute('role', 'dialog');
142 dialog.setAttribute('aria-modal', 'true');
143 dialog.classList.add('TWPT-dialog');
144
145 var header = document.createElement('header');
146 header.setAttribute('role', 'presentation');
147 header.classList.add('TWPT-dialog-header');
148
149 var title = document.createElement('div');
150 title.classList.add('TWPT-dialog-header--title', 'title');
151 title.textContent = chrome.i18n.getMessage('inject_lockbtn');
152
153 header.append(title);
154
155 var main = document.createElement('main');
156 main.setAttribute('role', 'presentation');
157 main.classList.add('TWPT-dialog-main');
158
159 var p = document.createElement('p');
160 p.textContent = chrome.i18n.getMessage('inject_lockdialog_desc');
161
162 main.append(p);
163
164 dialog.append(header, main);
165
166 var footers = [['lock', 'unlock', 'cancel'], ['reload', 'close']];
167
168 for (var i = 0; i < footers.length; ++i) {
169 var footer = document.createElement('footer');
170 footer.setAttribute('role', 'presentation');
171 footer.classList.add('TWPT-dialog-footer');
172 footer.setAttribute('data-footer-id', i);
173
174 if (i > 0) footer.classList.add('is-hidden');
175
176 footers[i].forEach(action => {
177 var btn = document.createElement('material-button');
178 btn.setAttribute('role', 'button');
179 btn.classList.add('TWPT-dialog-footer-btn');
180 if (i == 1) btn.classList.add('is-disabled');
181
182 switch (action) {
183 case 'lock':
184 case 'unlock':
185 btn.addEventListener('click', _ => {
186 if (btn.classList.contains('is-disabled')) return;
187 var message = {
188 action,
189 prefix: 'TWPT-batchlock',
190 };
191 window.postMessage(message, '*');
192 });
193 break;
194
195 case 'cancel':
196 case 'close':
197 btn.addEventListener('click', _ => {
198 if (btn.classList.contains('is-disabled')) return;
199 modal.classList.remove('visible');
200 modal.style.display = 'none';
201 removeChildNodes(modal);
202 });
203 break;
204
205 case 'reload':
206 btn.addEventListener('click', _ => {
207 if (btn.classList.contains('is-disabled')) return;
208 window.location.reload()
209 });
210 break;
211 }
212
213 var content = document.createElement('div');
214 content.classList.add('content', 'TWPT-dialog-footer-btn--content');
215 content.textContent =
216 chrome.i18n.getMessage('inject_lockdialog_btn_' + action);
217
218 btn.append(content);
219 footer.append(btn);
220 });
221
222 var clear = document.createElement('div');
223 clear.style.clear = 'both';
224
225 footer.append(clear);
226 dialog.append(footer);
227 }
228
229 removeChildNodes(modal);
230 modal.append(dialog);
231 modal.classList.add('visible', 'modal');
232 modal.style.display = 'flex';
233 });
Adrià Vilanova Martínez74273ee2021-06-25 19:23:27 +0200234
235 var duplicateBtn =
236 readToggle.parentNode.querySelector('[debugid="mark-duplicate-button"]');
237 if (duplicateBtn)
238 duplicateBtn.parentNode.insertBefore(
239 clone, (duplicateBtn.nextSibling || duplicateBtn));
240 else
241 readToggle.parentNode.insertBefore(
242 clone, (readToggle.nextSibling || readToggle));
avm99963f5923962020-12-07 16:44:37 +0100243}
244
avm999633eae4522021-04-22 01:14:27 +0200245// TODO(avm99963): This is a prototype. DON'T FORGET TO ADD ERROR HANDLING.
246function injectAvatars(node) {
247 var header = node.querySelector(
248 'ec-thread-summary .main-header .panel-description a.header');
249 if (header === null) return;
250
251 var link = parseUrl(header.href);
252 if (link === false) return;
253
254 var APIRequestUrl = 'https://support.google.com/s/community/api/ViewThread' +
255 (authuser == '0' ? '' : '?authuser=' + encodeURIComponent(authuser));
256
257 fetch(APIRequestUrl, {
258 'headers': {
259 'content-type': 'text/plain; charset=utf-8',
260 },
261 'body': JSON.stringify({
262 1: link.forum,
263 2: link.thread,
264 3: {
265 1: {2: 15},
266 3: true,
267 5: true,
268 10: true,
269 16: true,
270 18: true,
271 }
272 }),
273 'method': 'POST',
274 'mode': 'cors',
275 'credentials': 'omit',
276 })
277 .then(res => {
278 if (res.status == 200 || res.status == 400) {
279 return res.json().then(data => ({
280 status: res.status,
281 body: data,
282 }));
283 } else {
284 throw new Error('Status code ' + res.status + ' was not expected.');
285 }
286 })
287 .then(res => {
288 if (res.status == 400) {
289 throw new Error(
290 res.body[4] ||
291 ('Response status: 400. Error code: ' + res.body[2]));
292 }
293
294 return res.body;
295 })
296 .then(data => {
297 if (!('1' in data) || !('8' in data['1'])) return false;
298
299 var messages = data['1']['8'];
300 if (messages == 0) return;
301
302 var avatarUrls = [];
303
304 if (!('3' in data['1'])) return false;
305 for (var m of data['1']['3']) {
306 if (!('3' in m) || !('1' in m['3']) || !('2' in m['3']['1']))
307 continue;
308
309 var url = m['3']['1']['2'];
310
311 if (!avatarUrls.includes(url)) avatarUrls.push(url);
312
313 if (avatarUrls.length == 3) break;
314 }
315
316 var avatarsContainer = document.createElement('div');
317 avatarsContainer.classList.add('TWPT-avatars');
318
319 var count = Math.floor(Math.random() * 4);
320
321 for (var i = 0; i < avatarUrls.length; ++i) {
322 var avatar = document.createElement('div');
323 avatar.classList.add('TWPT-avatar');
avm99963a007d492021-05-02 12:32:03 +0200324 avatar.style.backgroundImage = 'url(\'' + avatarUrls[i] + '\')';
avm999633eae4522021-04-22 01:14:27 +0200325 avatarsContainer.appendChild(avatar);
326 }
327
328 header.appendChild(avatarsContainer);
329 });
330}
331
avm99963a007d492021-05-02 12:32:03 +0200332var autoRefresh = {
333 isLookingForUpdates: false,
334 isUpdatePromptShown: false,
335 lastTimestamp: null,
336 filter: null,
337 path: null,
338 snackbar: null,
339 interval: null,
340 firstCallTimeout: null,
341 intervalMs: 3 * 60 * 1000, // 3 minutes
342 firstCallDelayMs: 3 * 1000, // 3 seconds
343 getStartupData() {
344 return JSON.parse(
345 document.querySelector('html').getAttribute('data-startup'));
346 },
347 isOrderedByTimestampDescending() {
348 var startup = this.getStartupData();
349 // Returns orderOptions.by == TIMESTAMP && orderOptions.desc == true
350 return (
351 startup?.[1]?.[1]?.[3]?.[14]?.[1] == 1 &&
352 startup?.[1]?.[1]?.[3]?.[14]?.[2] == true);
353 },
354 getCustomFilter(path) {
355 var searchRegex = /^\/s\/community\/search\/([^\/]*)/;
356 var matches = path.match(searchRegex);
357 if (matches !== null && matches.length > 1) {
358 var search = decodeURIComponent(matches[1]);
359 var params = new URLSearchParams(search);
360 return params.get('query') || '';
361 }
362
363 return '';
364 },
365 filterHasOverride(filter, override) {
366 var escapedOverride = override.replace(/([^\w\d\s])/gi, '\\$1');
367 var regex = new RegExp('[^a-zA-Z0-9]?' + escapedOverride + ':');
368 return regex.test(filter);
369 },
370 getFilter(path) {
371 var query = this.getCustomFilter(path);
372
373 // Note: This logic has been copied and adapted from the
374 // _buildQuery$1$threadId function in the Community Console
375 var conditions = '';
376 var startup = this.getStartupData();
377
378 // TODO(avm99963): if the selected forums are changed without reloading the
379 // page, this will get the old selected forums. Fix this.
380 var forums = startup?.[1]?.[1]?.[3]?.[8] ?? [];
381 if (!this.filterHasOverride(query, 'forum') && forums !== null &&
382 forums.length > 0)
383 conditions += ' forum:(' + forums.join(' | ') + ')';
384
385 var langs = startup?.[1]?.[1]?.[3]?.[5] ?? [];
386 if (!this.filterHasOverride(query, 'lang') && langs !== null &&
387 langs.length > 0)
388 conditions += ' lang:(' + langs.map(l => '"' + l + '"').join(' | ') + ')';
389
390 if (query.length !== 0 && conditions.length !== 0)
391 return '(' + query + ')' + conditions;
392 return query + conditions;
393 },
394 getLastTimestamp() {
395 var APIRequestUrl = 'https://support.google.com/s/community/api/ViewForum' +
396 (authuser == '0' ? '' : '?authuser=' + encodeURIComponent(authuser));
397
398 return fetch(APIRequestUrl, {
399 'headers': {
400 'content-type': 'text/plain; charset=utf-8',
401 },
402 'body': JSON.stringify({
403 1: '0', // TODO: Change, when only a forum is selected, it
404 // should be set here
405 2: {
406 1: {
407 2: 2,
408 },
409 2: {
410 1: 1,
411 2: true,
412 },
413 12: this.filter,
414 },
415 }),
416 'method': 'POST',
417 'mode': 'cors',
418 'credentials': 'include',
419 })
420 .then(res => {
421 if (res.status == 200 || res.status == 400) {
422 return res.json().then(data => ({
423 status: res.status,
424 body: data,
425 }));
426 } else {
427 throw new Error('Status code ' + res.status + ' was not expected.');
428 }
429 })
430 .then(res => {
431 if (res.status == 400) {
432 throw new Error(
433 res.body[4] ||
434 ('Response status: 400. Error code: ' + res.body[2]));
435 }
436
437 return res.body;
438 })
439 .then(body => {
440 var timestamp = body?.[1]?.[2]?.[0]?.[2]?.[17];
441 if (timestamp === undefined)
442 throw new Error(
443 'Unexpected body of response (' +
444 (body?.[1]?.[2]?.[0] === undefined ?
445 'no threads were returned' :
446 'the timestamp value is not present in the first thread') +
447 ').');
448
449 return timestamp;
450 });
451 // TODO(avm99963): Add retry mechanism (sometimes thread lists are empty,
452 // but when loading the next page the thread appears).
453 //
454 // NOTE(avm99963): It seems like loading the first 2 threads instead of only
455 // the first one fixes this (empty lists are now rarely returned).
456 },
457 unregister() {
458 console.debug('autorefresh_list: unregistering');
459
460 if (!this.isLookingForUpdates) return;
461
462 window.clearTimeout(this.firstCallTimeout);
463 window.clearInterval(this.interval);
464 this.isUpdatePromptShown = false;
465 this.isLookingForUpdates = false;
466 },
467 showUpdatePrompt() {
468 this.snackbar.classList.remove('TWPT-hidden');
469 document.title = '[!!!] ' + document.title.replace('[!!!] ', '');
470 this.isUpdatePromptShown = true;
471 },
472 hideUpdatePrompt() {
473 this.snackbar.classList.add('TWPT-hidden');
474 document.title = document.title.replace('[!!!] ', '');
475 this.isUpdatePromptShown = false;
476 },
477 injectUpdatePrompt() {
478 var pane = document.createElement('div');
479 pane.classList.add('TWPT-pane-for-snackbar');
480
481 var snackbar = document.createElement('material-snackbar-panel');
482 snackbar.classList.add('TWPT-snackbar');
483 snackbar.classList.add('TWPT-hidden');
484
485 var ac = document.createElement('div');
486 ac.classList.add('TWPT-animation-container');
487
488 var nb = document.createElement('div');
489 nb.classList.add('TWPT-notification-bar');
490
491 var ft = document.createElement('focus-trap');
492
493 var content = document.createElement('div');
494 content.classList.add('TWPT-focus-content-wrapper');
495
496 var badge = createExtBadge();
497
498 var message = document.createElement('div');
499 message.classList.add('TWPT-message');
500 message.textContent =
501 chrome.i18n.getMessage('inject_autorefresh_list_snackbar_message');
502
503 var action = document.createElement('div');
504 action.classList.add('TWPT-action');
505 action.textContent =
506 chrome.i18n.getMessage('inject_autorefresh_list_snackbar_action');
507
508 action.addEventListener('click', e => {
509 this.hideUpdatePrompt();
510 document.querySelector('.app-title-button').click();
511 });
512
513 content.append(badge, message, action);
514 ft.append(content);
515 nb.append(ft);
516 ac.append(nb);
517 snackbar.append(ac);
518 pane.append(snackbar);
519 document.getElementById('default-acx-overlay-container').append(pane);
520 this.snackbar = snackbar;
521 },
522 checkUpdate() {
523 if (location.pathname != this.path) {
524 this.unregister();
525 return;
526 }
527
528 if (this.isUpdatePromptShown) return;
529
530 console.debug('Checking for update at: ', new Date());
531
532 this.getLastTimestamp()
533 .then(timestamp => {
534 if (timestamp != this.lastTimestamp) this.showUpdatePrompt();
535 })
536 .catch(
537 err => console.error(
538 'Coudln\'t get last timestamp (while updating): ', err));
539 },
540 firstCall() {
541 console.debug(
542 'autorefresh_list: now performing first call to finish setup (filter: [' +
543 this.filter + '])');
544
545 if (location.pathname != this.path) {
546 this.unregister();
547 return;
548 }
549
550 this.getLastTimestamp()
551 .then(timestamp => {
552 this.lastTimestamp = timestamp;
553 var checkUpdateCallback = this.checkUpdate.bind(this);
554 this.interval =
555 window.setInterval(checkUpdateCallback, this.intervalMs);
556 })
557 .catch(
558 err => console.error(
559 'Couldn\'t get last timestamp (while setting up): ', err));
560 },
561 setUp() {
562 if (!this.isOrderedByTimestampDescending()) return;
563
564 this.unregister();
565
566 console.debug('autorefresh_list: starting set up...');
567
568 if (this.snackbar === null) this.injectUpdatePrompt();
569 this.isLookingForUpdates = true;
570 this.path = location.pathname;
571 this.filter = this.getFilter(this.path);
572
573 var firstCall = this.firstCall.bind(this);
574 this.firstCallTimeout = window.setTimeout(firstCall, this.firstCallDelayMs);
575 },
576};
577
Adrià Vilanova Martínezc6aacfa2021-06-09 14:16:11 +0200578function isDarkThemeOn() {
579 if (!options.ccdarktheme) return false;
580
581 if (options.ccdarktheme_mode == 'switch')
582 return options.ccdarktheme_switch_status;
583
584 return window.matchMedia &&
585 window.matchMedia('(prefers-color-scheme: dark)').matches;
586}
587
588var unifiedProfilesFix = {
589 checkIframe(iframe) {
590 var srcRegex = /support.*\.google\.com\/profile\//;
Adrià Vilanova Martínezc6aacfa2021-06-09 14:16:11 +0200591 return srcRegex.test(iframe.src ?? '');
592 },
593 fixIframe(iframe) {
594 console.info('[unifiedProfilesFix] Fixing unified profiles iframe');
595 var url = new URL(iframe.src);
596 url.searchParams.set('dark', 1);
597 iframe.src = url.href;
598 },
599};
600
avm9996390cc2e32021-02-05 18:14:16 +0100601function injectPreviousPostsLinks(nameElement) {
602 var mainCardContent = getNParent(nameElement, 3);
603 if (mainCardContent === null) {
604 console.error(
605 '[previousposts] Couldn\'t find |.main-card-content| element.');
606 return;
avm99963490114d2021-02-05 16:12:20 +0100607 }
avm9996390cc2e32021-02-05 18:14:16 +0100608
609 var forumId = location.href.split('/forum/')[1].split('/')[0] || '0';
610
avm99963193233a2021-05-29 15:49:29 +0200611 var nameTag =
612 (nameElement.tagName == 'EC-DISPLAY-NAME-EDITOR' ?
613 nameElement.querySelector('.top-section > span') ?? nameElement :
614 nameElement);
615 var name = escapeUsername(nameTag.textContent);
avm9996390cc2e32021-02-05 18:14:16 +0100616 var query1 = encodeURIComponent(
617 '(creator:"' + name + '" | replier:"' + name + '") forum:' + forumId);
618 var query2 = encodeURIComponent(
619 '(creator:"' + name + '" | replier:"' + name + '") forum:any');
620
621 var container = document.createElement('div');
622 container.classList.add('TWPT-previous-posts');
623
624 var badge = createExtBadge();
625 container.appendChild(badge);
626
627 var linkContainer = document.createElement('div');
628 linkContainer.classList.add('TWPT-previous-posts--links');
629
630 addProfileHistoryLink(linkContainer, 'forum', query1);
631 addProfileHistoryLink(linkContainer, 'all', query2);
632
633 container.appendChild(linkContainer);
634
635 mainCardContent.appendChild(container);
avm99963490114d2021-02-05 16:12:20 +0100636}
637
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200638// Send a request to mark the current thread as read
639function markCurrentThreadAsRead() {
640 var threadRegex =
641 /\/s\/community\/?.*\/forum\/([0-9]+)\/?.*\/thread\/([0-9]+)/;
642
643 var url = location.href;
644 var matches = url.match(threadRegex);
645 if (matches !== null && matches.length > 2) {
646 var forumId = matches[1];
647 var threadId = matches[2];
648
649 return CCApi(
650 'ViewThread', {
651 1: forumId,
652 2: threadId,
653 // options
654 3: {
655 // pagination
656 1: {
657 2: 0, // maxNum
658 },
659 3: false, // withMessages
660 5: false, // withUserProfile
661 6: true, // withUserReadState
662 9: false, // withRequestorProfile
663 10: false, // withPromotedMessages
664 11: false, // withExpertResponder
665 },
666 },
667 authuser)
668 .then(thread => {
669 if (thread?.[1]?.[6] === true) {
670 console.debug(
671 'This thread is already marked as read, but marking it as read anyways.');
672 }
673
674 var lastMessageId = thread?.[1]?.[2]?.[10];
675 if (lastMessageId === undefined)
676 throw new Error(
677 'Couldn\'t find lastMessageId in the ViewThread response.');
678
679 return CCApi(
680 'SetUserReadStateBulk', {
681 1: [{
682 1: forumId,
683 2: threadId,
684 3: lastMessageId,
685 }],
686 },
687 authuser);
688 })
689 .catch(err => {
690 console.error(
691 '[forceMarkAsRead] Error while marking current thread as read: ',
692 err);
693 });
694 }
695}
696
avm99963490114d2021-02-05 16:12:20 +0100697const watchedNodesSelectors = [
avm9996328fddc62021-02-05 20:33:48 +0100698 // App container (used to set up the intersection observer and inject the dark
699 // mode button)
avm9996311707032021-02-05 19:11:25 +0100700 'ec-app',
701
avm99963490114d2021-02-05 16:12:20 +0100702 // Load more bar (for the "load more"/"load all" buttons)
703 '.load-more-bar',
704
avm99963b3e89862021-05-15 19:58:21 +0200705 // Username span/editor inside ec-user (user profile view)
avm9996390cc2e32021-02-05 18:14:16 +0100706 'ec-user .main-card .header > .name > span',
avm99963b3e89862021-05-15 19:58:21 +0200707 'ec-user .main-card .header > .name > ec-display-name-editor',
avm99963490114d2021-02-05 16:12:20 +0100708
709 // Rich text editor
710 'ec-movable-dialog',
711 'ec-rich-text-editor',
712
713 // Read/unread bulk action in the list of thread, for the batch lock feature
714 'ec-bulk-actions material-button[debugid="mark-read-button"]',
715 'ec-bulk-actions material-button[debugid="mark-unread-button"]',
avm999633eae4522021-04-22 01:14:27 +0200716
717 // Thread list items (used to inject the avatars)
718 'li',
avm99963a007d492021-05-02 12:32:03 +0200719
720 // Thread list (used for the autorefresh feature)
721 'ec-thread-list',
Adrià Vilanova Martínezc6aacfa2021-06-09 14:16:11 +0200722
723 // Unified profile iframe
724 'iframe',
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200725
726 // Thread component
727 'ec-thread',
avm99963490114d2021-02-05 16:12:20 +0100728];
729
730function handleCandidateNode(node) {
731 if (typeof node.classList !== 'undefined') {
avm9996328fddc62021-02-05 20:33:48 +0100732 if (('tagName' in node) && node.tagName == 'EC-APP') {
733 // Set up the intersectionObserver
734 if (typeof intersectionObserver === 'undefined') {
735 var scrollableContent = node.querySelector('.scrollable-content');
736 if (scrollableContent !== null) {
737 intersectionOptions = {
738 root: scrollableContent,
739 rootMargin: '0px',
740 threshold: 1.0,
741 };
avm9996311707032021-02-05 19:11:25 +0100742
avm9996328fddc62021-02-05 20:33:48 +0100743 intersectionObserver = new IntersectionObserver(
744 intersectionCallback, intersectionOptions);
745 }
746 }
747
748 // Inject the dark mode button
749 if (options.ccdarktheme && options.ccdarktheme_mode == 'switch') {
750 var rightControl = node.querySelector('header .right-control');
751 if (rightControl !== null) injectDarkModeButton(rightControl);
avm99963d24e2db2021-02-05 20:03:55 +0100752 }
avm99963490114d2021-02-05 16:12:20 +0100753 }
754
avm9996311707032021-02-05 19:11:25 +0100755 // Start the intersectionObserver for the "load more"/"load all" buttons
756 // inside a thread
757 if ((options.thread || options.threadall) &&
758 node.classList.contains('load-more-bar')) {
759 if (typeof intersectionObserver !== 'undefined') {
760 if (options.thread)
761 intersectionObserver.observe(node.querySelector('.load-more-button'));
762 if (options.threadall)
763 intersectionObserver.observe(node.querySelector('.load-all-button'));
764 } else {
765 console.warn(
766 '[infinitescroll] ' +
767 'The intersectionObserver is not ready yet.');
768 }
avm99963490114d2021-02-05 16:12:20 +0100769 }
770
771 // Show the "previous posts" links
772 // Here we're selecting the 'ec-user > div' element (unique child)
avm9996390cc2e32021-02-05 18:14:16 +0100773 if (options.history &&
avm99963b3e89862021-05-15 19:58:21 +0200774 (node.matches('ec-user .main-card .header > .name > span') ||
775 node.matches(
776 'ec-user .main-card .header > .name > ec-display-name-editor'))) {
avm99963490114d2021-02-05 16:12:20 +0100777 injectPreviousPostsLinks(node);
778 }
779
780 // Fix the drag&drop issue with the rich text editor
781 //
782 // We target both tags because in different contexts different
783 // elements containing the text editor get added to the DOM structure.
784 // Sometimes it's a EC-MOVABLE-DIALOG which already contains the
785 // EC-RICH-TEXT-EDITOR, and sometimes it's the EC-RICH-TEXT-EDITOR
786 // directly.
787 if (options.ccdragndropfix && ('tagName' in node) &&
788 (node.tagName == 'EC-MOVABLE-DIALOG' ||
789 node.tagName == 'EC-RICH-TEXT-EDITOR')) {
790 applyDragAndDropFix(node);
791 }
792
793 // Inject the batch lock button in the thread list
794 if (options.batchlock && nodeIsReadToggleBtn(node)) {
795 addBatchLockBtn(node);
796 }
avm999633eae4522021-04-22 01:14:27 +0200797
798 // Inject avatar links to threads in the thread list
799 if (options.threadlistavatars && ('tagName' in node) &&
800 (node.tagName == 'LI') &&
801 node.querySelector('ec-thread-summary') !== null) {
802 injectAvatars(node);
803 }
avm99963a007d492021-05-02 12:32:03 +0200804
805 // Set up the autorefresh list feature
806 if (options.autorefreshlist && ('tagName' in node) &&
807 node.tagName == 'EC-THREAD-LIST') {
808 autoRefresh.setUp();
809 }
Adrià Vilanova Martínezc6aacfa2021-06-09 14:16:11 +0200810
811 // Redirect unified profile iframe to dark version if applicable
812 if (node.tagName == 'IFRAME' && isDarkThemeOn() &&
813 unifiedProfilesFix.checkIframe(node)) {
814 unifiedProfilesFix.fixIframe(node);
815 }
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200816
817 // Force mark thread as read
818 if (options.forcemarkasread && node.tagName == 'EC-THREAD') {
819 markCurrentThreadAsRead();
820 }
avm99963a007d492021-05-02 12:32:03 +0200821 }
822}
823
824function handleRemovedNode(node) {
825 // Remove snackbar when exiting thread list view
826 if ('tagName' in node && node.tagName == 'EC-THREAD-LIST') {
827 autoRefresh.hideUpdatePrompt();
avm99963490114d2021-02-05 16:12:20 +0100828 }
829}
830
avm99963847ee632019-03-27 00:57:44 +0100831function mutationCallback(mutationList, observer) {
832 mutationList.forEach((mutation) => {
avm99963b69eb3d2020-08-20 02:03:44 +0200833 if (mutation.type == 'childList') {
834 mutation.addedNodes.forEach(function(node) {
avm99963490114d2021-02-05 16:12:20 +0100835 handleCandidateNode(node);
avm99963847ee632019-03-27 00:57:44 +0100836 });
avm99963a007d492021-05-02 12:32:03 +0200837
838 mutation.removedNodes.forEach(function(node) {
839 handleRemovedNode(node);
840 });
avm99963847ee632019-03-27 00:57:44 +0100841 }
842 });
843}
844
avm99963adf90862020-04-12 13:27:45 +0200845function intersectionCallback(entries, observer) {
avm99963847ee632019-03-27 00:57:44 +0100846 entries.forEach(entry => {
847 if (entry.isIntersecting) {
848 entry.target.click();
849 }
850 });
851};
852
853var observerOptions = {
854 childList: true,
avm99963b69eb3d2020-08-20 02:03:44 +0200855 subtree: true,
avm99963129fb502020-08-28 05:18:53 +0200856};
avm99963847ee632019-03-27 00:57:44 +0100857
avm99963129fb502020-08-28 05:18:53 +0200858chrome.storage.sync.get(null, function(items) {
859 options = items;
avm99963cbea3142019-03-28 00:48:15 +0100860
avm99963a2945b62020-11-27 00:32:02 +0100861 var startup =
862 JSON.parse(document.querySelector('html').getAttribute('data-startup'));
863 authuser = startup[2][1] || '0';
864
avm99963490114d2021-02-05 16:12:20 +0100865 // Before starting the mutation Observer, check whether we missed any
avm9996311707032021-02-05 19:11:25 +0100866 // mutations by manually checking whether some watched nodes already
867 // exist.
avm99963490114d2021-02-05 16:12:20 +0100868 var cssSelectors = watchedNodesSelectors.join(',');
869 document.querySelectorAll(cssSelectors)
870 .forEach(node => handleCandidateNode(node));
871
avm99963129fb502020-08-28 05:18:53 +0200872 mutationObserver = new MutationObserver(mutationCallback);
avm99963e4cac402020-12-03 16:10:58 +0100873 mutationObserver.observe(document.body, observerOptions);
avm99963cbea3142019-03-28 00:48:15 +0100874
avm99963129fb502020-08-28 05:18:53 +0200875 if (options.fixedtoolbar) {
876 injectStyles(
avm999630bc113a2020-09-07 13:02:11 +0200877 'ec-bulk-actions{position: sticky; top: 0; background: var(--TWPT-primary-background, #fff); z-index: 96;}');
avm99963129fb502020-08-28 05:18:53 +0200878 }
avm99963ae6a26d2020-04-12 14:03:51 +0200879
avm99963129fb502020-08-28 05:18:53 +0200880 if (options.increasecontrast) {
avm999630bc113a2020-09-07 13:02:11 +0200881 injectStyles(
avm99963a2a06442020-11-25 21:11:10 +0100882 '.thread-summary.read:not(.checked){background: var(--TWPT-thread-read-background, #ecedee)!important;}');
avm99963129fb502020-08-28 05:18:53 +0200883 }
avm999630f9503f2020-07-27 13:56:52 +0200884
avm99963129fb502020-08-28 05:18:53 +0200885 if (options.stickysidebarheaders) {
886 injectStyles(
avm999630bc113a2020-09-07 13:02:11 +0200887 'material-drawer .main-header{background: var(--TWPT-drawer-background, #fff)!important; position: sticky; top: 0; z-index: 1;}');
888 }
889
avm99963698d3762021-02-16 01:19:54 +0100890 if (options.enhancedannouncementsdot) {
891 injectStylesheet(
892 chrome.runtime.getURL('injections/enhanced_announcements_dot.css'));
893 }
894
avm99963d98126f2021-02-17 10:44:36 +0100895 if (options.repositionexpandthread) {
896 injectStylesheet(
897 chrome.runtime.getURL('injections/reposition_expand_thread.css'));
898 }
899
avm99963129942f2020-09-08 02:07:18 +0200900 if (options.ccforcehidedrawer) {
901 var drawer = document.querySelector('material-drawer');
902 if (drawer !== null && drawer.classList.contains('mat-drawer-expanded')) {
903 document.querySelector('.material-drawer-button').click();
904 }
905 }
avm99963f5923962020-12-07 16:44:37 +0100906
907 if (options.batchlock) {
908 injectScript(chrome.runtime.getURL('injections/batchlock_inject.js'));
Adrià Vilanova Martínez74273ee2021-06-25 19:23:27 +0200909 injectStylesheet(chrome.runtime.getURL('injections/batchlock_inject.css'));
avm99963f5923962020-12-07 16:44:37 +0100910 }
avm999633eae4522021-04-22 01:14:27 +0200911
912 if (options.threadlistavatars) {
913 injectStylesheet(
914 chrome.runtime.getURL('injections/thread_list_avatars.css'));
915 }
avm99963a007d492021-05-02 12:32:03 +0200916
917 if (options.autorefreshlist) {
918 injectStylesheet(chrome.runtime.getURL('injections/autorefresh_list.css'));
919 }
avm99963129fb502020-08-28 05:18:53 +0200920});