aboutsummaryrefslogtreecommitdiffstats
path: root/src/Editor.tsx
blob: d179b83d3ab1799a1aeb977daf401c422d3c1041 (plain)
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
import AceEditor from "react-ace"
import "ace-builds/src-noconflict/mode-java"
import "ace-builds/src-noconflict/theme-github"
import { useState } from "react"
import styles from "./Editor.module.css"
import { APIResult, submitSource } from "./api"

const Editor = () => {
  const [sourceText, setSourceText] = useState("")
  const [result, setResult] = useState<APIResult<string, Error>>({ type: "not_yet_requested" })
  const onChange = setSourceText

  const executeCode = async (text: string) => {
    const result = await submitSource(text)
    setResult(result)
  }

  const renderResults = () => {
    switch (result.type) {
      case "not_yet_requested":
      case "loading":
        return null
      case "failed":
        return (
          <div className={styles.error}>
            Failed to run code on the server. See console for details.
          </div>
        )
      case "success":
        return (
          <AceEditor
            mode=""
            theme="github"
            onChange={() => undefined}
            value={result.data}
            name="results"
            editorProps={{ $blockScrolling: true }}
            width="100%"
            fontSize={16}
            readOnly
          />
        )
    }
  }

  return (
    <>
      <AceEditor
        mode=""
        theme="github"
        onChange={onChange}
        value={sourceText}
        name="editor"
        editorProps={{ $blockScrolling: true }}
        width="100%"
        fontSize={16}
      />
      <button className={styles.runButton} onClick={() => executeCode(sourceText)}>
        ▶️ Run code on server
      </button>
      <div className={styles.results}>
        {renderResults()}
      </div>
    </>
  )
}

export default Editor