|
1 | 1 | import { assert } from 'vitest'; |
2 | 2 |
|
3 | | -/** @param {Element} node */ |
4 | | -function clean_children(node) { |
| 3 | +/** |
| 4 | + * @param {Element} node |
| 5 | + * @param {{ preserveComments: boolean }} opts |
| 6 | + */ |
| 7 | +function clean_children(node, opts) { |
5 | 8 | let previous = null; |
6 | 9 | let has_element_children = false; |
7 | 10 | let template = |
@@ -56,20 +59,26 @@ function clean_children(node) { |
56 | 59 |
|
57 | 60 | continue; |
58 | 61 | } |
59 | | - } else if (child.nodeType === 8) { |
| 62 | + } |
| 63 | + |
| 64 | + if (child.nodeType === 8 && !opts.preserveComments) { |
60 | 65 | // comment |
61 | 66 | child.remove(); |
62 | 67 | continue; |
63 | | - } else if (child.nodeType === 1) { |
| 68 | + } |
| 69 | + |
| 70 | + if (child.nodeType === 1 || child.nodeType === 8) { |
64 | 71 | if (previous?.nodeType === 3) { |
65 | 72 | const prev = /** @type {Text} */ (previous); |
66 | 73 | prev.data = prev.data.replace(/^[^\S]+$/, '\n'); |
67 | | - } else if (previous?.nodeType === 1) { |
| 74 | + } else if (previous?.nodeType === 1 || previous?.nodeType === 8) { |
68 | 75 | node.insertBefore(document.createTextNode('\n'), child); |
69 | 76 | } |
70 | 77 |
|
71 | | - has_element_children = true; |
72 | | - clean_children(/** @type {Element} */ (child)); |
| 78 | + if (child.nodeType === 1) { |
| 79 | + has_element_children = true; |
| 80 | + clean_children(/** @type {Element} */ (child), opts); |
| 81 | + } |
73 | 82 | } |
74 | 83 |
|
75 | 84 | previous = child; |
@@ -103,9 +112,9 @@ function clean_children(node) { |
103 | 112 | export function normalize_html(window, html, { preserveComments = false } = {}) { |
104 | 113 | try { |
105 | 114 | const node = window.document.createElement('div'); |
106 | | - node.innerHTML = html.replace(/(<!(--)?.*?\2>)/g, preserveComments ? '$1' : '').trim(); |
107 | 115 |
|
108 | | - clean_children(node); |
| 116 | + node.innerHTML = html.trim(); |
| 117 | + clean_children(node, { preserveComments }); |
109 | 118 |
|
110 | 119 | return node.innerHTML; |
111 | 120 | } catch (err) { |
|
0 commit comments