-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
79 lines (72 loc) · 2.06 KB
/
index.js
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
import React from "react";
import ReactDOM from "react-dom";
import JsxParser from "react-jsx-parser";
export let TEMPLATING_ERROR = /<!--.*ERROR MESSAGE STARTS HERE.*-->/;
/**
* @param {{[key: string]: React.ElementType}} components
* @param {Element} root
* @param {() => void} [callback]
* @returns {void}
*/
export function render(components, root, callback) {
if (!TEMPLATING_ERROR.test(root.innerHTML)) {
const restoreCallback = () => {
restoreComments(root);
if (callback instanceof Function) {
callback();
}
};
ReactDOM.render(parse(components, root), root, restoreCallback);
}
}
function parse(components, root) {
return parseJSX(components, escapeComments(extractJSX(root)));
}
function parseJSX(components, jsx) {
return React.createElement(
JsxParser,
{ components, jsx, disableFragments: true, renderInWrapper: false },
null
);
}
function escapeComments(jsx) {
return jsx.replace(/<!--/g, "<!--").replace(/-->/g, "-->");
}
function extractJSX(root) {
let jsx = "";
if (root) {
[...root.getElementsByTagName("script")].forEach((node) => {
jsx += node.innerHTML;
});
}
return jsx
.replace(/\n/g, "")
.replace(/[\t ]+\</g, "<")
.replace(/\>[\t ]+\</g, "><")
.replace(/\>[\t ]+$/g, ">");
}
function restoreComments(root) {
if (root) {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) {
const node = walker.currentNode;
if (
node.nodeValue &&
node.nodeValue.includes("<!--") &&
node.nodeValue.includes("-->")
) {
const comments = node.nodeValue.trim().split(/<!--(.*?)-->/m);
const nextSibling = node.nextSibling;
comments.forEach((comment) => {
if (comment.trim().length > 0) {
const commentObject = document.createComment(comment);
if (node.parentNode) {
node.parentNode.insertBefore(commentObject, nextSibling);
}
node.nodeValue = null;
}
});
}
}
}
}