/
index.ts
290 lines (245 loc) · 8.38 KB
/
index.ts
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
import {debounce} from 'throttle-debounce';
import {isBackgroundPage} from 'webext-detect-page';
import {serialize, deserialize} from 'dom-form-serializer/lib';
import {compressToEncodedURIComponent as compress, decompressFromEncodedURIComponent as decompress} from 'lz-string';
/**
@example
{
// Recommended
defaults: {
color: 'blue'
},
// Optional
migrations: [
savedOptions => {
if (savedOptions.oldStuff) {
delete savedOptions.oldStuff;
}
}
],
}
*/
interface Setup<TOptions extends Options> {
storageName?: string;
logging?: boolean;
defaults?: TOptions;
/**
* A list of functions to call when the extension is updated.
*/
migrations?: Array<Migration<TOptions>>;
}
/**
A map of options as strings or booleans. The keys will have to match the form fields' `name` attributes.
*/
interface Options {
[key: string]: string | number | boolean;
}
/*
Handler signature for when an extension updates.
*/
export type Migration<TOptions extends Options> = (savedOptions: TOptions, defaults: TOptions) => void;
class OptionsSync<TOptions extends Options> {
public static migrations = {
/**
Helper method that removes any option that isn't defined in the defaults. It's useful to avoid leaving old options taking up space.
*/
removeUnused(options: Options, defaults: Options) {
for (const key of Object.keys(options)) {
if (!(key in defaults)) {
delete options[key];
}
}
}
};
storageName: string;
defaults: TOptions;
private _form!: HTMLFormElement;
private readonly _migrations: Promise<void>;
/**
@constructor Returns an instance linked to the chosen storage.
@param setup - Configuration for `webext-options-sync`
*/
constructor({
// `as` reason: https://github.com/fregante/webext-options-sync/pull/21#issuecomment-500314074
defaults = {} as TOptions,
storageName = 'options',
migrations = [],
logging = true
}: Setup<TOptions> = {}) {
this.storageName = storageName;
this.defaults = defaults;
this._handleFormInput = debounce(600, this._handleFormInput.bind(this));
this._handleStorageChangeOnForm = this._handleStorageChangeOnForm.bind(this);
if (logging === false) {
this._log = () => {};
}
this._migrations = this._runMigrations(migrations);
}
/**
Retrieves all the options stored.
@returns Promise that will resolve with **all** the options stored, as an object.
@example
const optionsStorage = new OptionsSync();
const options = await optionsStorage.getAll();
console.log('The user’s options are', options);
if (options.color) {
document.body.style.color = color;
}
*/
async getAll(): Promise<TOptions> {
await this._migrations;
return this._getAll();
}
/**
Overrides **all** the options stored with your `options`.
@param newOptions - A map of default options as strings or booleans. The keys will have to match the form fields' `name` attributes.
*/
async setAll(newOptions: TOptions): Promise<void> {
await this._migrations;
return this._setAll(newOptions);
}
/**
Merges new options with the existing stored options.
@param newOptions - A map of default options as strings or booleans. The keys will have to match the form fields' `name` attributes.
*/
async set(newOptions: Partial<TOptions>): Promise<void> {
return this.setAll({...await this.getAll(), ...newOptions});
}
/**
Any defaults or saved options will be loaded into the `<form>` and any change will automatically be saved via `chrome.storage.sync`.
@param selector - The `<form>` that needs to be synchronized or a CSS selector (one element).
The form fields' `name` attributes will have to match the option names.
*/
async syncForm(form: string | HTMLFormElement): Promise<void> {
this._form = form instanceof HTMLFormElement ?
form :
document.querySelector<HTMLFormElement>(form)!;
this._form.addEventListener('input', this._handleFormInput);
this._form.addEventListener('submit', this._handleFormSubmit);
chrome.storage.onChanged.addListener(this._handleStorageChangeOnForm);
this._updateForm(this._form, await this.getAll());
}
/**
Removes any listeners added by `syncForm`
*/
async stopSyncForm(): Promise<void> {
if (this._form) {
this._form.removeEventListener('input', this._handleFormInput);
this._form.removeEventListener('submit', this._handleFormSubmit);
chrome.storage.onChanged.removeListener(this._handleStorageChangeOnForm);
delete this._form;
}
}
private _log(method: keyof Console, ...args: any[]): void {
console[method](...args);
}
private async _getAll(): Promise<TOptions> {
return new Promise<TOptions>((resolve, reject) => {
chrome.storage.sync.get(this.storageName, result => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
resolve(this._decode(result[this.storageName]));
}
});
});
}
private async _setAll(newOptions: TOptions): Promise<void> {
this._log('log', 'Saving options', newOptions);
return new Promise((resolve, reject) => {
chrome.storage.sync.set({
[this.storageName]: this._encode(newOptions)
}, () => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
resolve();
}
});
});
}
private _encode(options: TOptions): string {
const thinnedOptions: Partial<TOptions> = {...options};
for (const [key, value] of Object.entries(thinnedOptions)) {
if (this.defaults[key] === value) {
delete thinnedOptions[key];
}
}
this._log('log', 'Without the default values', thinnedOptions);
return compress(JSON.stringify(thinnedOptions));
}
private _decode(options: string|TOptions): TOptions {
let decompressed = options;
if (typeof options === 'string') {
decompressed = JSON.parse(decompress(options));
}
return {...this.defaults, ...decompressed as TOptions};
}
private async _runMigrations(migrations: Array<Migration<TOptions>>): Promise<void> {
if (migrations.length === 0 || !isBackgroundPage()) {
return;
}
const {installType} = await new Promise(resolve => chrome.management.getSelf(resolve));
// Chrome doesn't run `onInstalled` when launching the browser with a pre-loaded development extension #25
if (installType !== 'development') {
await new Promise(resolve => chrome.runtime.onInstalled.addListener(resolve));
}
const options = await this._getAll();
const initial = JSON.stringify(options);
this._log('log', 'Found these stored options', {...options});
this._log('info', 'Will run', migrations.length, migrations.length === 1 ? 'migration' : ' migrations');
migrations.forEach(migrate => migrate(options, this.defaults));
// Only save to storage if there were any changes
if (initial !== JSON.stringify(options)) {
await this._setAll(options);
}
}
private async _handleFormInput({target}: Event): Promise<void> {
const field = target as HTMLInputElement;
if (!field.name) {
return;
}
await this.set(this._parseForm(field.form!));
field.form!.dispatchEvent(new CustomEvent('options-sync:form-synced', {
bubbles: true
}));
}
private _handleFormSubmit(event: Event): void {
event.preventDefault();
}
private _updateForm(form: HTMLFormElement, options: TOptions): void {
// Reduce changes to only values that have changed
const currentFormState = this._parseForm(form);
for (const [key, value] of Object.entries(options)) {
if (currentFormState[key] === value) {
delete options[key];
}
}
const include = Object.keys(options);
if (include.length > 0) {
// Limits `deserialize` to only the specified fields. Without it, it will try to set the every field, even if they're missing from the supplied `options`
deserialize(form, options, {include});
}
}
// Parse form into object, except invalid fields
private _parseForm(form: HTMLFormElement): Partial<TOptions> {
const include: string[] = [];
// Don't serialize disabled and invalid fields
for (const field of form.querySelectorAll<HTMLInputElement>('[name]')) {
if (field.validity.valid && !field.disabled) {
include.push(field.name.replace(/\[.*\]/, ''));
}
}
return serialize(form, {include});
}
private _handleStorageChangeOnForm(changes: Record<string, any>, areaName: string): void {
if (
areaName === 'sync' &&
changes[this.storageName] &&
(!document.hasFocus() || !this._form.contains(document.activeElement)) // Avoid applying changes while the user is editing a field
) {
this._updateForm(this._form, this._decode(changes[this.storageName].newValue));
}
}
}
export default OptionsSync;