summaryrefslogtreecommitdiff
path: root/ext/js/display/option-toggle-hotkey-handler.js
blob: ba4c8578f43a16553cc720fe888a8d68a0e57a2e (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
/*
 * Copyright (C) 2023  Yomitan Authors
 * Copyright (C) 2021-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 {generateId} from '../core.js';
import {ExtensionError} from '../core/extension-error.js';
import {toError} from '../core/to-error.js';
import {yomitan} from '../yomitan.js';

export class OptionToggleHotkeyHandler {
    /**
     * @param {import('./display.js').Display} display
     */
    constructor(display) {
        /** @type {import('./display.js').Display} */
        this._display = display;
        /** @type {?import('./display-notification.js').DisplayNotification} */
        this._notification = null;
        /** @type {?import('core').Timeout} */
        this._notificationHideTimer = null;
        /** @type {number} */
        this._notificationHideTimeout = 5000;
        /** @type {string} */
        this._source = `option-toggle-hotkey-handler-${generateId(16)}`;
    }

    /** @type {number} */
    get notificationHideTimeout() {
        return this._notificationHideTimeout;
    }

    set notificationHideTimeout(value) {
        this._notificationHideTimeout = value;
    }

    /** */
    prepare() {
        this._display.hotkeyHandler.registerActions([
            ['toggleOption', this._onHotkeyActionToggleOption.bind(this)]
        ]);
    }

    // Private

    /**
     * @param {unknown} argument
     */
    _onHotkeyActionToggleOption(argument) {
        if (typeof argument !== 'string') { return; }
        this._toggleOption(argument);
    }

    /**
     * @param {string} path
     */
    async _toggleOption(path) {
        let value;
        try {
            const optionsContext = this._display.getOptionsContext();

            const getSettingsResponse = (await yomitan.api.getSettings([{
                scope: 'profile',
                path,
                optionsContext
            }]))[0];
            const {error: getSettingsError} = getSettingsResponse;
            if (typeof getSettingsError !== 'undefined') {
                throw ExtensionError.deserialize(getSettingsError);
            }

            value = getSettingsResponse.result;
            if (typeof value !== 'boolean') {
                throw new Error(`Option value of type ${typeof value} cannot be toggled`);
            }

            value = !value;

            /** @type {import('settings-modifications').ScopedModificationSet} */
            const modification = {
                scope: 'profile',
                action: 'set',
                path,
                value,
                optionsContext
            };
            const modifySettingsResponse = (await yomitan.api.modifySettings([modification], this._source))[0];
            const {error: modifySettingsError} = modifySettingsResponse;
            if (typeof modifySettingsError !== 'undefined') {
                throw ExtensionError.deserialize(modifySettingsError);
            }

            this._showNotification(this._createSuccessMessage(path, value), true);
        } catch (e) {
            this._showNotification(this._createErrorMessage(path, e), false);
        }
    }

    /**
     * @param {string} path
     * @param {unknown} value
     * @returns {DocumentFragment}
     */
    _createSuccessMessage(path, value) {
        const fragment = document.createDocumentFragment();
        const n1 = document.createElement('em');
        n1.textContent = path;
        const n2 = document.createElement('strong');
        n2.textContent = `${value}`;
        fragment.appendChild(document.createTextNode('Option '));
        fragment.appendChild(n1);
        fragment.appendChild(document.createTextNode(' changed to '));
        fragment.appendChild(n2);
        return fragment;
    }

    /**
     * @param {string} path
     * @param {unknown} error
     * @returns {DocumentFragment}
     */
    _createErrorMessage(path, error) {
        const message = toError(error).message;
        const fragment = document.createDocumentFragment();
        const n1 = document.createElement('em');
        n1.textContent = path;
        const n2 = document.createElement('div');
        n2.textContent = message;
        n2.className = 'danger-text';
        fragment.appendChild(document.createTextNode('Failed to toggle option '));
        fragment.appendChild(n1);
        fragment.appendChild(document.createTextNode(': '));
        fragment.appendChild(n2);
        return fragment;
    }

    /**
     * @param {DocumentFragment} message
     * @param {boolean} autoClose
     */
    _showNotification(message, autoClose) {
        if (this._notification === null) {
            this._notification = this._display.createNotification(false);
            this._notification.node.addEventListener('click', this._onNotificationClick.bind(this), false);
        }

        this._notification.setContent(message);
        this._notification.open();

        this._stopHideNotificationTimer();
        if (autoClose) {
            this._notificationHideTimer = setTimeout(this._onNotificationHideTimeout.bind(this), this._notificationHideTimeout);
        }
    }

    /**
     * @param {boolean} animate
     */
    _hideNotification(animate) {
        if (this._notification === null) { return; }
        this._notification.close(animate);
        this._stopHideNotificationTimer();
    }

    /** */
    _stopHideNotificationTimer() {
        if (this._notificationHideTimer !== null) {
            clearTimeout(this._notificationHideTimer);
            this._notificationHideTimer = null;
        }
    }

    /** */
    _onNotificationHideTimeout() {
        this._notificationHideTimer = null;
        this._hideNotification(true);
    }

    /** */
    _onNotificationClick() {
        this._stopHideNotificationTimer();
    }
}