blob: 6344e3c326074c69dc1baf800b32cabbcb1e5680 [file] [log] [blame]
Adrià Vilanova Martínez2d9be8d2022-12-28 00:50:14 +01001import {getOptions} from '../../../common/optionsUtils.js';
2import {softRefreshView} from '../utils/common.js';
3
4import * as consts from './constants.js';
5
6export default class ThreadToolbar {
7 constructor() {
8 this.getOptions().then(options => {
9 this.updateBodyClasses(options);
10 });
11 }
12
13 updateBodyClasses(options) {
14 if (this.shouldSeeToolbar(options))
15 document.body.classList.add('TWPT-threadtoolbar-shown');
16 else
17 document.body.classList.remove('TWPT-threadtoolbar-shown');
18
19 if (options.flattenthreads && options.flattenthreads_switch_enabled)
20 document.body.classList.add('TWPT-flattenthreads-enabled');
21 else
22 document.body.classList.remove('TWPT-flattenthreads-enabled');
23 }
24
25 shouldSeeToolbar(options) {
26 return Object.values(options).some(option => !!option);
27 }
28
29 getOptions() {
30 return getOptions(['flattenthreads', 'flattenthreads_switch_enabled']);
31 }
32
33 inject(node, options) {
34 const toolbar = document.createElement('twpt-thread-toolbar-inject');
35 toolbar.setAttribute('options', JSON.stringify(options));
36 toolbar.addEventListener(consts.kEventFlattenThreadsUpdated, e => {
37 const enabled = e.detail?.enabled;
38 if (typeof enabled != 'boolean') return;
39 chrome.storage.sync.set({flattenthreads_switch_enabled: enabled}, _ => {
40 softRefreshView();
41 });
42 });
43 node.parentElement.insertBefore(toolbar, node);
44 }
45
46 injectIfApplicable(node) {
47 this.getOptions().then(options => {
48 this.updateBodyClasses(options);
49 if (!this.shouldSeeToolbar(options)) return;
50 return this.inject(node, options);
51 });
52 }
53
54 shouldInject(node) {
55 return node.matches(consts.kRepliesSectionSelector);
56 }
57}