-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
webext-options-sync.js
184 lines (158 loc) · 4.24 KB
/
webext-options-sync.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
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
// https://github.com/bfred-it/webext-options-sync
class OptionsSync {
constructor(storageName = 'options') {
this.storageName = storageName;
}
define(defs) {
defs = Object.assign({
defaults: {},
migrations: [],
}, defs);
if (chrome.runtime.onInstalled) { // In background script
chrome.runtime.onInstalled.addListener(() => this._applyDefinition(defs));
} else { // In content script, discouraged
this._applyDefinition(defs);
}
}
async _applyDefinition(defs) {
const options = Object.assign({}, defs.defaults, await this.getAll());
console.group('Appling definitions');
console.info('Current options:', options);
if (defs.migrations.length > 0) {
console.info('Running', defs.migrations.length, 'migrations');
defs.migrations.forEach(migrate => migrate(options, defs.defaults));
}
console.groupEnd();
this.setAll(options);
}
_parseNumbers(options) {
for (const name of Object.keys(options)) {
if (options[name] === String(Number(options[name]))) {
options[name] = Number(options[name]);
}
}
return options;
}
getAll() {
return new Promise(resolve => {
chrome.storage.sync.get(this.storageName,
keys => resolve(keys[this.storageName] || {})
);
}).then(this._parseNumbers);
}
setAll(newOptions) {
return new Promise(resolve => {
chrome.storage.sync.set({
[this.storageName]: newOptions,
}, resolve);
});
}
async set(newOptions) {
const options = await this.getAll();
this.setAll(Object.assign(options, newOptions));
}
syncForm(form) {
if (typeof form === 'string') {
form = document.querySelector(form);
}
this.getAll().then(options => OptionsSync._applyToForm(options, form));
form.addEventListener('input', e => this._handleFormUpdates(e));
form.addEventListener('change', e => this._handleFormUpdates(e));
chrome.storage.onChanged.addListener((changes, namespace) => {
if (namespace === 'sync') {
for (const key of Object.keys(changes)) {
const {newValue} = changes[key];
if (key === this.storageName) {
OptionsSync._applyToForm(newValue, form);
return;
}
}
}
});
}
static _applyToForm(options, form) {
console.group('Updating form');
for (const name of Object.keys(options)) {
const els = form.querySelectorAll(`[name="${CSS.escape(name)}"]`);
const [field] = els;
if (field) {
console.info(name, ':', options[name]);
switch (field.type) {
case 'checkbox':
if (typeof options[name] === 'boolean') {
field.checked = options[name];
} else {
const values = options[name].split('\u001C');
for (const checkbox of els) {
if (values.includes(checkbox.value)) {
checkbox.checked = true;
}
}
}
break;
case 'radio': {
const [selected] = [...els].filter(el => el.value === options[name]);
if (selected) {
selected.checked = true;
}
break;
}
default:
field.value = options[name];
break;
}
} else {
console.warn('Stored option {', name, ':', options[name], '} was not found on the page');
}
}
console.groupEnd();
}
_handleFormUpdates({target: el}) {
const {name} = el;
let {value} = el;
if (!name || !el.validity.valid) {
return;
}
switch (el.type) {
case 'select-one':
value = el.options[el.selectedIndex].value;
break;
case 'checkbox':
if (el.getAttribute('value')) {
const selector = `[name="${CSS.escape(name)}"]:checked`;
value = [...document.querySelectorAll(selector)].map(el => el.value).join('\u001C');
} else {
value = el.checked;
}
break;
default: break;
}
console.info('Saving option', el.name, 'to', value);
this.set({
[name]: value,
});
}
}
OptionsSync.migrations = {
removeUnused(options, defaults) {
for (const key of Object.keys(options)) {
if (!(key in defaults)) {
delete options[key];
}
}
}
};
if (typeof HTMLElement !== 'undefined') {
class OptionsSyncElement extends HTMLElement {
constructor() {
super();
new OptionsSync(this.getAttribute('storageName') || undefined).syncForm(this);
}
}
try {
customElements.define('options-sync', OptionsSyncElement);
} catch (error) {/* */}
}
if (typeof module === 'object') {
module.exports = OptionsSync;
}