Skip to content

Commit

Permalink
Merge pull request #64 from georgestagg/runapp-fixes
Browse files Browse the repository at this point in the history
Remove default engine argument in `runApp()`, ensure correct engine is selected at runtime
  • Loading branch information
georgestagg authored Sep 13, 2023
2 parents 4f5dc4e + cf5455f commit 7d0c799
Show file tree
Hide file tree
Showing 16 changed files with 90 additions and 45 deletions.
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -234,9 +234,9 @@ serve-r:
# Build the _shinylive directory for deployment of both R and Python sites
_shinylive:
$(MAKE) buildjs-prod
cp -Lr $(SITE_DIR) $(SHINYLIVE_DIR)/py
cp -Lr $(SITE_DIR)/. $(SHINYLIVE_DIR)/py
$(MAKE) buildjs-prod-r
cp -Lr $(SITE_DIR) $(SHINYLIVE_DIR)/r
cp -Lr $(SITE_DIR)/. $(SHINYLIVE_DIR)/r

# Build htmltools, shiny, and shinywidgets. This target must be run manually after
# updating the package submodules; it will not run automatically with `make all`
Expand Down
2 changes: 1 addition & 1 deletion export_template/edit/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
const appFiles = await response.json();

const appRoot = document.getElementById("root");
runApp(appRoot, "editor-terminal-viewer", {startFiles: appFiles});
runApp(appRoot, "editor-terminal-viewer", {startFiles: appFiles}, "{{APP_ENGINE}}");
</script>
<link rel="stylesheet" href="../{{REL_PATH}}shinylive/style-resets.css" />
<link rel="stylesheet" href="../{{REL_PATH}}shinylive/shinylive.css" />
Expand Down
2 changes: 1 addition & 1 deletion export_template/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
const appFiles = await response.json();

const appRoot = document.getElementById("root");
runApp(appRoot, "viewer", {startFiles: appFiles});
runApp(appRoot, "viewer", {startFiles: appFiles}, "{{APP_ENGINE}}");
</script>
<link rel="stylesheet" href="./{{REL_PATH}}shinylive/style-resets.css" />
<link rel="stylesheet" href="./{{REL_PATH}}shinylive/shinylive.css" />
Expand Down
6 changes: 2 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
"tsx": "^3.12.7",
"typescript": "^5.1.3",
"vscode-languageserver-protocol": "^3.17.3",
"webr": "^0.2.1",
"xterm": "^5.2.1",
"xterm-addon-fit": "^0.7.0",
"xterm-readline": "^1.1.1"
Expand Down Expand Up @@ -133,8 +134,5 @@
"react-hooks/exhaustive-deps": "warn"
}
},
"packageManager": "[email protected]",
"dependencies": {
"webr": "0.2.1"
}
"packageManager": "[email protected]"
}
28 changes: 25 additions & 3 deletions scripts/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { spawn } from "child_process";
import esbuild from "esbuild";
import * as fs from "fs";
import http from "http";
import path from "path";
import process from "process";
import packageJson from "../package.json";
import type { AppEngine } from "../src/Components/App";
import buildExamples from "./build_examples_json";
import type { AppEngine } from '../src/Components/App';

const EXAMPLES_SOURCE_DIR = "./examples";
const BUILD_DIR = "./build";
Expand Down Expand Up @@ -78,6 +79,25 @@ const metafilePlugin = {
},
};

function readdirSyncRecursive(dir: string, root: string = dir): string[] {
return fs.readdirSync(dir).reduce((files: string[], file: string) => {
const name = path.join(dir, file);
if (fs.statSync(name).isDirectory()) {
return [...files, ...readdirSyncRecursive(name, root)];
}
return [...files, path.relative(root, name)];
}, []);
}

function buildSiteHtml(appEngine: AppEngine) {
console.log(`[${new Date().toISOString()}] Copying HTML templates...`);
readdirSyncRecursive("site_template").forEach((file) => {
const tmpl = fs.readFileSync(`site_template/${file}`, "utf8");
const html = tmpl.replace("{{APP_ENGINE}}", appEngine);
fs.writeFileSync(`${SITE_DIR}/${file}`, html);
});
}

const buildmap = {
app: esbuild.context({
bundle: true,
Expand Down Expand Up @@ -111,7 +131,6 @@ const buildmap = {
banner: banner,
metafile: metafile,
define: {
"process.env.APP_ENGINE": `"${appEngine}"`,
"process.env.NODE_ENV": reactProductionMode
? '"production"'
: '"development"',
Expand Down Expand Up @@ -212,6 +231,9 @@ const buildmap = {
}),
};

// Build shinylive website HTML in /site for R or Python as requested
buildSiteHtml(appEngine);

Object.values(buildmap).forEach((build) =>
build
.then((context) => {
Expand All @@ -236,7 +258,7 @@ if (serve) {
http.request(
{ hostname: "0.0.0.0", port: 3001, path: url, method, headers },
(proxyRes) => {
if (appEngine === 'r') {
if (appEngine === "r") {
proxyRes.headers = {
...proxyRes.headers,
"cross-origin-opener-policy": "same-origin",
Expand Down
1 change: 1 addition & 0 deletions site/app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
index.html
1 change: 1 addition & 0 deletions site/editor/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
index.html
1 change: 1 addition & 0 deletions site/examples/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
index.html
2 changes: 1 addition & 1 deletion site/app/index.html → site_template/app/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
allowCodeUrl: true,
allowGistUrl: true,
allowExampleUrl: true,
});
}, "{{APP_ENGINE}}");
</script>
<link rel="stylesheet" href="../shinylive/style-resets.css" />
<link rel="stylesheet" href="../shinylive/shinylive.css" />
Expand Down
2 changes: 1 addition & 1 deletion site/editor/index.html → site_template/editor/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
};

const appRoot = document.getElementById("root");
runApp(appRoot, "editor-terminal-viewer", runAppOpts);
runApp(appRoot, "editor-terminal-viewer", runAppOpts, "{{APP_ENGINE}}");
</script>
<link rel="stylesheet" href="../shinylive/style-resets.css" />
<link rel="stylesheet" href="../shinylive/shinylive.css" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
allowCodeUrl: true,
allowGistUrl: true,
allowExampleUrl: true,
});
}, "{{APP_ENGINE}}");
</script>
<link rel="stylesheet" href="../shinylive/style-resets.css" />
<link rel="stylesheet" href="../shinylive/shinylive.css" />
Expand Down
55 changes: 32 additions & 23 deletions src/Components/App.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
import LZString from "lz-string";
import * as React from "react";
import { createRoot } from "react-dom/client";
import {
findExampleByTitle,
getExampleCategories,
sanitizeTitleForUrl,
} from "../examples";
import {
PyodideProxyHandle,
initPyodide,
initShiny,
PyodideProxyHandle,
usePyodide,
} from "../hooks/usePyodide";
import {
initWebR,
WebRProxyHandle,
initRShiny,
initWebR,
useWebR,
WebRProxyHandle
} from "../hooks/useWebR";
import { ProxyType } from "../pyodide-proxy";
import "./App.css";
Expand All @@ -26,9 +29,6 @@ import { Viewer, ViewerMethods } from "./Viewer";
import { FCorFCJSONtoFC, FileContent, FileContentJson } from "./filecontent";
import { fetchGist, gistApiResponseToFileContents } from "./gist";
import { editorUrlPrefix, fileContentsToUrlString } from "./share";
import LZString from "lz-string";
import * as React from "react";
import { createRoot } from "react-dom/client";

// Load Editor component dynamically and lazily because it's large and not
// needed for all configurations.
Expand Down Expand Up @@ -97,7 +97,6 @@ type AppOptions = {
showHeaderBar?: boolean;
};


export type ProxyHandle = PyodideProxyHandle | WebRProxyHandle;
let pyodideProxyHandlePromise: Promise<PyodideProxyHandle> | null = null;
let webRProxyHandlePromise: Promise<WebRProxyHandle> | null = null;
Expand Down Expand Up @@ -172,7 +171,7 @@ export function App({
appMode = "examples-editor-terminal-viewer",
startFiles = [],
appOptions = {},
appEngine = process.env.APP_ENGINE as AppEngine,
appEngine,
}: {
appMode: AppMode;
startFiles: FileContent[];
Expand Down Expand Up @@ -220,10 +219,10 @@ export function App({
useWasmEngine = () => usePyodide({ pyodideProxyHandlePromise: promise });
break;
}
case "r":{
const promise = webRProxyHandlePromise = ensureWebRProxyHandlePromise({
case "r": {
const promise = (webRProxyHandlePromise = ensureWebRProxyHandlePromise({
shiny: loadShiny,
});
}));
useWasmEngine = () => useWebR({ webRProxyHandlePromise: promise });
break;
}
Expand Down Expand Up @@ -310,7 +309,9 @@ export function App({
setHeaderBarCallbacks({
openEditorWindowFromViewer: () => {
window.open(
editorUrlPrefix + "#code=" + fileContentsToUrlString(startFiles),
editorUrlPrefix(appEngine) +
"#code=" +
fileContentsToUrlString(startFiles),
"_blank"
);
},
Expand Down Expand Up @@ -348,8 +349,11 @@ export function App({
terminalMethods={terminalMethods}
viewerMethods={viewerMethods}
utilityMethods={utilityMethods}
runOnLoad={currentFiles.some((file) =>
file.name === "app.py" || file.name === "app.R" || file.name === "server.R"
runOnLoad={currentFiles.some(
(file) =>
file.name === "app.py" ||
file.name === "app.R" ||
file.name === "server.R"
)}
appEngine={appEngine}
/>
Expand Down Expand Up @@ -391,8 +395,11 @@ export function App({
terminalMethods={terminalMethods}
viewerMethods={viewerMethods}
utilityMethods={utilityMethods}
runOnLoad={currentFiles.some((file) =>
file.name === "app.py" || file.name === "app.R" || file.name === "server.R"
runOnLoad={currentFiles.some(
(file) =>
file.name === "app.py" ||
file.name === "app.R" ||
file.name === "server.R"
)}
appEngine={appEngine}
/>
Expand Down Expand Up @@ -491,10 +498,7 @@ export function App({
appEngine={appEngine}
/>
</React.Suspense>
<Viewer
proxyHandle={proxyHandle}
setViewerMethods={setViewerMethods}
/>
<Viewer proxyHandle={proxyHandle} setViewerMethods={setViewerMethods} />
</ResizableGrid>
);
} else if (appMode === "viewer") {
Expand Down Expand Up @@ -542,7 +546,7 @@ export function runApp(
allowGistUrl?: boolean;
allowExampleUrl?: boolean;
} = {},
appEngine: AppEngine = process.env.APP_ENGINE as AppEngine,
appEngine: AppEngine
) {
const optsDefaults = {
allowCodeUrl: false,
Expand Down Expand Up @@ -595,7 +599,7 @@ export function runApp(
if (value === "") exampleName = key;
}

const exampleCategories = (await getExampleCategories(appEngine));
const exampleCategories = await getExampleCategories(appEngine);
let pos = findExampleByTitle(exampleName, exampleCategories);
if (pos) {
opts.selectedExample = exampleName;
Expand Down Expand Up @@ -640,7 +644,12 @@ export function runApp(
const root = createRoot(domTarget);
root.render(
<React.StrictMode>
<App appMode={mode} startFiles={startFiles} appOptions={appOpts} appEngine={appEngine} />
<App
appMode={mode}
startFiles={startFiles}
appOptions={appOpts}
appEngine={appEngine}
/>
</React.StrictMode>
);
})();
Expand Down
3 changes: 2 additions & 1 deletion src/Components/Editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ export default function Editor({
syncActiveFileState();
const fileContents = editorFilesToFileContents(files);
window.open(
editorUrlPrefix + "#code=" + fileContentsToUrlString(fileContents),
editorUrlPrefix(appEngine) + "#code=" + fileContentsToUrlString(fileContents),
"_blank"
);
}, [files, syncActiveFileState]);
Expand All @@ -445,6 +445,7 @@ export default function Editor({
<ShareModal
fileContents={editorFilesToFileContents(files)}
setShareModalVisible={setShareModalVisible}
appEngine={appEngine}
></ShareModal>
);
}
Expand Down
7 changes: 5 additions & 2 deletions src/Components/ShareModal.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useOnEscOrClickOutside } from "../hooks/useOnEscOrClickOutside";
import { AppEngine } from "./App";
import "./ShareModal.css";
import { FileContent } from "./filecontent";
import {
Expand All @@ -15,20 +16,22 @@ import * as React from "react";
export function ShareModal({
fileContents = [],
setShareModalVisible,
appEngine,
}: {
fileContents: FileContent[];
setShareModalVisible: React.Dispatch<React.SetStateAction<boolean>>;
appEngine: AppEngine;
}) {
const showModalRef = React.useRef<HTMLDivElement>(null);

const encodedCode = fileContentsToUrlString(fileContents);

const [hideHeaderChecked, setHideHeaderChecked] = React.useState(false);

const editorUrl = editorUrlPrefix + "#code=" + encodedCode;
const editorUrl = editorUrlPrefix(appEngine) + "#code=" + encodedCode;

const appUrl =
appUrlPrefix +
appUrlPrefix(appEngine) +
"#" +
(hideHeaderChecked ? "h=0&" : "") +
"code=" +
Expand Down
15 changes: 12 additions & 3 deletions src/Components/share.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import { AppEngine } from "./App";
import { FCtoFCJSON, FileContent } from "./filecontent";
import LZString from "lz-string";

const shortEngine = process.env.APP_ENGINE === "python" ? "py" : "r";
export const editorUrlPrefix = `https://shinylive.io/${shortEngine}/editor/`;
export const appUrlPrefix = `https://shinylive.io/${shortEngine}/app/`;
const shortEngine = {
python: "py",
r: "r",
}
export function editorUrlPrefix(engine: AppEngine) {
return `https://shinylive.io/${shortEngine[engine]}/editor/`;
}

export function appUrlPrefix(engine: AppEngine) {
return `https://shinylive.io/${shortEngine[engine]}/app/`;
}

/**
* Given a FileContent[] object, return a string that is a LZ-compressed JSON
Expand Down
4 changes: 2 additions & 2 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6552,7 +6552,7 @@ __metadata:
tsx: ^3.12.7
typescript: ^5.1.3
vscode-languageserver-protocol: ^3.17.3
webr: 0.2.1
webr: ^0.2.1
xterm: ^5.2.1
xterm-addon-fit: ^0.7.0
xterm-readline: ^1.1.1
Expand Down Expand Up @@ -7241,7 +7241,7 @@ __metadata:
languageName: node
linkType: hard

"webr@npm:0.2.1":
"webr@npm:^0.2.1":
version: 0.2.1
resolution: "webr@npm:0.2.1"
dependencies:
Expand Down

0 comments on commit 7d0c799

Please sign in to comment.