blob: 670080f80ab80e4deba59c9e3565f315af792fce [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
638const watchedNodesSelectors = [
avm9996328fddc62021-02-05 20:33:48 +0100639 // App container (used to set up the intersection observer and inject the dark
640 // mode button)
avm9996311707032021-02-05 19:11:25 +0100641 'ec-app',
642
avm99963490114d2021-02-05 16:12:20 +0100643 // Load more bar (for the "load more"/"load all" buttons)
644 '.load-more-bar',
645
avm99963b3e89862021-05-15 19:58:21 +0200646 // Username span/editor inside ec-user (user profile view)
avm9996390cc2e32021-02-05 18:14:16 +0100647 'ec-user .main-card .header > .name > span',
avm99963b3e89862021-05-15 19:58:21 +0200648 'ec-user .main-card .header > .name > ec-display-name-editor',
avm99963490114d2021-02-05 16:12:20 +0100649
650 // Rich text editor
651 'ec-movable-dialog',
652 'ec-rich-text-editor',
653
654 // Read/unread bulk action in the list of thread, for the batch lock feature
655 'ec-bulk-actions material-button[debugid="mark-read-button"]',
656 'ec-bulk-actions material-button[debugid="mark-unread-button"]',
avm999633eae4522021-04-22 01:14:27 +0200657
658 // Thread list items (used to inject the avatars)
659 'li',
avm99963a007d492021-05-02 12:32:03 +0200660
661 // Thread list (used for the autorefresh feature)
662 'ec-thread-list',
Adrià Vilanova Martínezc6aacfa2021-06-09 14:16:11 +0200663
664 // Unified profile iframe
665 'iframe',
avm99963490114d2021-02-05 16:12:20 +0100666];
667
668function handleCandidateNode(node) {
669 if (typeof node.classList !== 'undefined') {
avm9996328fddc62021-02-05 20:33:48 +0100670 if (('tagName' in node) && node.tagName == 'EC-APP') {
671 // Set up the intersectionObserver
672 if (typeof intersectionObserver === 'undefined') {
673 var scrollableContent = node.querySelector('.scrollable-content');
674 if (scrollableContent !== null) {
675 intersectionOptions = {
676 root: scrollableContent,
677 rootMargin: '0px',
678 threshold: 1.0,
679 };
avm9996311707032021-02-05 19:11:25 +0100680
avm9996328fddc62021-02-05 20:33:48 +0100681 intersectionObserver = new IntersectionObserver(
682 intersectionCallback, intersectionOptions);
683 }
684 }
685
686 // Inject the dark mode button
687 if (options.ccdarktheme && options.ccdarktheme_mode == 'switch') {
688 var rightControl = node.querySelector('header .right-control');
689 if (rightControl !== null) injectDarkModeButton(rightControl);
avm99963d24e2db2021-02-05 20:03:55 +0100690 }
avm99963490114d2021-02-05 16:12:20 +0100691 }
692
avm9996311707032021-02-05 19:11:25 +0100693 // Start the intersectionObserver for the "load more"/"load all" buttons
694 // inside a thread
695 if ((options.thread || options.threadall) &&
696 node.classList.contains('load-more-bar')) {
697 if (typeof intersectionObserver !== 'undefined') {
698 if (options.thread)
699 intersectionObserver.observe(node.querySelector('.load-more-button'));
700 if (options.threadall)
701 intersectionObserver.observe(node.querySelector('.load-all-button'));
702 } else {
703 console.warn(
704 '[infinitescroll] ' +
705 'The intersectionObserver is not ready yet.');
706 }
avm99963490114d2021-02-05 16:12:20 +0100707 }
708
709 // Show the "previous posts" links
710 // Here we're selecting the 'ec-user > div' element (unique child)
avm9996390cc2e32021-02-05 18:14:16 +0100711 if (options.history &&
avm99963b3e89862021-05-15 19:58:21 +0200712 (node.matches('ec-user .main-card .header > .name > span') ||
713 node.matches(
714 'ec-user .main-card .header > .name > ec-display-name-editor'))) {
avm99963490114d2021-02-05 16:12:20 +0100715 injectPreviousPostsLinks(node);
716 }
717
718 // Fix the drag&drop issue with the rich text editor
719 //
720 // We target both tags because in different contexts different
721 // elements containing the text editor get added to the DOM structure.
722 // Sometimes it's a EC-MOVABLE-DIALOG which already contains the
723 // EC-RICH-TEXT-EDITOR, and sometimes it's the EC-RICH-TEXT-EDITOR
724 // directly.
725 if (options.ccdragndropfix && ('tagName' in node) &&
726 (node.tagName == 'EC-MOVABLE-DIALOG' ||
727 node.tagName == 'EC-RICH-TEXT-EDITOR')) {
728 applyDragAndDropFix(node);
729 }
730
731 // Inject the batch lock button in the thread list
732 if (options.batchlock && nodeIsReadToggleBtn(node)) {
733 addBatchLockBtn(node);
734 }
avm999633eae4522021-04-22 01:14:27 +0200735
736 // Inject avatar links to threads in the thread list
737 if (options.threadlistavatars && ('tagName' in node) &&
738 (node.tagName == 'LI') &&
739 node.querySelector('ec-thread-summary') !== null) {
740 injectAvatars(node);
741 }
avm99963a007d492021-05-02 12:32:03 +0200742
743 // Set up the autorefresh list feature
744 if (options.autorefreshlist && ('tagName' in node) &&
745 node.tagName == 'EC-THREAD-LIST') {
746 autoRefresh.setUp();
747 }
Adrià Vilanova Martínezc6aacfa2021-06-09 14:16:11 +0200748
749 // Redirect unified profile iframe to dark version if applicable
750 if (node.tagName == 'IFRAME' && isDarkThemeOn() &&
751 unifiedProfilesFix.checkIframe(node)) {
752 unifiedProfilesFix.fixIframe(node);
753 }
avm99963a007d492021-05-02 12:32:03 +0200754 }
755}
756
757function handleRemovedNode(node) {
758 // Remove snackbar when exiting thread list view
759 if ('tagName' in node && node.tagName == 'EC-THREAD-LIST') {
760 autoRefresh.hideUpdatePrompt();
avm99963490114d2021-02-05 16:12:20 +0100761 }
762}
763
avm99963847ee632019-03-27 00:57:44 +0100764function mutationCallback(mutationList, observer) {
765 mutationList.forEach((mutation) => {
avm99963b69eb3d2020-08-20 02:03:44 +0200766 if (mutation.type == 'childList') {
767 mutation.addedNodes.forEach(function(node) {
avm99963490114d2021-02-05 16:12:20 +0100768 handleCandidateNode(node);
avm99963847ee632019-03-27 00:57:44 +0100769 });
avm99963a007d492021-05-02 12:32:03 +0200770
771 mutation.removedNodes.forEach(function(node) {
772 handleRemovedNode(node);
773 });
avm99963847ee632019-03-27 00:57:44 +0100774 }
775 });
776}
777
avm99963adf90862020-04-12 13:27:45 +0200778function intersectionCallback(entries, observer) {
avm99963847ee632019-03-27 00:57:44 +0100779 entries.forEach(entry => {
780 if (entry.isIntersecting) {
781 entry.target.click();
782 }
783 });
784};
785
786var observerOptions = {
787 childList: true,
avm99963b69eb3d2020-08-20 02:03:44 +0200788 subtree: true,
avm99963129fb502020-08-28 05:18:53 +0200789};
avm99963847ee632019-03-27 00:57:44 +0100790
avm99963129fb502020-08-28 05:18:53 +0200791chrome.storage.sync.get(null, function(items) {
792 options = items;
avm99963cbea3142019-03-28 00:48:15 +0100793
avm99963a2945b62020-11-27 00:32:02 +0100794 var startup =
795 JSON.parse(document.querySelector('html').getAttribute('data-startup'));
796 authuser = startup[2][1] || '0';
797
avm99963490114d2021-02-05 16:12:20 +0100798 // Before starting the mutation Observer, check whether we missed any
avm9996311707032021-02-05 19:11:25 +0100799 // mutations by manually checking whether some watched nodes already
800 // exist.
avm99963490114d2021-02-05 16:12:20 +0100801 var cssSelectors = watchedNodesSelectors.join(',');
802 document.querySelectorAll(cssSelectors)
803 .forEach(node => handleCandidateNode(node));
804
avm99963129fb502020-08-28 05:18:53 +0200805 mutationObserver = new MutationObserver(mutationCallback);
avm99963e4cac402020-12-03 16:10:58 +0100806 mutationObserver.observe(document.body, observerOptions);
avm99963cbea3142019-03-28 00:48:15 +0100807
avm99963129fb502020-08-28 05:18:53 +0200808 if (options.fixedtoolbar) {
809 injectStyles(
avm999630bc113a2020-09-07 13:02:11 +0200810 'ec-bulk-actions{position: sticky; top: 0; background: var(--TWPT-primary-background, #fff); z-index: 96;}');
avm99963129fb502020-08-28 05:18:53 +0200811 }
avm99963ae6a26d2020-04-12 14:03:51 +0200812
avm99963129fb502020-08-28 05:18:53 +0200813 if (options.increasecontrast) {
avm999630bc113a2020-09-07 13:02:11 +0200814 injectStyles(
avm99963a2a06442020-11-25 21:11:10 +0100815 '.thread-summary.read:not(.checked){background: var(--TWPT-thread-read-background, #ecedee)!important;}');
avm99963129fb502020-08-28 05:18:53 +0200816 }
avm999630f9503f2020-07-27 13:56:52 +0200817
avm99963129fb502020-08-28 05:18:53 +0200818 if (options.stickysidebarheaders) {
819 injectStyles(
avm999630bc113a2020-09-07 13:02:11 +0200820 'material-drawer .main-header{background: var(--TWPT-drawer-background, #fff)!important; position: sticky; top: 0; z-index: 1;}');
821 }
822
avm99963698d3762021-02-16 01:19:54 +0100823 if (options.enhancedannouncementsdot) {
824 injectStylesheet(
825 chrome.runtime.getURL('injections/enhanced_announcements_dot.css'));
826 }
827
avm99963d98126f2021-02-17 10:44:36 +0100828 if (options.repositionexpandthread) {
829 injectStylesheet(
830 chrome.runtime.getURL('injections/reposition_expand_thread.css'));
831 }
832
avm99963129942f2020-09-08 02:07:18 +0200833 if (options.ccforcehidedrawer) {
834 var drawer = document.querySelector('material-drawer');
835 if (drawer !== null && drawer.classList.contains('mat-drawer-expanded')) {
836 document.querySelector('.material-drawer-button').click();
837 }
838 }
avm99963f5923962020-12-07 16:44:37 +0100839
840 if (options.batchlock) {
841 injectScript(chrome.runtime.getURL('injections/batchlock_inject.js'));
Adrià Vilanova Martínez74273ee2021-06-25 19:23:27 +0200842 injectStylesheet(chrome.runtime.getURL('injections/batchlock_inject.css'));
avm99963f5923962020-12-07 16:44:37 +0100843 }
avm999633eae4522021-04-22 01:14:27 +0200844
845 if (options.threadlistavatars) {
846 injectStylesheet(
847 chrome.runtime.getURL('injections/thread_list_avatars.css'));
848 }
avm99963a007d492021-05-02 12:32:03 +0200849
850 if (options.autorefreshlist) {
851 injectStylesheet(chrome.runtime.getURL('injections/autorefresh_list.css'));
852 }
avm99963129fb502020-08-28 05:18:53 +0200853});