Skip to content

Commit d6df6d6

Browse files
committed
Replace DOMParser with template for fragment
This brings the code in line w/: <https://github.com/syntax-tree/hast-util-from-html-isomorphic> Closes GH-23.
1 parent 8db7662 commit d6df6d6

File tree

1 file changed

+22
-23
lines changed

1 file changed

+22
-23
lines changed
+22-23
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/**
22
* @import {Root} from 'hast'
33
* @import {Options} from 'rehype-dom-parse'
4-
* @import {Parser, Processor} from 'unified'
4+
* @import {Processor} from 'unified'
55
*/
66

77
import {fromDom} from 'hast-util-from-dom'
@@ -22,42 +22,41 @@ export default function parse(options) {
2222

2323
self.parser = parser
2424

25-
/** @type {Parser<Root>} */
25+
/**
26+
* @param {string} value
27+
* Value to parse.
28+
* @returns {Root}
29+
* Tree.
30+
*/
2631
function parser(value) {
27-
const create = settings.fragment === false ? createDocument : createFragment
32+
const create = settings.fragment === false ? parseDocument : parseFragment
2833
// Assume document/fragment in -> root out.
2934
return /** @type {Root} */ (fromDom(create(value)))
3035
}
3136
}
3237

3338
/**
34-
* Create a fragment.
39+
* Create a document.
3540
*
3641
* @param {string} value
37-
* HTML.
38-
* @returns {DocumentFragment}
39-
* Document fragment.
42+
* Value to parse.
43+
* @returns {Document}
44+
* Document.
4045
*/
41-
function createFragment(value) {
42-
const node = createDocument('<!doctype html><body>' + value)
43-
44-
/**
45-
* Pretend as a DocumentFragment node, which is fine for `fromDom`.
46-
*/
47-
return /** @type {DocumentFragment} */ ({
48-
nodeType: 11,
49-
childNodes: node.body.childNodes
50-
})
46+
function parseDocument(value) {
47+
return new DOMParser().parseFromString(value, 'text/html')
5148
}
5249

5350
/**
54-
* Create a document.
51+
* Parse as a fragment.
5552
*
5653
* @param {string} value
57-
* HTML.
58-
* @returns {Document}
59-
* Document.
54+
* Value to parse.
55+
* @returns {DocumentFragment}
56+
* Document fragment.
6057
*/
61-
function createDocument(value) {
62-
return new DOMParser().parseFromString(value, 'text/html')
58+
function parseFragment(value) {
59+
const template = document.createElement('template')
60+
template.innerHTML = value
61+
return template.content
6362
}

0 commit comments

Comments
 (0)