Skip to content

Commit

Permalink
Nuke run on server. add format command (#764)
Browse files Browse the repository at this point in the history
* add format command

* remove server running

* pnpm lint
  • Loading branch information
tarasglek authored Dec 22, 2024
1 parent 02925f7 commit d0d2270
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 81 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"preview": "vite preview",
"prepare": "husky",
"lint": "eslint .",
"prettier": "prettier --write .",
"prettier": "pnpm run format",
"format": "prettier --write .",
"test": "vitest"
},
"dependencies": {
Expand Down
84 changes: 10 additions & 74 deletions src/components/CodeHeader.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
import { memo, useCallback, useMemo, type ReactNode, useState } from "react";
import { memo, type ReactNode, useCallback, useMemo, useState } from "react";
import {
Box,
Flex,
IconButton,
useClipboard,
useColorModeValue,
Text,
Box,
Menu,
MenuButton,
MenuItem,
MenuList,
Spinner,
Text,
useClipboard,
useColorModeValue,
} from "@chakra-ui/react";
import { TbCopy, TbDownload, TbRun, TbExternalLink } from "react-icons/tb";
import { TbCopy, TbDownload, TbExternalLink, TbRun } from "react-icons/tb";

import { download, formatAsCodeBlock } from "../lib/utils";
import { useAlert } from "../hooks/use-alert";
import { isRunnableInBrowser, isRunnableOnServer, runCode } from "../lib/run-code";
import { isRunnableInBrowser, runCode } from "../lib/run-code";

type PreHeaderProps = {
language: string;
Expand All @@ -36,12 +34,10 @@ function CodeHeader({
codeDownloadFilename,
}: PreHeaderProps) {
const { onCopy } = useClipboard(code);
const { info, error } = useAlert();
const { info } = useAlert();
const [isRunning, setIsRunning] = useState(false);
// Only show the "Run" button for JS code blocks, and only when we aren't already loading
const shouldShowRunButton =
(isRunnableInBrowser(language) || isRunnableOnServer(language)) && onPrompt;
const shouldShowRunMenuList = isRunnableOnServer(language) && onPrompt;
const shouldShowRunButton = isRunnableInBrowser(language) && onPrompt;

const handleCopy = useCallback(() => {
onCopy();
Expand All @@ -59,60 +55,6 @@ function CodeHeader({
});
}, [info, code, codeDownloadFilename]);

const handleRunRemote = useCallback(async () => {
if (!onPrompt) {
return;
}

// https://docs.val.town/api/eval/
const evalUrl = new URL("https://api.val.town/v1/eval");
const res = await fetch(evalUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
code: code.replaceAll("\n", " ").trim(),
args: [],
}),
});

if (!res.ok) {
error({ title: "Error Running Code", message: "Unable to run code remotely" });
return;
}

let result: string;
try {
// val.town returns an empty body when code doesn't return a value, which breaks res.json()
result = await res.json();
} catch {
error({
title: "Server unable to parse code",
message: "Try rewriting the code as an async function returning a value.",
});
return;
}

try {
if (typeof result === "string") {
// catch corner cases with strings
if (!result.length || result[0] === "/") {
result = formatAsCodeBlock(JSON.stringify(result), "js");
} else if (result.startsWith("<")) {
result = formatAsCodeBlock(result, "html");
} else {
// result is good to include inline, might have formatting, etc
}
}
} catch (error: any) {
result = formatAsCodeBlock(
error instanceof Error ? `${error.name}: ${error.message}\n${error.stack}` : `${error}`
);
}
if (result !== undefined) {
onPrompt(result);
}
}, [code, onPrompt, error]);

const handleRunBrowser = useCallback(async () => {
if (!onPrompt) {
return;
Expand Down Expand Up @@ -210,14 +152,8 @@ function CodeHeader({
_dark={{ color: "gray.300" }}
variant="ghost"
isDisabled={isLoading}
onClick={shouldShowRunMenuList ? undefined : handleRunBrowser}
onClick={handleRunBrowser}
/>
{shouldShowRunMenuList && (
<MenuList>
<MenuItem onClick={handleRunBrowser}>Run in Browser</MenuItem>
<MenuItem onClick={handleRunRemote}>Run on Server</MenuItem>
</MenuList>
)}
</Menu>
)}
<IconButton
Expand Down
7 changes: 1 addition & 6 deletions src/lib/run-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ const SupportedBrowserLanguages = [
...supportedPY,
...supportedRuby,
];
const supportedServerLanguages = [...supportedJS, ...supportedTS];

function isJavaScript(language: string) {
return supportedJS.includes(language);
Expand All @@ -41,10 +40,6 @@ export function isRunnableInBrowser(language: string) {
return SupportedBrowserLanguages.includes(language);
}

export function isRunnableOnServer(language: string) {
return supportedServerLanguages.includes(language);
}

async function captureConsole<T>(
callback: () => Promise<T>
): Promise<{ logs: string | undefined; ret: T }> {
Expand All @@ -57,7 +52,7 @@ async function captureConsole<T>(
};

// Prepare a string to store the captured messages
let capturedMessages: string = "";
let capturedMessages = "";

// Function to create an overridden console method
const createOverriddenMethod = (method: keyof Console) => {
Expand Down

0 comments on commit d0d2270

Please sign in to comment.