summaryrefslogtreecommitdiff
path: root/test/document-util.test.js
blob: 518724220dfa4456edb53c5de2ae2abf1e55ad8d (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
/*
 * Copyright (C) 2023  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 {fileURLToPath} from 'node:url';
import path from 'path';
import {describe, expect} from 'vitest';
import {DocumentUtil} from '../ext/js/dom/document-util.js';
import {DOMTextScanner} from '../ext/js/dom/dom-text-scanner.js';
import {TextSourceElement} from '../ext/js/dom/text-source-element.js';
import {TextSourceRange} from '../ext/js/dom/text-source-range.js';
import {createDomTest} from './fixtures/dom-test.js';

const dirname = path.dirname(fileURLToPath(import.meta.url));

// DOMRect class definition
class DOMRect {
    /**
     * @param {number} x
     * @param {number} y
     * @param {number} width
     * @param {number} height
     */
    constructor(x, y, width, height) {
        /** @type {number} */
        this._x = x;
        /** @type {number} */
        this._y = y;
        /** @type {number} */
        this._width = width;
        /** @type {number} */
        this._height = height;
    }

    /** @type {number} */
    get x() { return this._x; }
    /** @type {number} */
    get y() { return this._y; }
    /** @type {number} */
    get width() { return this._width; }
    /** @type {number} */
    get height() { return this._height; }
    /** @type {number} */
    get left() { return this._x + Math.min(0, this._width); }
    /** @type {number} */
    get right() { return this._x + Math.max(0, this._width); }
    /** @type {number} */
    get top() { return this._y + Math.min(0, this._height); }
    /** @type {number} */
    get bottom() { return this._y + Math.max(0, this._height); }
    /** @returns {string} */
    toJSON() { return '<not implemented>'; }
}


/**
 * @param {Element} element
 * @param {string|undefined} selector
 * @returns {?Element}
 */
function querySelectorChildOrSelf(element, selector) {
    return selector ? element.querySelector(selector) : element;
}

/**
 * @param {import('jsdom').DOMWindow} window
 * @param {?Node} node
 * @returns {?Text|Node}
 */
function getChildTextNodeOrSelf(window, node) {
    if (node === null) { return null; }
    const Node = window.Node;
    const childNode = node.firstChild;
    return (childNode !== null && childNode.nodeType === Node.TEXT_NODE ? childNode : node);
}

/**
 * @param {unknown} value
 * @returns {unknown}
 */
function getPrototypeOfOrNull(value) {
    try {
        return Object.getPrototypeOf(value);
    } catch (e) {
        return null;
    }
}

/**
 * @param {Document} document
 * @returns {?Element}
 */
function findImposterElement(document) {
    // Finds the imposter element based on it's z-index style
    return document.querySelector('div[style*="2147483646"]>*');
}

const test = createDomTest(path.join(dirname, 'data/html/test-document1.html'));

describe('DocumentUtil', () => {
    test('Text scanning functions', ({window}) => {
        const {document} = window;
        for (const testElement of /** @type {NodeListOf<HTMLElement>} */ (document.querySelectorAll('.test[data-test-type=scan]'))) {
            // Get test parameters
            const {
                elementFromPointSelector,
                caretRangeFromPointSelector,
                startNodeSelector,
                startOffset,
                endNodeSelector,
                endOffset,
                resultType,
                sentenceScanExtent,
                sentence,
                hasImposter,
                terminateAtNewlines
            } = testElement.dataset;

            const elementFromPointValue = querySelectorChildOrSelf(testElement, elementFromPointSelector);
            const caretRangeFromPointValue = querySelectorChildOrSelf(testElement, caretRangeFromPointSelector);
            const startNode = getChildTextNodeOrSelf(window, querySelectorChildOrSelf(testElement, startNodeSelector));
            const endNode = getChildTextNodeOrSelf(window, querySelectorChildOrSelf(testElement, endNodeSelector));

            const startOffset2 = parseInt(/** @type {string} */ (startOffset), 10);
            const endOffset2 = parseInt(/** @type {string} */ (endOffset), 10);
            const sentenceScanExtent2 = parseInt(/** @type {string} */ (sentenceScanExtent), 10);
            const terminateAtNewlines2 = (terminateAtNewlines !== 'false');

            expect(elementFromPointValue).not.toStrictEqual(null);
            expect(caretRangeFromPointValue).not.toStrictEqual(null);
            expect(startNode).not.toStrictEqual(null);
            expect(endNode).not.toStrictEqual(null);

            // Setup functions
            document.elementFromPoint = () => elementFromPointValue;

            document.caretRangeFromPoint = (x, y) => {
                const imposter = getChildTextNodeOrSelf(window, findImposterElement(document));
                expect(!!imposter).toStrictEqual(hasImposter === 'true');

                const range = document.createRange();
                range.setStart(/** @type {Node} */ (imposter ? imposter : startNode), startOffset2);
                range.setEnd(/** @type {Node} */ (imposter ? imposter : startNode), endOffset2);

                // Override getClientRects to return a rect guaranteed to contain (x, y)
                range.getClientRects = () => {
                    /** @type {import('test/document-types').PseudoDOMRectList} */
                    const domRectList = Object.assign(
                        [new DOMRect(x - 1, y - 1, 2, 2)],
                        {
                            /**
                             * @this {DOMRect[]}
                             * @param {number} index
                             * @returns {DOMRect}
                             */
                            item: function item(index) { return this[index]; }
                        }
                    );
                    return domRectList;
                };
                return range;
            };

            // Test docRangeFromPoint
            const source = DocumentUtil.getRangeFromPoint(0, 0, {
                deepContentScan: false,
                normalizeCssZoom: true
            });
            switch (resultType) {
                case 'TextSourceRange':
                    expect(getPrototypeOfOrNull(source)).toStrictEqual(TextSourceRange.prototype);
                    break;
                case 'TextSourceElement':
                    expect(getPrototypeOfOrNull(source)).toStrictEqual(TextSourceElement.prototype);
                    break;
                case 'null':
                    expect(source).toStrictEqual(null);
                    break;
                default:
                    expect.unreachable();
                    break;
            }
            if (source === null) { continue; }

            // Sentence info
            const terminatorString = '…。..??!!';
            const terminatorMap = new Map();
            for (const char of terminatorString) {
                terminatorMap.set(char, [false, true]);
            }
            const quoteArray = [['「', '」'], ['『', '』'], ['\'', '\''], ['"', '"']];
            const forwardQuoteMap = new Map();
            const backwardQuoteMap = new Map();
            for (const [char1, char2] of quoteArray) {
                forwardQuoteMap.set(char1, [char2, false]);
                backwardQuoteMap.set(char2, [char1, false]);
            }

            // Test docSentenceExtract
            const sentenceActual = DocumentUtil.extractSentence(
                source,
                false,
                sentenceScanExtent2,
                terminateAtNewlines2,
                terminatorMap,
                forwardQuoteMap,
                backwardQuoteMap
            ).text;
            expect(sentenceActual).toStrictEqual(sentence);

            // Clean
            source.cleanup();
        }
    });
});

describe('DOMTextScanner', () => {
    test('Seek functions', async ({window}) => {
        const {document} = window;
        for (const testElement of /** @type {NodeListOf<HTMLElement>} */ (document.querySelectorAll('.test[data-test-type=text-source-range-seek]'))) {
            // Get test parameters
            const {
                seekNodeSelector,
                seekNodeIsText,
                seekOffset,
                seekLength,
                seekDirection,
                expectedResultNodeSelector,
                expectedResultNodeIsText,
                expectedResultOffset,
                expectedResultContent
            } = testElement.dataset;

            const seekOffset2 = parseInt(/** @type {string} */ (seekOffset), 10);
            const seekLength2 = parseInt(/** @type {string} */ (seekLength), 10);
            const expectedResultOffset2 = parseInt(/** @type {string} */ (expectedResultOffset), 10);

            /** @type {?Node} */
            let seekNode = testElement.querySelector(/** @type {string} */ (seekNodeSelector));
            if (seekNodeIsText === 'true' && seekNode !== null) {
                seekNode = seekNode.firstChild;
            }

            /** @type {?Node} */
            let expectedResultNode = testElement.querySelector(/** @type {string} */ (expectedResultNodeSelector));
            if (expectedResultNodeIsText === 'true' && expectedResultNode !== null) {
                expectedResultNode = expectedResultNode.firstChild;
            }

            const {node, offset, content} = (
                seekDirection === 'forward' ?
                new DOMTextScanner(/** @type {Node} */ (seekNode), seekOffset2, true, false).seek(seekLength2) :
                new DOMTextScanner(/** @type {Node} */ (seekNode), seekOffset2, true, false).seek(-seekLength2)
            );

            expect(node).toStrictEqual(expectedResultNode);
            expect(offset).toStrictEqual(expectedResultOffset2);
            expect(content).toStrictEqual(expectedResultContent);
        }
    });
});