summaryrefslogtreecommitdiff
path: root/ext/bg/js/query-parser.js
blob: af1dd30ba83a131b4804d726ba282ad4a6823e8f (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
/*
 * Copyright (C) 2019-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
 * TextScanner
 * api
 */

class QueryParser extends EventDispatcher {
    constructor({getOptionsContext, setSpinnerVisible, documentUtil}) {
        super();
        this._getOptionsContext = getOptionsContext;
        this._setSpinnerVisible = setSpinnerVisible;
        this._selectedParser = null;
        this._documentUtil = documentUtil;
        this._parseResults = [];
        this._queryParser = document.querySelector('#query-parser-content');
        this._queryParserModeContainer = document.querySelector('#query-parser-mode-container');
        this._queryParserModeSelect = document.querySelector('#query-parser-mode-select');
        this._textScanner = new TextScanner({
            node: this._queryParser,
            ignoreElements: () => [],
            ignorePoint: null,
            getOptionsContext,
            documentUtil,
            searchTerms: true,
            searchKanji: false,
            searchOnClick: true
        });
    }

    prepare() {
        this._textScanner.prepare();
        this._textScanner.on('searched', this._onSearched.bind(this));
        this._queryParserModeSelect.addEventListener('change', this._onParserChange.bind(this), false);
    }

    setOptions({selectedParser, termSpacing, scanning}) {
        if (selectedParser === null || typeof selectedParser === 'string') {
            this._selectedParser = selectedParser;
        }
        if (typeof termSpacing === 'boolean') {
            this._queryParser.dataset.termSpacing = `${termSpacing}`;
        }
        if (scanning !== null && typeof scanning === 'object') {
            this._textScanner.setOptions(scanning);
        }
        this._textScanner.setEnabled(true);
    }

    async setText(text) {
        this._setSpinnerVisible(true);

        this._setPreview(text);

        this._parseResults = await api.textParse(text, this._getOptionsContext());
        this._refreshSelectedParser();

        this._renderParserSelect();
        this._renderParseResult();

        this._setSpinnerVisible(false);
    }

    // Private

    _onSearched({type, definitions, sentence, input, textSource, optionsContext, error}) {
        if (error !== null) {
            yomichan.logError(error);
            return;
        }
        if (type === null) { return; }

        this.trigger('searched', {
            type,
            definitions,
            sentence,
            input,
            textSource,
            optionsContext
        });
    }

    _onParserChange(e) {
        const value = e.currentTarget.value;
        this._setSelectedParser(value);
    }

    _refreshSelectedParser() {
        if (this._parseResults.length > 0 && !this._getParseResult()) {
            const value = this._parseResults[0].id;
            this._setSelectedParser(value);
        }
    }

    _setSelectedParser(value) {
        const optionsContext = this._getOptionsContext();
        api.modifySettings([{
            action: 'set',
            path: 'parsing.selectedParser',
            value,
            scope: 'profile',
            optionsContext
        }], 'search');
    }

    _getParseResult() {
        const selectedParser = this._selectedParser;
        return this._parseResults.find((r) => r.id === selectedParser);
    }

    _setPreview(text) {
        const terms = [[{text, reading: ''}]];
        this._queryParser.textContent = '';
        this._queryParser.appendChild(this._createParseResult(terms, true));
    }

    _renderParserSelect() {
        const visible = (this._parseResults.length > 1);
        if (visible) {
            this._updateParserModeSelect(this._queryParserModeSelect, this._parseResults, this._selectedParser);
        }
        this._queryParserModeContainer.hidden = !visible;
    }

    _renderParseResult() {
        const parseResult = this._getParseResult();
        this._queryParser.textContent = '';
        if (!parseResult) { return; }
        this._queryParser.appendChild(this._createParseResult(parseResult.content, false));
    }

    _updateParserModeSelect(select, parseResults, selectedParser) {
        const fragment = document.createDocumentFragment();

        let index = 0;
        let selectedIndex = -1;
        for (const parseResult of parseResults) {
            const option = document.createElement('option');
            option.value = parseResult.id;
            switch (parseResult.source) {
                case 'scanning-parser':
                    option.textContent = 'Scanning parser';
                    break;
                case 'mecab':
                    option.textContent = `MeCab: ${parseResult.dictionary}`;
                    break;
                default:
                    option.textContent = `Unknown source: ${parseResult.source}`;
                    break;
            }
            fragment.appendChild(option);

            if (selectedParser === parseResult.id) {
                selectedIndex = index;
            }
            ++index;
        }

        select.textContent = '';
        select.appendChild(fragment);
        select.selectedIndex = selectedIndex;
    }

    _createParseResult(terms, preview) {
        const type = preview ? 'preview' : 'normal';
        const fragment = document.createDocumentFragment();
        for (const term of terms) {
            const termNode = document.createElement('span');
            termNode.className = 'query-parser-term';
            termNode.dataset.type = type;
            for (const segment of term) {
                if (segment.reading.trim().length === 0) {
                    this._addSegmentText(segment.text, termNode);
                } else {
                    termNode.appendChild(this._createSegment(segment));
                }
            }
            fragment.appendChild(termNode);
        }
        return fragment;
    }

    _createSegment(segment) {
        const segmentNode = document.createElement('ruby');
        segmentNode.className = 'query-parser-segment';

        const textNode = document.createElement('span');
        textNode.className = 'query-parser-segment-text';

        const readingNode = document.createElement('rt');
        readingNode.className = 'query-parser-segment-reading';

        segmentNode.appendChild(textNode);
        segmentNode.appendChild(readingNode);

        this._addSegmentText(segment.text, textNode);
        readingNode.textContent = segment.reading;

        return segmentNode;
    }

    _addSegmentText(text, container) {
        for (const character of text) {
            const node = document.createElement('span');
            node.className = 'query-parser-char';
            node.textContent = character;
            container.appendChild(node);
        }
    }
}