Skip to content

Commit

Permalink
Move R code chunks to .R files
Browse files Browse the repository at this point in the history
  • Loading branch information
WardBrian committed Jul 30, 2024
1 parent f740623 commit 2779b7e
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 13 deletions.
7 changes: 7 additions & 0 deletions gui/src/app/Scripting/webR/data_postamble.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# 'data' is a built in function, so we need to make sure the user actually set it
if (typeof(data) != "list") {
stop("[stan-playground] data must be a list")
}
.SP_DATA <- jsonlite::toJSON(data, pretty = TRUE, auto_unbox = TRUE)
# invisible prevents printing of the output
invisible(.SP_DATA)
18 changes: 5 additions & 13 deletions gui/src/app/Scripting/webR/useWebR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import { WebR } from "webr";
import { InterpreterStatus } from "@SpScripting/InterpreterTypes";
import { writeConsoleOutToDiv } from "@SpScripting/OutputDivUtils";

import webRPreamble from "./webR_preamble.R?raw";
import dataPostamble from "./data_postamble.R?raw";

const captureOutputOptions = {
withAutoprint: true,
captureStreams: false,
Expand Down Expand Up @@ -84,23 +87,12 @@ const useWebR = ({ imagesRef, consoleRef, onStatus, onData }: useWebRProps) => {
const options = { ...captureOutputOptions, env };

// setup
await webR.evalRVoid(
`webr::shim_install()
webr::canvas()`,
options,
);
await webR.evalRVoid(webRPreamble, options);
await webR.evalRVoid(code, options);

if (onData) {
const result = JSON.parse(
await webR.evalRString(
`if (typeof(data) != "list") {
stop("[stan-playground] data must be a list")
}
.SP_DATA <- jsonlite::toJSON(data, pretty = TRUE, auto_unbox = TRUE)
invisible(.SP_DATA)`,
options,
),
await webR.evalRString(dataPostamble, options),
);
onData(result);
}
Expand Down
4 changes: 4 additions & 0 deletions gui/src/app/Scripting/webR/webR_preamble.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# set up install.packages to use webR's repository
webr::shim_install()
# enable the canvas backend for plotting
webr::canvas()

0 comments on commit 2779b7e

Please sign in to comment.