-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathFormattedText.jsx
More file actions
65 lines (59 loc) · 2.02 KB
/
FormattedText.jsx
File metadata and controls
65 lines (59 loc) · 2.02 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
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import remarkUnwrapImages from 'remark-unwrap-images';
import { remarkDefinitionList, defListHastHandlers } from 'remark-definition-list';
import CroppedImage from './CroppedImage';
import VideoComment from './VideoComment';
import FragmentComment from './FragmentComment';
function getId(text) {
if (!text) return null;
const regExp = /^.*(?:youtube\.com\/watch\?v=|youtu\.be\/)([^\s&]{11})/;
const match = text.match(regExp);
return match ? match[1] : null;
}
function embedVideo({ src }) {
const videoId = getId(src);
if (videoId) {
const embedLink = `https://www.youtube.com/embed/${videoId}`;
return <iframe width="80%" height="300" src={embedLink} style={{ border: 0 }} allowFullScreen title="YouTube video" />;
}
return null;
}
function FormattedText({ children, setHighlightedText, selectable, setSelectedText }) {
const handleMouseUp = () => {
if (selectable) {
let text = window.getSelection().toString();
setSelectedText(text);
setHighlightedText(text);
}
};
const renderLinkOrVideo = ({ children, href }) => {
const videoId = getId(href);
if (videoId) {
const embedLink = `https://www.youtube.com/embed/${videoId}`;
return <iframe width="80%" height="300" src={embedLink} style={{ border: 0 }} allowFullScreen title="YouTube video" />;
}
return <a href={href}>{children}</a>;
};
return (
<>
<ReactMarkdown
remarkPlugins={[remarkGfm, remarkDefinitionList, remarkUnwrapImages]}
components={{
img: (x) => embedVideo(x) || CroppedImage(x),
p: (x) =>
VideoComment(x) ||
FragmentComment({ ...x, setHighlightedText }) ||
<p onMouseUp={handleMouseUp}>{x.children}</p>,
a: renderLinkOrVideo
}}
remarkRehypeOptions={{
handlers: defListHastHandlers
}}
>
{children}
</ReactMarkdown>
</>
);
}
export default FormattedText;