summaryrefslogtreecommitdiff
path: root/ext/bg/js/settings/dictionary-controller.js
blob: d2ff831f3cd80e7fea5e5e2a099678a096e09c7a (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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
/*
 * Copyright (C) 2020  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/>.
 */

/* global
 * DictionaryDatabase
 * ObjectPropertyAccessor
 * api
 */

class DictionaryEntry {
    constructor(dictionaryController, node, dictionaryInfo) {
        this._dictionaryController = dictionaryController;
        this._node = node;
        this._dictionaryInfo = dictionaryInfo;
        this._eventListeners = new EventListenerCollection();
        this._detailsContainer = null;
        this._hasDetails = false;
        this._hasCounts = false;
    }

    get node() {
        return this._node;
    }

    get dictionaryTitle() {
        return this._dictionaryInfo.title;
    }

    prepare() {
        const node = this._node;
        const {title, revision, prefixWildcardsSupported, version} = this._dictionaryInfo;

        this._detailsContainer = node.querySelector('.dictionary-details');

        const enabledCheckbox = node.querySelector('.dictionary-enabled');
        const allowSecondarySearchesCheckbox = node.querySelector('.dictionary-allow-secondary-searches');
        const priorityInput = node.querySelector('.dictionary-priority');
        const deleteButton = node.querySelector('.dictionary-delete-button');
        const menuButton = node.querySelector('.dictionary-menu-button');
        const detailsTable = node.querySelector('.dictionary-details-table');
        const detailsToggleLink = node.querySelector('.dictionary-details-toggle-link');
        const outdatedContainer = node.querySelector('.dictionary-outdated-notification');
        const titleNode = node.querySelector('.dictionary-title');
        const versionNode = node.querySelector('.dictionary-version');
        const wildcardSupportedCheckbox = node.querySelector('.dictionary-prefix-wildcard-searches-supported');

        const hasDetails = this._setupDetails(detailsTable);
        this._hasDetails = hasDetails;

        titleNode.textContent = title;
        versionNode.textContent = `rev.${revision}`;
        wildcardSupportedCheckbox.checked = !!prefixWildcardsSupported;

        outdatedContainer.hidden = (version >= 3);
        if (detailsToggleLink !== null) { detailsToggleLink.hidden = !hasDetails; }

        enabledCheckbox.dataset.setting = ObjectPropertyAccessor.getPathString(['dictionaries', title, 'enabled']);
        priorityInput.dataset.setting = ObjectPropertyAccessor.getPathString(['dictionaries', title, 'priority']);
        if (allowSecondarySearchesCheckbox !== null) {
            allowSecondarySearchesCheckbox.dataset.setting = ObjectPropertyAccessor.getPathString(['dictionaries', title, 'allowSecondarySearches']);
        }

        if (deleteButton !== null) {
            this._eventListeners.addEventListener(deleteButton, 'click', this._onDeleteButtonClicked.bind(this), false);
        }
        if (menuButton !== null) {
            this._eventListeners.addEventListener(menuButton, 'menuOpened', this._onMenuOpened.bind(this), false);
            this._eventListeners.addEventListener(menuButton, 'menuClosed', this._onMenuClosed.bind(this), false);
        }
        if (detailsToggleLink !== null && this._detailsContainer !== null) {
            this._eventListeners.addEventListener(detailsToggleLink, 'click', this._onDetailsToggleLinkClicked.bind(this), false);
        }
        this._eventListeners.addEventListener(priorityInput, 'settingChanged', this._onPriorityChanged.bind(this), false);
    }

    cleanup() {
        this._eventListeners.removeAllEventListeners();
        const node = this._node;
        if (node.parentNode !== null) {
            node.parentNode.removeChild(node);
        }
    }

    setCounts(counts) {
        const node = this._node.querySelector('.dictionary-counts');
        node.textContent = JSON.stringify({info: this._dictionaryInfo, counts}, null, 4);
        node.hidden = false;
        this._hasCounts = true;
    }

    // Private

    _onDeleteButtonClicked(e) {
        e.preventDefault();
        this._delete();
    }

    _onMenuOpened(e) {
        const {detail: {menu}} = e;
        const showDetails = menu.querySelector('.popup-menu-item[data-menu-action="showDetails"]');
        const hideDetails = menu.querySelector('.popup-menu-item[data-menu-action="hideDetails"]');
        const hasDetails = (this._detailsContainer !== null && (this._hasDetails || this._hasCounts));
        const detailsVisible = (hasDetails && !this._detailsContainer.hidden);
        if (showDetails !== null) {
            showDetails.hidden = detailsVisible;
            showDetails.disabled = !hasDetails;
        }
        if (hideDetails !== null) {
            hideDetails.hidden = !detailsVisible;
            hideDetails.disabled = !hasDetails;
        }
    }

    _onMenuClosed(e) {
        const {detail: {action}} = e;
        switch (action) {
            case 'delete':
                this._delete();
                break;
            case 'showDetails':
                if (this._detailsContainer !== null) { this._detailsContainer.hidden = false; }
                break;
            case 'hideDetails':
                if (this._detailsContainer !== null) { this._detailsContainer.hidden = true; }
                break;
        }
    }

    _onDetailsToggleLinkClicked(e) {
        e.preventDefault();
        this._detailsContainer.hidden = !this._detailsContainer.hidden;
    }

    _onPriorityChanged(e) {
        const {detail: {value}} = e;
        this._node.style.order = `${-value}`;
    }

    _setupDetails(detailsTable) {
        const targets = [
            ['Author', 'author'],
            ['URL', 'url'],
            ['Description', 'description'],
            ['Attribution', 'attribution']
        ];

        const dictionaryInfo = this._dictionaryInfo;
        const fragment = document.createDocumentFragment();
        let any = false;
        for (const [label, key] of targets) {
            const info = dictionaryInfo[key];
            if (typeof info !== 'string') { continue; }

            const details = this._dictionaryController.instantiateTemplate('dictionary-details-entry');
            details.dataset.type = key;
            details.querySelector('.dictionary-details-entry-label').textContent = `${label}:`;
            details.querySelector('.dictionary-details-entry-info').textContent = info;
            fragment.appendChild(details);

            any = true;
        }

        detailsTable.appendChild(fragment);
        return any;
    }

    _delete() {
        this._dictionaryController.deleteDictionary(this.dictionaryTitle);
    }
}

class DictionaryController {
    constructor(settingsController, modalController, storageController, statusFooter=null) {
        this._settingsController = settingsController;
        this._modalController = modalController;
        this._storageController = storageController;
        this._statusFooter = statusFooter;
        this._dictionaries = null;
        this._dictionaryEntries = [];
        this._databaseStateToken = null;
        this._checkingIntegrity = false;
        this._checkIntegrityButton = null;
        this._dictionaryEntryContainer = null;
        this._integrityExtraInfoContainer = null;
        this._dictionaryInstallCountNode = null;
        this._deleteDictionaryModal = null;
        this._integrityExtraInfoNode = null;
        this._isDeleting = false;
    }

    async prepare() {
        this._checkIntegrityButton = document.querySelector('#dictionary-check-integrity');
        this._dictionaryEntryContainer = document.querySelector('#dictionary-list');
        this._integrityExtraInfoContainer = document.querySelector('#dictionary-list-extra');
        this._dictionaryInstallCountNode = document.querySelector('#dictionary-install-count');
        this._noDictionariesInstalledWarnings = document.querySelectorAll('.no-dictionaries-installed-warning');
        this._deleteDictionaryModal = this._modalController.getModal('dictionary-confirm-delete');

        yomichan.on('databaseUpdated', this._onDatabaseUpdated.bind(this));

        document.querySelector('#dictionary-confirm-delete-button').addEventListener('click', this._onDictionaryConfirmDelete.bind(this), false);
        this._checkIntegrityButton.addEventListener('click', this._onCheckIntegrityButtonClick.bind(this), false);

        await this._onDatabaseUpdated();
    }

    deleteDictionary(dictionaryTitle) {
        if (this._isDeleting) { return; }
        const modal = this._deleteDictionaryModal;
        modal.node.dataset.dictionaryTitle = dictionaryTitle;
        modal.node.querySelector('#dictionary-confirm-delete-name').textContent = dictionaryTitle;
        modal.setVisible(true);
    }

    instantiateTemplate(name) {
        return this._settingsController.instantiateTemplate(name);
    }

    // Private

    async _onDatabaseUpdated() {
        const token = {};
        this._databaseStateToken = token;
        this._dictionaries = null;
        const dictionaries = await this._settingsController.getDictionaryInfo();
        if (this._databaseStateToken !== token) { return; }
        this._dictionaries = dictionaries;

        this._updateMainDictionarySelectOptions(dictionaries);

        for (const entry of this._dictionaryEntries) {
            entry.cleanup();
        }
        this._dictionaryEntries = [];

        if (this._dictionaryInstallCountNode !== null) {
            this._dictionaryInstallCountNode.textContent = `${dictionaries.length}`;
        }

        const hasDictionary = (dictionaries.length > 0);
        for (const node of this._noDictionariesInstalledWarnings) {
            node.hidden = hasDictionary;
        }

        await this._ensureDictionarySettings(dictionaries);
        for (const dictionary of dictionaries) {
            this._createDictionaryEntry(dictionary);
        }
    }

    _onDictionaryConfirmDelete(e) {
        e.preventDefault();

        const modal = this._deleteDictionaryModal;
        modal.setVisible(false);

        const title = modal.node.dataset.dictionaryTitle;
        if (typeof title !== 'string') { return; }
        delete modal.node.dataset.dictionaryTitle;

        this._deleteDictionary(title);
    }

    _onCheckIntegrityButtonClick(e) {
        e.preventDefault();
        this._checkIntegrity();
    }

    _updateMainDictionarySelectOptions(dictionaries) {
        for (const select of document.querySelectorAll('[data-setting="general.mainDictionary"]')) {
            const fragment = document.createDocumentFragment();

            let option = document.createElement('option');
            option.className = 'text-muted';
            option.value = '';
            option.textContent = 'Not selected';
            fragment.appendChild(option);

            for (const {title, sequenced} of dictionaries) {
                if (!sequenced) { continue; }
                option = document.createElement('option');
                option.value = title;
                option.textContent = title;
                fragment.appendChild(option);
            }

            select.textContent = ''; // Empty
            select.appendChild(fragment);
        }
    }

    async _checkIntegrity() {
        if (this._dictionaries === null || this._checkingIntegrity || this._isDeleting) { return; }

        try {
            this._checkingIntegrity = true;
            this._setButtonsEnabled(false);

            const token = this._databaseStateToken;
            const dictionaryTitles = this._dictionaries.map(({title}) => title);
            const {counts, total} = await api.getDictionaryCounts(dictionaryTitles, true);
            if (this._databaseStateToken !== token) { return; }

            for (let i = 0, ii = Math.min(counts.length, this._dictionaryEntries.length); i < ii; ++i) {
                const entry = this._dictionaryEntries[i];
                entry.setCounts(counts[i]);
            }

            this._setCounts(counts, total);
        } finally {
            this._setButtonsEnabled(true);
            this._checkingIntegrity = false;
        }
    }

    _setCounts(dictionaryCounts, totalCounts) {
        const remainders = Object.assign({}, totalCounts);
        const keys = Object.keys(remainders);

        for (const counts of dictionaryCounts) {
            for (const key of keys) {
                remainders[key] -= counts[key];
            }
        }

        let totalRemainder = 0;
        for (const key of keys) {
            totalRemainder += remainders[key];
        }

        this._cleanupExtra();
        if (totalRemainder > 0) {
            this.extra = this._createExtra(totalCounts, remainders, totalRemainder);
        }
    }

    _createExtra(totalCounts, remainders, totalRemainder) {
        const node = this.instantiateTemplate('dictionary-extra');
        this._integrityExtraInfoNode = node;

        node.querySelector('.dictionary-total-count').textContent = `${totalRemainder} item${totalRemainder !== 1 ? 's' : ''}`;

        const n = node.querySelector('.dictionary-counts');
        n.textContent = JSON.stringify({counts: totalCounts, remainders}, null, 4);
        n.hidden = false;

        this._integrityExtraInfoContainer.appendChild(node);
    }

    _cleanupExtra() {
        const node = this._integrityExtraInfoNode;
        if (node === null) { return; }
        this._integrityExtraInfoNode = null;

        const parent = node.parentNode;
        if (parent === null) { return; }

        parent.removeChild(node);
    }

    _createDictionaryEntry(dictionary) {
        const node = this.instantiateTemplate('dictionary');
        this._dictionaryEntryContainer.appendChild(node);

        const entry = new DictionaryEntry(this, node, dictionary);
        this._dictionaryEntries.push(entry);
        entry.prepare();
    }

    async _deleteDictionary(dictionaryTitle) {
        if (this._isDeleting || this._checkingIntegrity) { return; }

        const index = this._dictionaryEntries.findIndex((entry) => entry.dictionaryTitle === dictionaryTitle);
        if (index < 0) { return; }

        const storageController = this._storageController;
        const statusFooter = this._statusFooter;
        const {node} = this._dictionaryEntries[index];
        const progressSelector = '.dictionary-delete-progress';
        const progressContainers = [
            ...node.querySelectorAll('.progress-container'),
            ...document.querySelectorAll(`#dictionaries ${progressSelector}`)
        ];
        const progressBars = [
            ...node.querySelectorAll('.progress-bar'),
            ...document.querySelectorAll(`${progressSelector} .progress-bar`)
        ];
        const infoLabels = document.querySelectorAll(`${progressSelector} .progress-info`);
        const statusLabels = document.querySelectorAll(`${progressSelector} .progress-status`);
        const prevention = this._settingsController.preventPageExit();
        try {
            this._isDeleting = true;
            this._setButtonsEnabled(false);

            const onProgress = ({processed, count, storeCount, storesProcesed}) => {
                const percent = (
                    (count > 0 && storesProcesed > 0) ?
                    (processed / count) * (storesProcesed / storeCount) * 100.0 :
                    0.0
                );
                const cssString = `${percent}%`;
                const statusString = `${percent.toFixed(0)}%`;
                for (const progressBar of progressBars) { progressBar.style.width = cssString; }
                for (const label of statusLabels) { label.textContent = statusString; }
            };

            onProgress({processed: 0, count: 1, storeCount: 1, storesProcesed: 0});

            for (const progress of progressContainers) { progress.hidden = false; }
            for (const label of infoLabels) { label.textContent = 'Deleting dictionary...'; }
            if (statusFooter !== null) { statusFooter.setTaskActive(progressSelector, true); }

            await this._deleteDictionaryInternal(dictionaryTitle, onProgress);
            await this._deleteDictionarySettings(dictionaryTitle);
        } catch (e) {
            yomichan.logError(e);
        } finally {
            prevention.end();
            for (const progress of progressContainers) { progress.hidden = true; }
            if (statusFooter !== null) { statusFooter.setTaskActive(progressSelector, false); }
            this._setButtonsEnabled(true);
            storageController.updateStats();
            this._isDeleting = false;
        }
    }

    _setButtonsEnabled(value) {
        value = !value;
        for (const node of document.querySelectorAll('.dictionary-database-mutating-input')) {
            node.disabled = value;
        }
    }

    async _deleteDictionaryInternal(dictionaryTitle, onProgress) {
        const dictionaryDatabase = await this._getPreparedDictionaryDatabase();
        try {
            await dictionaryDatabase.deleteDictionary(dictionaryTitle, {rate: 1000}, onProgress);
            api.triggerDatabaseUpdated('dictionary', 'delete');
        } finally {
            dictionaryDatabase.close();
        }
    }

    async _getPreparedDictionaryDatabase() {
        const dictionaryDatabase = new DictionaryDatabase();
        await dictionaryDatabase.prepare();
        return dictionaryDatabase;
    }

    async _deleteDictionarySettings(dictionaryTitle) {
        const optionsFull = await this._settingsController.getOptionsFull();
        const {profiles} = optionsFull;
        const targets = [];
        for (let i = 0, ii = profiles.length; i < ii; ++i) {
            const {options: {dictionaries}} = profiles[i];
            if (Object.prototype.hasOwnProperty.call(dictionaries, dictionaryTitle)) {
                const path = ObjectPropertyAccessor.getPathString(['profiles', i, 'options', 'dictionaries', dictionaryTitle]);
                targets.push({action: 'delete', path});
            }
        }
        await this._settingsController.modifyGlobalSettings(targets);
    }

    async _ensureDictionarySettings(dictionaries2) {
        const optionsFull = await this._settingsController.getOptionsFull();
        const {profiles} = optionsFull;
        const targets = [];
        for (const {title} of dictionaries2) {
            for (let i = 0, ii = profiles.length; i < ii; ++i) {
                const {options: {dictionaries: dictionaryOptions}} = profiles[i];
                if (Object.prototype.hasOwnProperty.call(dictionaryOptions, title)) { continue; }

                const path = ObjectPropertyAccessor.getPathString(['profiles', i, 'options', 'dictionaries', title]);
                targets.push({
                    action: 'set',
                    path,
                    value: DictionaryController.createDefaultDictionarySettings()
                });
            }
        }

        if (targets.length > 0) {
            await this._settingsController.modifyGlobalSettings(targets);
        }
    }

    static createDefaultDictionarySettings() {
        return {
            enabled: false,
            allowSecondarySearches: false,
            priority: 0
        };
    }
}