-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.jsx
58 lines (49 loc) · 1.56 KB
/
index.jsx
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
import React from "react";
const Editable = ({
children,
editable = true,
rootSelector = "#root",
linksRoot = "/",
onChange = () => {}
}) => {
const replaceLocalLinks = html_string => {
const html = new DOMParser().parseFromString(html_string, 'text/html');
const domain = window.location.protocol + '//' + window.location.host;
const links = html.querySelectorAll(`a[href^="${linksRoot}"]`);
links.forEach(link => {
link.href = link.href.replace(/^\.\//, domain + '/');
});
const images = html.querySelectorAll(`img[src^="${linksRoot}"]`);
images.forEach(image => {
image.src = image.src.replace(/^\.\//, domain + '/');
});
const headLinks = html.querySelectorAll(`link[href^="${linksRoot}"]`);
headLinks.forEach(link => {
link.href = link.href.replace(/^\.\//, domain + '/');
});
const scripts = html.querySelectorAll(`script[src^="${linksRoot}"]`);
scripts.forEach(script => {
script.src = script.src.replace(/^\.\//, domain + '/');
});
return html.documentElement.outerHTML;
};
const convertRawHtmlToStyledHtml = rawHtml => {
const pageContent = document.querySelector("html").cloneNode(true);
pageContent.querySelector(rootSelector).innerHTML = rawHtml;
const styledHtml = replaceLocalLinks(pageContent.innerHTML);
return styledHtml;
};
return (
<div
contentEditable={editable}
onInput={event => {
const rawHtml = event.target.innerHTML;
const styledHtml = convertRawHtmlToStyledHtml(rawHtml);
onChange(rawHtml, styledHtml);
}}
>
{children}
</div>
);
};
export default Editable;