-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathGoPlay.tsx
83 lines (71 loc) · 2.05 KB
/
GoPlay.tsx
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
import { GoPlayProxy } from "@ggicci/goplay"
import CodeBlock from "@theme/CodeBlock"
import React from "react"
import styles from "./GoPlay.module.css"
const GOPLAY_PROXY_URL = "https://goplay.ggicci.me"
type ButtonProps = {
children: React.ReactNode
onClick: () => void
}
const Button = (props: ButtonProps) => {
const { children, onClick } = props
return (
<button className={styles.button} onClick={onClick}>
{children}
</button>
)
}
type GoPlayProps = {
children: React.ReactElement
}
const GoPlay = (props: GoPlayProps) => {
const { children } = props
const codeContainer = React.useRef<HTMLDivElement>(null)
const outputContainer = React.useRef<HTMLDivElement>(null)
const preEl = children
const codeEl = preEl && preEl.props.children
if (!codeEl) {
return (
<div
style={{
color: "#FFF",
fontWeight: "bold",
backgroundColor: "#d20a0a",
padding: "0.5rem 1rem ",
}}
>
Error: GoPlay: the wrapped data is not a codeblock.
</div>
)
}
if (!/\blanguage-go\b/.test(codeEl && codeEl.props.className)) {
return <div>GoPlay: only go code supported.</div>
}
function handleRun() {
if (outputContainer.current) {
const play = new GoPlayProxy(GOPLAY_PROXY_URL)
codeContainer.current.classList.remove(styles.hidden)
play.renderCompile(outputContainer.current, codeEl.props.children.trim())
}
}
async function handleShare() {
const play = new GoPlayProxy(GOPLAY_PROXY_URL)
const shareUrl = await play.share(codeEl.props.children.trim())
window.open(shareUrl, "_blank")
}
return (
<React.Fragment>
{children}
<div ref={codeContainer} className={styles.hidden}>
<CodeBlock language="text">
<div ref={outputContainer}></div>
</CodeBlock>
</div>
<div className={styles.toolbar}>
<Button onClick={handleRun}>Run</Button>
<Button onClick={handleShare}>{"Try it yourself ⇢"}</Button>
</div>
</React.Fragment>
)
}
export default GoPlay