-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.jsx
98 lines (85 loc) · 2.76 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
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
91
92
93
94
95
96
97
98
import { memo, useEffect, useRef, useState } from "react";
import classnames from "classnames";
import DOMPurify from "dompurify";
import CopyToClipboardButton from "neetomolecules/CopyToClipboardButton";
import { isNil } from "ramda";
import { createRoot } from "react-dom/client";
import { EDITOR_SIZES } from "src/common/constants";
import "src/styles/editor/editor-content.scss";
import { EDITOR_CONTENT_CLASS_NAME, SANITIZE_OPTIONS } from "./constants";
import ImagePreview from "./ImagePreview";
import {
highlightCode,
substituteVariables,
applyLineHighlighting,
} from "./utils";
const EditorContent = ({
content = "",
variables = [],
className,
size = EDITOR_SIZES.MEDIUM,
...otherProps
}) => {
const [imagePreviewDetails, setImagePreviewDetails] = useState(null);
const editorContentRef = useRef(null);
const htmlContent = substituteVariables(highlightCode(content), variables);
const sanitize = DOMPurify.sanitize;
const injectCopyButtonToCodeBlocks = () => {
const preTags = editorContentRef.current?.querySelectorAll(
`.${EDITOR_CONTENT_CLASS_NAME} pre`
);
preTags.forEach(preTag => {
const button = document.createElement("div");
button.className = "neeto-editor-codeblock-options";
const root = createRoot(button);
root.render(
<CopyToClipboardButton
size="small"
style="text"
value={preTag.textContent}
/>
);
preTag.appendChild(button);
});
};
const bindImageClickListener = () => {
const figureTags = editorContentRef.current?.querySelectorAll(
`.${EDITOR_CONTENT_CLASS_NAME} figure`
);
figureTags.forEach(figureTag => {
const image = figureTag.querySelector("img");
const link = figureTag.querySelector("a");
if (isNil(image) || isNil(link)) return;
figureTag.addEventListener("click", event => {
event.preventDefault();
const caption = figureTag.querySelector("figcaption").innerText;
setImagePreviewDetails({ src: image.src, caption });
});
});
};
useEffect(() => {
injectCopyButtonToCodeBlocks();
bindImageClickListener();
applyLineHighlighting(editorContentRef.current);
}, [content]);
return (
<>
<div
data-cy="neeto-editor-content"
ref={editorContentRef}
className={classnames(EDITOR_CONTENT_CLASS_NAME, {
[className]: className,
[`${EDITOR_CONTENT_CLASS_NAME}--size-${size}`]: true,
})}
dangerouslySetInnerHTML={{
__html: sanitize(htmlContent, SANITIZE_OPTIONS),
}}
{...otherProps}
/>
{imagePreviewDetails && (
<ImagePreview {...{ imagePreviewDetails, setImagePreviewDetails }} />
)}
</>
);
};
export default memo(EditorContent);