-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
90 lines (84 loc) · 2.46 KB
/
index.js
File metadata and controls
90 lines (84 loc) · 2.46 KB
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
import React from "react";
import { createRoot } from "react-dom/client";
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)) {
document.addEventListener("readystatechange", (e) => {
if (e.target?.["readyState"] === "complete") {
const restore = () => {
restoreComments(root);
if (typeof parent["mgnlRefresh"] === "function") {
parent["mgnlRefresh"]();
}
if (typeof callback === "function") {
callback();
}
};
if (typeof requestIdleCallback === "function") {
requestIdleCallback(restore);
} else {
setTimeout(restore, 250);
}
}
});
createRoot(root).render(parse(components, root));
}
}
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;
}
});
}
}
}
}