Skip to content

Commit

Permalink
Add REPL component
Browse files Browse the repository at this point in the history
  • Loading branch information
thiagooak committed Sep 2, 2024
1 parent be98ea6 commit 80d57e5
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 3 deletions.
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,16 @@ Accepts the same props as [react-syntax-highlighter](https://github.com/react-sy
plus:
* `language` defaults to "clojure"
* `allowEval` a boolean that defaults to true if the language is "clojure".
* `allowEval` a boolean that defaults to true if the language is "clojure".
---
```js
"use client"
import { Repl } from "react-interactive-cljs"

export function Page() {
return (<Repl defaultInput={`"Hello, World!"`} />)
)

```
40 changes: 39 additions & 1 deletion index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function CodeBlock({ children, language = "clojure", allowEval = true, st
function handleRun() {
setOutput("Running...")
let [evalOutput, printOutput] = evaluate(children);
setOutput(printOutput.concat(evalOutput).join("\n"))
setOutput(printOutput.concat(evalOutput ?? 'nil').join("\n"))
}

return (
Expand All @@ -38,4 +38,42 @@ export function CodeBlock({ children, language = "clojure", allowEval = true, st
</>)}
</>
);
}

export function Repl({
defaultInput = `(println "Hello World!")`,
outputClass = "px-2 py-1 h-3/4 max-h-3/4",
formClass = "flex-row sm:flex px-2 sm:h-1/4",
textareaClass = "w-full h-full p-1 bg-gray-800",
submitClass = "rounded bg-blue-600 py-1 px-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600"
}) {
const [input, setInput] = React.useState(defaultInput);
const [output, setOutput] = React.useState("")

function handleChange(e) {
setInput(e.target.value);
}

function handleSubmit(e) {
e.preventDefault();
let [evalOutput, printOutput] = evaluate(input);
setOutput(
output.concat(
input,
"\n",
printOutput.concat(evalOutput ?? 'nil').join("\n")
).concat("\n")
)
}

return (<>
<div className={outputClass}>
{output.split("\n").map((o, i) => (<div key={i}>{o}</div>))}
</div>
<form onSubmit={(e) => handleSubmit(e)} className={formClass}>
<textarea className={textareaClass} spellCheck={false} onChange={(e) => handleChange(e)}>{input}</textarea>
<input type="submit" className={submitClass} value="Enter" />
</form>
</>
);
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-interactive-cljs",
"version": "0.1.0",
"version": "0.2.0",
"description": "Interactive cljs code blocks",
"main": "index.js",
"scripts": {
Expand Down

0 comments on commit 80d57e5

Please sign in to comment.