« get me outta code hell

main.js « popup « extension - interactive-bgm - Browser extension that adds background music based on the site you're browsing
about summary refs log tree commit diff
path: root/extension/popup/main.js
blob: cb51c753d467127fcc69d80ccf2976818de59ce4 (plain)
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
import {getRuleScoreOnPage, getURLParts} from '../lib.js';

function last(arr) {
    return arr[arr.length - 1];
}

function clearChildren(el) {
    while (el.firstChild) {
        el.removeChild(el.firstChild);
    }
}

function changeScreen(id) {
    for (const screen of document.getElementsByClassName('screen')) {
        if (screen.id === id) {
            screen.classList.add('visible');
        } else {
            screen.classList.remove('visible');
        }
    }
}

function changeContentScreen(id) {
    for (const screen of document.getElementsByClassName('content-screen')) {
        if (screen.id === id) {
            screen.classList.add('visible');
        } else {
            screen.classList.remove('visible');
        }
    }
}

function loadTrackList(opts) {
    const {tab, rule, saveRule, deleteRule} = opts;
    const {music} = rule;
    saveRule();
    return browser.storage.sync.get('tracks').then(({tracks = []}) => {
        const ul = document.getElementById('track-list');
        while (ul.firstChild) {
            ul.removeChild(ul.firstChild);
        }

        tracks.sort();

        for (const track of tracks) {
            const li = document.createElement('li');
            ul.appendChild(li);

            li.classList.add('track');

            const topRow = document.createElement('div');
            li.appendChild(topRow);

            const label = document.createElement('label');
            topRow.appendChild(label);

            topRow.classList.add('top-row');

            const checkbox = document.createElement('input');
            label.appendChild(checkbox);

            checkbox.type = 'checkbox';
            checkbox.checked = track in music;
            checkbox.title = `Toggle whether the track "${track}" will play when this site is opened.`

            checkbox.addEventListener('click', () => {
                updateVolumeSlider();
                if (checkbox.checked) {
                    if (!(track in music)) {
                        music[track] = volumeSlider.value;
                    }
                } else {
                    if (track in music) {
                        delete music[track];
                    }
                }
                saveRule();
            });

            label.appendChild(document.createTextNode(' ' + track));

            const deleteButton = document.createElement('button');
            topRow.appendChild(deleteButton);

            deleteButton.appendChild(document.createTextNode('Delete...'));
            deleteButton.title = `Delete the track from all site configuration. You will be confirmed first.`;

            deleteButton.addEventListener('click', () => {
                if (confirm(`This will delete "${track}" from ALL sites - this cannot be undone. Are you sure?`)) {
                    changeScreen('loading-screen');
                    tracks = tracks.filter(t => t !== track);
                    for (const site of Object.values(siteSettings)) {
                        while (site.includes(track)) {
                            site.splice(site.indexOf(track, 1));
                        }
                    }
                    Promise.all([
                        browser.runtime.sendMessage({type: 'deleteTrack', trackName: track}),
                        browser.storage.sync.set({tracks, siteSettings})
                            .then(() => loadTrackList(opts))
                    ]).then(() => changeScreen('main-screen'));
                }
            });

            const bottomRow = document.createElement('div');
            li.appendChild(bottomRow);

            const volumeLabel = document.createElement('label');
            bottomRow.appendChild(volumeLabel);

            volumeLabel.appendChild(document.createTextNode('Volume: '));

            const updateVolumeSlider = () => {
                volumeLabel.style.display = checkbox.checked ? 'block' : 'none';
            };

            const volumeSlider = document.createElement('input');
            volumeLabel.appendChild(volumeSlider);

            updateVolumeSlider();

            volumeSlider.type = 'range';
            volumeSlider.min = 0;
            volumeSlider.max = 100;
            volumeSlider.step = 1;
            volumeSlider.value = track in music ? music[track] : 100;

            volumeSlider.addEventListener('change', () => {
                if (track in music) {
                    music[track] = volumeSlider.value;
                    saveRule();
                }
            });
        }

        const actionLi = document.createElement('li');
        ul.appendChild(actionLi);

        actionLi.classList.add('action');

        const addButton = document.createElement('button');
        actionLi.appendChild(addButton);

        addButton.appendChild(document.createTextNode('Create Track'));
        addButton.title = `Create a new track, which will be an option present in all sites.`;

        addButton.addEventListener('click', () => {
            browser.tabs.sendMessage(tab.id, {createTrack: true});
            window.close();
        });

        const deleteRuleButton = document.createElement('button');
        actionLi.appendChild(deleteRuleButton);

        deleteRuleButton.appendChild(document.createTextNode('Delete Rule'));
        deleteRuleButton.title = `Remove this rule altogether. It will be discarded and won't affect the BGM anymore.`;

        deleteRuleButton.addEventListener('click', () => {
            if (confirm(`Are you sure you want to delete this entry? (${getWildcardRepresentation(rule)})`)) {
                deleteRule();
            }
        });
    });
}

function getWildcardRepresentation(rule, verbose = false) {
    const {hostnameMatch, pathnameMatch} = rule;
    const {hostnameParts, pathnameParts} = getURLParts(rule.sourceURL);

    let string = verbose ? 'http(s)://' : '';

    if (hostnameMatch.length !== hostnameParts.length) {
        if (hostnameMatch.length > 0) {
            string += '*.';
        } else {
            string += '*';
        }
    }

    string += hostnameMatch.slice().reverse().join('.');

    if (pathnameMatch.length) {
        string += '/';
    }

    string += pathnameMatch.join('/');

    if (!pathnameMatch.length || !last(pathnameMatch).includes('.')) {
        string += '/*';
    }

    return string;
}

function loadRuleScreen({tab, rule, saveRule, deleteRule}) {
    if (getRuleScoreOnPage(rule, tab.url) > 0) {
        rule.sourceURL = tab.url;
    }

    const heading = document.getElementById('hostname');
    while (heading.firstChild) {
        heading.removeChild(heading.firstChild);
    }

    const hostnameSpans = [];
    const pathnameSpans = [];

    const isSelected = s => s.dataset.selected === 'yes';

    const setSelected = (s, val) => {
        s.dataset.selected = val ? 'yes' : 'no';
    };

    const toggleSelected = s => {
        setSelected(s, !isSelected(s));
    };

    const updateWildcardRepresentation = () => {
        const string = getWildcardRepresentation(rule, true);

        const el = document.getElementById('wildcard-representation');
        while (el.firstChild) {
            el.removeChild(el.firstChild);
        }
        el.appendChild(document.createTextNode(string));
    };

    const addPart = (span, allSpans, save) => {
        heading.appendChild(span);

        span.style.cursor = 'pointer';

        span.classList.add('scope');

        const getSubordinateSpans = () => {
            const index = allSpans.indexOf(span);
            return allSpans.slice(0, index + 1);
        };

        const getSuperiorSpans = () => {
            const index = allSpans.indexOf(span);
            return allSpans.slice(index + 1);
        };

        span.addEventListener('mouseenter', () => {
            for (const s of getSubordinateSpans()) {
                s.classList.add('highlighted');
            }
        });

        span.addEventListener('mouseleave', () => {
            for (const s of getSubordinateSpans()) {
                s.classList.remove('highlighted');
            }
        });

        span.addEventListener('click', () => {
            if (last(allSpans.filter(isSelected)) === span) {
                toggleSelected(span);
            } else {
                setSelected(span, true);
            }

            for (const s of getSubordinateSpans()) {
                s.classList.remove('highlighted');
                setSelected(s, isSelected(span));
            }

            for (const s of getSuperiorSpans()) {
                setSelected(s, false);
            }

            save(getSubordinateSpans().filter(isSelected).map(s => s.dataset.partValue));
        });
    };

    const {hostnameMatch, pathnameMatch} = rule;
    const {hostnameParts, pathnameParts} = getURLParts(rule.sourceURL);

    for (let i = 0; i < hostnameParts.length; i++) {
        const part = hostnameParts[i];
        const span = document.createElement('span');
        span.appendChild(document.createTextNode(part));
        if (i < hostnameParts.length - 1) {
            span.appendChild(document.createTextNode('.'));
        }
        span.dataset.partValue = part;
        setSelected(span, hostnameMatch[hostnameParts.length - i - 1] === part);
        hostnameSpans.unshift(span);
        addPart(span, hostnameSpans, val => {
            rule.hostnameMatch = val;
            updateWildcardRepresentation();
            saveRule();
        });
    }

    for (let i = 0; i < pathnameParts.length; i++) {
        const part = pathnameParts[i];
        const span = document.createElement('span');
        span.appendChild(document.createTextNode('/'));
        span.appendChild(document.createTextNode(part));
        span.dataset.partValue = part;
        setSelected(span, pathnameMatch[i] === part);
        pathnameSpans.push(span);
        addPart(span, pathnameSpans, val => {
            rule.pathnameMatch = val;
            updateWildcardRepresentation();
            saveRule();
        });
    }

    updateWildcardRepresentation();

    if (hostname) {
        return loadTrackList({tab, rule, saveRule, deleteRule})
            .then(() => changeScreen('main-screen'));
    } else {
        changeScreen('invalid-host-screen');
    }
}

function loadRuleList({tab, siteSettings, selectRule}) {
    const createRuleItem = rule => {
        const li = document.createElement('li');

        li.classList.add('rule');
        li.dataset.wildcardRepresentation = getWildcardRepresentation(rule);
        li.appendChild(document.createTextNode(li.dataset.wildcardRepresentation));
        li.title = li.dataset.wildcardRepresentation;

        li.addEventListener('click', () => {
            selectRule(rule);
        });

        return li;
    };

    const allRulesList = document.getElementById('all-rules');
    clearChildren(allRulesList);

    const allRules = siteSettings;

    const allRuleItems = allRules.map(createRuleItem);

    allRuleItems.sort((a, b) => a.dataset.wildcardRepresentation < b.dataset.wildcardRepresentation ? -1 : 1);

    for (const item of allRuleItems) {
        allRulesList.appendChild(item);
    }

    const rulesOnThisPageList = document.getElementById('rules-on-this-page');
    clearChildren(rulesOnThisPageList);

    const createRuleLI = document.createElement('li');
    rulesOnThisPageList.appendChild(createRuleLI);

    const createRuleButton = document.createElement('button');
    createRuleLI.appendChild(createRuleButton);

    createRuleButton.appendChild(document.createTextNode('Create Rule'));

    if (!new URL(tab.url).hostname) {
        createRuleButton.disabled = true;
        createRuleButton.title = `Sorry, this page doesn't appear to have a hostname. We can't create a rule here.`;
    }

    createRuleButton.addEventListener('click', () => {
        const {hostnameParts} = getURLParts(tab.url);
        const rule = {
            sourceURL: tab.url,
            hostnameMatch: hostnameParts.slice().reverse(),
            pathnameMatch: [],
            music: {}
        };
        selectRule(rule);
    });

    const rulesOnThisPage = allRules.map(rule => ({
        rule,
        score: getRuleScoreOnPage(rule, tab.url)
    })).filter(obj => obj.score > 0);

    for (const obj of rulesOnThisPage) {
        obj.item = createRuleItem(obj.rule);
    }

    rulesOnThisPage.sort((a, b) => {
        if (a.score === b.score) {
            return a.item.dataset.wildcardRepresentation < b.item.dataset.wildcardRepresentation ? -1 : 1;
        } else {
            return b.score - a.score;
        }
    });

    for (const {item} of rulesOnThisPage) {
        rulesOnThisPageList.appendChild(item);
    }
}

Promise.all([
    browser.tabs.query({active: true, currentWindow: true}),
    browser.storage.sync.get(['disableEverywhere', 'siteSettings'])
]).then(([[tab], {disableEverywhere: disableEverywhereStatus, siteSettings}]) => {
    if (!Array.isArray(siteSettings)) {
        siteSettings = [];
    }

    console.log(siteSettings);

    const reloadRuleList = () => {
        return browser.storage.sync.get('siteSettings').then(({siteSettings}) => loadRuleList({
            tab, siteSettings,
            selectRule: rule => {
                changeContentScreen('loading-content');
                return loadRuleScreen({
                    rule, tab,
                    saveRule: () => {
                        if (!siteSettings.includes(rule)) {
                            siteSettings.push(rule);
                        }
                        return browser.storage.sync.set({siteSettings})
                            .then(() => browser.runtime.sendMessage({music: rule.music}))
                            .then(() => reloadRuleList());
                    },
                    deleteRule: () => {
                        changeScreen('loading-screen');
                        siteSettings = siteSettings.filter(r => r !== rule);
                        reloadRuleList();
                        return browser.storage.sync.set({siteSettings})
                            .then(() => reloadRuleList())
                            .then(() => {
                                changeScreen('main-screen')
                                changeContentScreen('no-rule-content');
                            });
                    }
                }).then(() => changeContentScreen('rule-content'));
            }
        }));
    };

    const disableEverywhere = document.getElementById('disable-everywhere');

    disableEverywhere.checked = disableEverywhereStatus;

    disableEverywhere.addEventListener('click', () => {
        browser.storage.sync.set({disableEverywhere: disableEverywhere.checked})
            .then(() => browser.runtime.sendMessage({urlString: tab.url}));
    });

    reloadRuleList().then(() => changeScreen('main-screen'));
});