aboutsummaryrefslogtreecommitdiff
path: root/ext/bg/js/settings/generic-setting-controller.js
blob: 04cad67db90e39d90c9021aab15ac9b7f3fd9dd4 (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
/*
 * 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/>.
 */

/* globals
 * DOMDataBinder
 */

class GenericSettingController {
    constructor(settingsController) {
        this._settingsController = settingsController;
        this._defaultScope = 'profile';
        this._dataBinder = new DOMDataBinder({
            selector: '[data-setting]',
            createElementMetadata: this._createElementMetadata.bind(this),
            compareElementMetadata: this._compareElementMetadata.bind(this),
            getValues: this._getValues.bind(this),
            setValues: this._setValues.bind(this)
        });
        this._transforms = new Map([
            ['setAttribute', this._setAttribute.bind(this)],
            ['setVisibility', this._setVisibility.bind(this)],
            ['splitTags', this._splitTags.bind(this)],
            ['joinTags', this._joinTags.bind(this)],
            ['toNumber', this._toNumber.bind(this)],
            ['toString', this._toString.bind(this)]
        ]);
    }

    async prepare() {
        this._dataBinder.observe(document.body);
        this._settingsController.on('optionsChanged', this._onOptionsChanged.bind(this));
    }

    async refresh() {
        await this._dataBinder.refresh();
    }

    // Private

    _onOptionsChanged() {
        this._dataBinder.refresh();
    }

    _createElementMetadata(element) {
        const {dataset: {setting: path, scope, transform: transformRaw}} = element;
        let transforms;
        if (typeof transformRaw === 'string') {
            transforms = JSON.parse(transformRaw);
            if (!Array.isArray(transforms)) { transforms = [transforms]; }
        } else {
            transforms = [];
        }
        return {
            path,
            scope,
            transforms,
            transformRaw
        };
    }

    _compareElementMetadata(metadata1, metadata2) {
        return (
            metadata1.path === metadata2.path &&
            metadata1.scope === metadata2.scope &&
            metadata1.transformRaw === metadata2.transformRaw
        );
    }

    async _getValues(targets) {
        const defaultScope = this._defaultScope;
        const settingsTargets = [];
        for (const {metadata: {path, scope}} of targets) {
            const target = {
                path,
                scope: scope || defaultScope
            };
            settingsTargets.push(target);
        }
        return this._transformResults(await this._settingsController.getSettings(settingsTargets), targets);
    }

    async _setValues(targets) {
        const defaultScope = this._defaultScope;
        const settingsTargets = [];
        for (const {metadata: {path, scope, transforms}, value, element} of targets) {
            const transformedValue = this._applyTransforms(value, transforms, 'pre', element);
            const target = {
                path,
                scope: scope || defaultScope,
                action: 'set',
                value: transformedValue
            };
            settingsTargets.push(target);
        }
        return this._transformResults(await this._settingsController.modifySettings(settingsTargets), targets);
    }

    _transformResults(values, targets) {
        return values.map((value, i) => {
            const error = value.error;
            if (error) { return jsonToError(error); }
            const {metadata: {transforms}, element} = targets[i];
            const result = this._applyTransforms(value.result, transforms, 'post', element);
            return {result};
        });
    }

    _applyTransforms(value, transforms, step, element) {
        for (const transform of transforms) {
            const transformStep = transform.step;
            if (typeof transformStep !== 'undefined' && transformStep !== step) { continue; }

            const transformFunction = this._transforms.get(transform.type);
            if (typeof transformFunction === 'undefined') { continue; }

            value = transformFunction(value, transform, element);
        }
        return value;
    }

    _getAncestor(node, ancestorDistance) {
        if (ancestorDistance < 0) {
            return document.documentElement;
        }
        for (let i = 0; i < ancestorDistance && node !== null; ++i) {
            node = node.parentNode;
        }
        return node;
    }

    _getRelativeElement(node, ancestorDistance, selector) {
        const selectorRoot = (
            typeof ancestorDistance === 'number' ?
            this._getAncestor(node, ancestorDistance) :
            document
        );
        if (selectorRoot === null) { return null; }

        return (
            typeof selector === 'string' ?
            selectorRoot.querySelector(selector) :
            (selectorRoot === document ? document.documentElement : selectorRoot)
        );
    }

    _evaluateSimpleOperation(operation, lhs, rhs) {
        switch (operation) {
            case '!': return !lhs;
            case '!!': return !!lhs;
            case '===': return lhs === rhs;
            case '!==': return lhs !== rhs;
            case '>=': return lhs >= rhs;
            case '<=': return lhs <= rhs;
            case '>': return lhs > rhs;
            case '<': return lhs < rhs;
            default: return false;
        }
    }

    // Transforms

    _setAttribute(value, data, element) {
        const {ancestorDistance, selector, attribute} = data;
        const relativeElement = this._getRelativeElement(element, ancestorDistance, selector);
        if (relativeElement !== null) {
            relativeElement.setAttribute(attribute, `${value}`);
        }
        return value;
    }

    _setVisibility(value, data, element) {
        const {ancestorDistance, selector, condition} = data;
        const relativeElement = this._getRelativeElement(element, ancestorDistance, selector);
        if (relativeElement !== null) {
            relativeElement.hidden = !this._evaluateSimpleOperation(condition.op, value, condition.value);
        }
        return value;
    }

    _splitTags(value) {
        return `${value}`.split(/[,; ]+/).filter((v) => !!v);
    }

    _joinTags(value) {
        return value.join(' ');
    }

    _toNumber(value, data) {
        let {constraints} = data;
        if (!isObject(constraints)) { constraints = {}; }
        return DOMDataBinder.convertToNumber(value, constraints);
    }

    _toString(value) {
        return `${value}`;
    }
}