aboutsummaryrefslogtreecommitdiff
path: root/ext/js/dom/simple-dom-parser.js
blob: adc009bfb1b9821771815ab288837e66989ec33e (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
/*
 * Copyright (C) 2023-2024  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 * as parse5 from '../../lib/parse5.js';

/**
 * @augments import('simple-dom-parser').ISimpleDomParser
 */
export class SimpleDOMParser {
    /**
     * @param {string} content
     */
    constructor(content) {
        /** @type {import('parse5')} */
        // @ts-expect-error - parse5 global is not defined in typescript declaration
        this._parse5Lib = /** @type {import('parse5')} */ (parse5);
        /** @type {import('parse5').TreeAdapter<import('parse5').DefaultTreeAdapterMap>} */
        this._treeAdapter = this._parse5Lib.defaultTreeAdapter;
        /** @type {import('simple-dom-parser').Parse5Document} */
        this._document = this._parse5Lib.parse(content, {
            treeAdapter: this._treeAdapter
        });
        /** @type {RegExp} */
        this._patternHtmlWhitespace = /[\t\r\n\f ]+/g;
    }

    /**
     * @param {string} id
     * @param {import('simple-dom-parser').Element} [root]
     * @returns {?import('simple-dom-parser').Element}
     */
    getElementById(id, root) {
        for (const node of this._allNodes(root)) {
            if (!this._treeAdapter.isElementNode(node) || this.getAttribute(node, 'id') !== id) { continue; }
            return node;
        }
        return null;
    }

    /**
     * @param {string} tagName
     * @param {import('simple-dom-parser').Element} [root]
     * @returns {?import('simple-dom-parser').Element}
     */
    getElementByTagName(tagName, root) {
        for (const node of this._allNodes(root)) {
            if (!this._treeAdapter.isElementNode(node) || node.tagName !== tagName) { continue; }
            return node;
        }
        return null;
    }

    /**
     * @param {string} tagName
     * @param {import('simple-dom-parser').Element} [root]
     * @returns {import('simple-dom-parser').Element[]}
     */
    getElementsByTagName(tagName, root) {
        const results = [];
        for (const node of this._allNodes(root)) {
            if (!this._treeAdapter.isElementNode(node) || node.tagName !== tagName) { continue; }
            results.push(node);
        }
        return results;
    }

    /**
     * @param {string} className
     * @param {import('simple-dom-parser').Element} [root]
     * @returns {import('simple-dom-parser').Element[]}
     */
    getElementsByClassName(className, root) {
        const results = [];
        for (const node of this._allNodes(root)) {
            if (!this._treeAdapter.isElementNode(node)) { continue; }
            const nodeClassName = this.getAttribute(node, 'class');
            if (nodeClassName !== null && this._hasToken(nodeClassName, className)) {
                results.push(node);
            }
        }
        return results;
    }

    /**
     * @param {import('simple-dom-parser').Element} element
     * @param {string} attribute
     * @returns {?string}
     */
    getAttribute(element, attribute) {
        for (const attr of /** @type {import('simple-dom-parser').Parse5Element} */ (element).attrs) {
            if (
                attr.name === attribute &&
                typeof attr.namespace === 'undefined'
            ) {
                return attr.value;
            }
        }
        return null;
    }

    /**
     * @param {import('simple-dom-parser').Element} element
     * @returns {string}
     */
    getTextContent(element) {
        let source = '';
        for (const node of this._allNodes(element)) {
            if (this._treeAdapter.isTextNode(node)) {
                source += node.value;
            }
        }
        return source;
    }

    /**
     * @returns {boolean}
     */
    static isSupported() {
        return typeof parse5 !== 'undefined';
    }

    // Private

    /**
     * @param {import('simple-dom-parser').Element|undefined} root
     * @returns {Generator<import('simple-dom-parser').Parse5ChildNode, void, unknown>}
     * @yields {import('simple-dom-parser').Parse5ChildNode}
     */
    *_allNodes(root) {
        // Depth-first pre-order traversal
        /** @type {import('simple-dom-parser').Parse5ChildNode[]} */
        const nodeQueue = [];
        if (typeof root !== 'undefined') {
            nodeQueue.push(/** @type {import('simple-dom-parser').Parse5Element} */ (root));
        } else {
            nodeQueue.push(...this._document.childNodes);
        }
        while (nodeQueue.length > 0) {
            const node = /** @type {import('simple-dom-parser').Parse5ChildNode} */ (nodeQueue.pop());
            yield node;
            if (this._treeAdapter.isElementNode(node)) {
                const {childNodes} = node;
                if (typeof childNodes !== 'undefined') {
                    for (let i = childNodes.length - 1; i >= 0; --i) {
                        nodeQueue.push(childNodes[i]);
                    }
                }
            }
        }
    }

    /**
     * @param {string} tokenListString
     * @param {string} token
     * @returns {boolean}
     */
    _hasToken(tokenListString, token) {
        let start = 0;
        const pattern = this._patternHtmlWhitespace;
        pattern.lastIndex = 0;
        while (true) {
            const match = pattern.exec(tokenListString);
            const end = match === null ? tokenListString.length : match.index;
            if (end > start && tokenListString.substring(start, end) === token) { return true; }
            if (match === null) { return false; }
            start = end + match[0].length;
        }
    }
}