This repository has been archived by the owner on Aug 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
reactionpacks.js
100 lines (78 loc) · 2.85 KB
/
reactionpacks.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
if (typeof browser === 'undefined') {
//noinspection ES6ConvertVarToLetConst,JSUnresolvedVariable
var browser = chrome;
}
const PACKS_API_PATH = `${document.location.protocol}//${document.location.host}/api/v1/packs/`;
const STORAGE = browser.storage.local;
/**
* Escape HTML special characters in template literals.
* @see https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2/
*/
function escape(templateData) {
let s = templateData[0];
for (let i = 1; i < arguments.length; i++) {
let arg = String(arguments[i]);
// Escape special characters in the substitution.
s += arg.replace(/[&"'<>]/g, (m) => ({"&": "&", '"': """, "'": "'", "<": "<", ">": ">"})[m]);
// Don't escape special characters in the template.
s += templateData[i];
}
return s;
}
function buildShowHideStylesheet(pack) {
return escape`.rp-extension-hook.hide-if-active-rp[data-rp='${pack['id']}'] {
display: none !important;
}
.rp-extension-hook.only-show-if-active-rp[data-rp='${pack['id']}'] {
display: block !important;
}
li.rp-extension-hook.only-show-if-active-rp[data-rp='${pack['id']}'] {
display: inline-block !important;
}`
}
function createRpStyleElement() {
const styleElem = document.createElement('style');
styleElem.id = 'reaction-pack-sheet';
styleElem.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(styleElem);
return styleElem;
}
function setPageStyle(sheet) {
let styleElem = document.getElementById('reaction-pack-sheet') || createRpStyleElement();
styleElem.textContent = sheet;
}
function fetchPackJson(id) {
return new Promise((resolve, reject) => {
const resource = PACKS_API_PATH + id;
fetch(resource)
.then(response => response.json())
.then(json => resolve(json));
});
}
STORAGE.get('pack', (store) => {
// For some reason, Firefox returns a 1-length array containing the
// store object, while Chrome returns the store object directly.
if (Array.isArray(store)) {
store = store[0];
}
if (store.pack) {
setTimeout(() => {
const stylesheet = buildShowHideStylesheet(store.pack);
setPageStyle(stylesheet);
}, 1);
}
});
Array.prototype.forEach.call(document.querySelectorAll('.use-pack'), (el) => {
el.addEventListener('click', (evt) => {
evt.preventDefault();
fetchPackJson(el.dataset.id)
.then(packJson => {
STORAGE.set({"pack": packJson.data});
return packJson.data
})
.then(pack => {
document.location.assign(`${document.location.protocol}//${document.location.host}/packs/${pack.id}`);
});
return false;
}, false);
});