aboutsummaryrefslogtreecommitdiff
path: root/ext/js/pages/settings/settings-controller.js
blob: a9f3a026f2130c0b9d04b5f49c69c57508355962 (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
/*
 * Copyright (C) 2023-2024  Yomitan Authors
 * Copyright (C) 2020-2022  Yomichan Authors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

import {EventDispatcher} from '../../core/event-dispatcher.js';
import {EventListenerCollection} from '../../core/event-listener-collection.js';
import {generateId, isObject} from '../../core/utilities.js';
import {OptionsUtil} from '../../data/options-util.js';
import {getAllPermissions} from '../../data/permissions-util.js';
import {HtmlTemplateCollection} from '../../dom/html-template-collection.js';

/**
 * @augments EventDispatcher<import('settings-controller').Events>
 */
export class SettingsController extends EventDispatcher {
    /**
     * @param {import('../../application.js').Application} application
     */
    constructor(application) {
        super();
        /** @type {import('../../application.js').Application} */
        this._application = application;
        /** @type {number} */
        this._profileIndex = 0;
        /** @type {string} */
        this._source = generateId(16);
        /** @type {Set<import('settings-controller').PageExitPrevention>} */
        this._pageExitPreventions = new Set();
        /** @type {EventListenerCollection} */
        this._pageExitPreventionEventListeners = new EventListenerCollection();
        /** @type {HtmlTemplateCollection} */
        this._templates = new HtmlTemplateCollection();
    }

    /** @type {import('../../application.js').Application} */
    get application() {
        return this._application;
    }

    /** @type {string} */
    get source() {
        return this._source;
    }

    /** @type {number} */
    get profileIndex() {
        return this._profileIndex;
    }

    set profileIndex(value) {
        if (this._profileIndex === value) { return; }
        this._setProfileIndex(value, true);
    }

    /** @type {HtmlTemplateCollection} */
    get templates() {
        return this._templates;
    }

    /** */
    async prepare() {
        await this._templates.loadFromFiles(['/templates-settings.html']);
        this._application.on('optionsUpdated', this._onOptionsUpdated.bind(this));
        if (this._canObservePermissionsChanges()) {
            chrome.permissions.onAdded.addListener(this._onPermissionsChanged.bind(this));
            chrome.permissions.onRemoved.addListener(this._onPermissionsChanged.bind(this));
        }
        const optionsFull = await this.getOptionsFull();
        const {profiles, profileCurrent} = optionsFull;
        if (profileCurrent >= 0 && profileCurrent < profiles.length) {
            this._profileIndex = profileCurrent;
        }
    }

    /** */
    async refresh() {
        await this._onOptionsUpdatedInternal(true);
    }

    /**
     * @returns {Promise<import('settings').ProfileOptions>}
     */
    async getOptions() {
        const optionsContext = this.getOptionsContext();
        return await this._application.api.optionsGet(optionsContext);
    }

    /**
     * @returns {Promise<import('settings').Options>}
     */
    async getOptionsFull() {
        return await this._application.api.optionsGetFull();
    }

    /**
     * @param {import('settings').Options} value
     */
    async setAllSettings(value) {
        const profileIndex = value.profileCurrent;
        await this._application.api.setAllSettings(value, this._source);
        this._setProfileIndex(profileIndex, true);
    }

    /**
     * @param {import('settings-modifications').ScopedRead[]} targets
     * @returns {Promise<import('settings-controller').ModifyResult[]>}
     */
    async getSettings(targets) {
        return await this._getSettings(targets, null);
    }

    /**
     * @param {import('settings-modifications').Read[]} targets
     * @returns {Promise<import('settings-controller').ModifyResult[]>}
     */
    async getGlobalSettings(targets) {
        return await this._getSettings(targets, {scope: 'global', optionsContext: null});
    }

    /**
     * @param {import('settings-modifications').Read[]} targets
     * @returns {Promise<import('settings-controller').ModifyResult[]>}
     */
    async getProfileSettings(targets) {
        return await this._getSettings(targets, {scope: 'profile', optionsContext: null});
    }

    /**
     * @param {import('settings-modifications').ScopedModification[]} targets
     * @returns {Promise<import('settings-controller').ModifyResult[]>}
     */
    async modifySettings(targets) {
        return await this._modifySettings(targets, null);
    }

    /**
     * @param {import('settings-modifications').Modification[]} targets
     * @returns {Promise<import('settings-controller').ModifyResult[]>}
     */
    async modifyGlobalSettings(targets) {
        return await this._modifySettings(targets, {scope: 'global', optionsContext: null});
    }

    /**
     * @param {import('settings-modifications').Modification[]} targets
     * @returns {Promise<import('settings-controller').ModifyResult[]>}
     */
    async modifyProfileSettings(targets) {
        return await this._modifySettings(targets, {scope: 'profile', optionsContext: null});
    }

    /**
     * @param {string} path
     * @param {unknown} value
     * @returns {Promise<import('settings-controller').ModifyResult[]>}
     */
    async setGlobalSetting(path, value) {
        return await this.modifyGlobalSettings([{action: 'set', path, value}]);
    }

    /**
     * @param {string} path
     * @param {unknown} value
     * @returns {Promise<import('settings-controller').ModifyResult[]>}
     */
    async setProfileSetting(path, value) {
        return await this.modifyProfileSettings([{action: 'set', path, value}]);
    }

    /**
     * @returns {Promise<import('dictionary-importer').Summary[]>}
     */
    async getDictionaryInfo() {
        return await this._application.api.getDictionaryInfo();
    }

    /**
     * @returns {import('settings').OptionsContext}
     */
    getOptionsContext() {
        return {index: this._profileIndex};
    }

    /**
     * @returns {import('settings-controller').PageExitPrevention}
     */
    preventPageExit() {
        /** @type {import('settings-controller').PageExitPrevention} */
        // eslint-disable-next-line sonarjs/prefer-object-literal
        const obj = {};
        obj.end = this._endPreventPageExit.bind(this, obj);
        if (this._pageExitPreventionEventListeners.size === 0) {
            this._pageExitPreventionEventListeners.addEventListener(window, 'beforeunload', this._onBeforeUnload.bind(this), false);
        }
        this._pageExitPreventions.add(obj);
        return obj;
    }

    /**
     * @param {string} name
     * @returns {Element}
     */
    instantiateTemplate(name) {
        return this._templates.instantiate(name);
    }

    /**
     * @param {string} name
     * @returns {DocumentFragment}
     */
    instantiateTemplateFragment(name) {
        return this._templates.instantiateFragment(name);
    }

    /**
     * @returns {Promise<import('settings').Options>}
     */
    async getDefaultOptions() {
        const optionsUtil = new OptionsUtil();
        await optionsUtil.prepare();
        return optionsUtil.getDefault();
    }

    // Private

    /**
     * @param {number} value
     * @param {boolean} canUpdateProfileIndex
     */
    _setProfileIndex(value, canUpdateProfileIndex) {
        this._profileIndex = value;
        this.trigger('optionsContextChanged', {});
        void this._onOptionsUpdatedInternal(canUpdateProfileIndex);
    }

    /**
     * @param {{source: string}} details
     */
    _onOptionsUpdated({source}) {
        if (source === this._source) { return; }
        void this._onOptionsUpdatedInternal(true);
    }

    /**
     * @param {boolean} canUpdateProfileIndex
     */
    async _onOptionsUpdatedInternal(canUpdateProfileIndex) {
        const optionsContext = this.getOptionsContext();
        try {
            const options = await this.getOptions();
            this.trigger('optionsChanged', {options, optionsContext});
        } catch (e) {
            if (canUpdateProfileIndex) {
                this._setProfileIndex(0, false);
                return;
            }
            throw e;
        }
    }

    /**
     * @param {import('settings-modifications').OptionsScope} target
     */
    _modifyOptionsScope(target) {
        if (target.scope === 'profile') {
            target.optionsContext = this.getOptionsContext();
        }
    }

    /**
     * @template {boolean} THasScope
     * @param {import('settings-controller').SettingsRead<THasScope>[]} targets
     * @param {import('settings-controller').SettingsExtraFields<THasScope>} extraFields
     * @returns {Promise<import('settings-controller').ModifyResult[]>}
     */
    async _getSettings(targets, extraFields) {
        const targets2 = targets.map((target) => {
            const target2 = /** @type {import('settings-controller').SettingsRead<true>} */ (Object.assign({}, extraFields, target));
            this._modifyOptionsScope(target2);
            return target2;
        });
        return await this._application.api.getSettings(targets2);
    }

    /**
     * @template {boolean} THasScope
     * @param {import('settings-controller').SettingsModification<THasScope>[]} targets
     * @param {import('settings-controller').SettingsExtraFields<THasScope>} extraFields
     * @returns {Promise<import('settings-controller').ModifyResult[]>}
     */
    async _modifySettings(targets, extraFields) {
        const targets2 = targets.map((target) => {
            const target2 = /** @type {import('settings-controller').SettingsModification<true>} */ (Object.assign({}, extraFields, target));
            this._modifyOptionsScope(target2);
            return target2;
        });
        return await this._application.api.modifySettings(targets2, this._source);
    }

    /**
     * @param {BeforeUnloadEvent} e
     * @returns {string|undefined}
     */
    _onBeforeUnload(e) {
        if (this._pageExitPreventions.size === 0) {
            return;
        }

        e.preventDefault();
        e.returnValue = '';
        return '';
    }

    /**
     * @param {import('settings-controller').PageExitPrevention} obj
     */
    _endPreventPageExit(obj) {
        this._pageExitPreventions.delete(obj);
        if (this._pageExitPreventions.size === 0) {
            this._pageExitPreventionEventListeners.removeAllEventListeners();
        }
    }

    /** */
    _onPermissionsChanged() {
        void this._triggerPermissionsChanged();
    }

    /** */
    async _triggerPermissionsChanged() {
        const eventName = 'permissionsChanged';
        if (!this.hasListeners(eventName)) { return; }

        const permissions = await getAllPermissions();
        this.trigger(eventName, {permissions});
    }

    /**
     * @returns {boolean}
     */
    _canObservePermissionsChanges() {
        return isObject(chrome.permissions) && isObject(chrome.permissions.onAdded) && isObject(chrome.permissions.onRemoved);
    }
}