SPB Git

Repository Public

RunCodeView.tsx 7.3 KB 117 lines tsx

1"use client";2/**3 * file: src/components/editor/nodes/RunCodeView.tsx4 * description: node view of the `runCode` block (SPEC §2) — a code cell whose JavaScript runs ONLY on an explicit action (the Run5 *   button or ⌘/Ctrl+Enter in the code field), never on load and never on edit, inside the throw-away sandbox of6 *   src/lib/client/sandbox.ts (opaque-origin iframe, no network, killed on timeout or Stop). The last result is stored in7 *   `output = {text, error, ms, at}` so every client can show it. Other languages are kept and displayed but cannot run here.8 * author: Simon-Pierre Boucher — contact@spboucher.ai9 */10import * as React from "react";11import { Eraser, Play, ShieldCheck, Square, SquareTerminal } from "lucide-react";12import type { RunCodeAttrs, RunOutput } from "@/lib/editor/next-node-defs";13import { runSandboxed, SANDBOX_DEFAULT_TIMEOUT_MS } from "@/lib/client/sandbox";14import { NodeButton, NodeFrame, useDebounced, type LeafViewProps } from "./frame";1516const LANGUAGES: { value: string; label: string }[] = [17  { value: "javascript", label: "JavaScript" }, { value: "typescript", label: "TypeScript" }, { value: "python", label: "Python" }, { value: "sql", label: "SQL" }, { value: "shell", label: "Shell" },18];19const isRunnable = (language: string) => language === "javascript" || language === "js";20const validOutput = (o: unknown): o is RunOutput => !!o && typeof o === "object" && typeof (o as RunOutput).text === "string";21function outputMeta(o: RunOutput): string {22  const parts: string[] = [];23  if (Number.isFinite(o.ms)) parts.push(o.ms >= 1000 ? `${(o.ms / 1000).toFixed(2)} s` : `${Math.round(o.ms)} ms`);24  const at = typeof o.at === "string" ? new Date(o.at) : null;25  if (at && !Number.isNaN(at.getTime())) parts.push(at.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" }));26  return parts.join(" · ");27}2829export function RunCodeView({ attrs, update, editable, selected }: LeafViewProps<RunCodeAttrs>) {30  const language = typeof attrs.language === "string" && attrs.language ? attrs.language : "javascript";31  const stored = typeof attrs.code === "string" ? attrs.code : "";32  const output = validOutput(attrs.output) ? attrs.output : null;33  const runnable = isRunnable(language);3435  // The textarea owns a draft; the attr is written a moment after typing stops. An external change (sync, undo) replaces the draft.36  const [draft, setDraft] = React.useState(stored);37  const written = React.useRef(stored);38  React.useEffect(() => { if (stored !== written.current) { written.current = stored; setDraft(stored); } }, [stored]);39  const save = useDebounced((code: string) => { if (code !== written.current) { written.current = code; update({ code }); } }, 400);4041  const [running, setRunning] = React.useState(false);42  const abort = React.useRef<AbortController | null>(null);43  const alive = React.useRef(true);44  React.useEffect(() => { alive.current = true; return () => { alive.current = false; abort.current?.abort(); }; }, []);45  const hintId = React.useId();4647  /** Explicit user action only. */48  const run = React.useCallback(async () => {49    if (!editable || !runnable || abort.current) return;50    save.flush();51    const controller = new AbortController(); abort.current = controller; setRunning(true);52    try {53      const r = await runSandboxed(draft, { timeoutMs: SANDBOX_DEFAULT_TIMEOUT_MS, signal: controller.signal });54      if (alive.current) update({ output: { text: r.text, error: r.error, ms: r.ms, at: new Date().toISOString() } });55    } finally {56      if (abort.current === controller) abort.current = null;57      if (alive.current) setRunning(false);58    }59  }, [draft, editable, runnable, save, update]);60  const stop = () => abort.current?.abort();6162  const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {63    if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); void run(); return; }64    if (e.key === "Tab" && !e.shiftKey && !e.altKey && !e.metaKey && !e.ctrlKey) {65      e.preventDefault();66      const el = e.currentTarget; const start = el.selectionStart, end = el.selectionEnd;67      const next = `${draft.slice(0, start)}  ${draft.slice(end)}`;68      setDraft(next); save(next);69      requestAnimationFrame(() => { if (document.activeElement === el) el.setSelectionRange(start + 2, start + 2); });70    } else if (e.key === "Escape") e.currentTarget.blur(); // way out for keyboard users, since Tab indents71  };72  const known = LANGUAGES.some((l) => l.value === language);73  const rows = Math.min(24, Math.max(4, draft.split("\n").length + 1));7475  return (76    <NodeFrame kind="runCode" label="Runnable code" icon={<SquareTerminal />} selected={selected}77      title={<span className="rc-hint" id={hintId}><ShieldCheck aria-hidden />Runs in an isolated sandbox without network access</span>}78      actions={editable ? (running79        ? <NodeButton label="Stop" tone="danger" text onClick={stop}><Square /></NodeButton>80        : <NodeButton label="Run code" tone="accent" text disabled={!runnable} onClick={() => void run()}><Play /></NodeButton>) : undefined}>81      <div className="rc" data-running={running ? "true" : undefined}>82        {editable ? (83          <>84            <div className="nb-toolbar">85              <label className="rc-lang"><span className="nb-meta">Language</span>86                <select className="nb-field" aria-label="Language" value={language} onChange={(e) => update({ language: e.target.value })}>87                  {LANGUAGES.map((l) => <option key={l.value} value={l.value}>{l.label}</option>)}88                  {!known && <option value={language}>{language}</option>}89                </select>90              </label>91              <span className="nb-meta rc-note" role="note">{runnable ? "Runs only when you press Run (⌘/Ctrl + Enter)" : "Only JavaScript runs in the browser"}</span>92            </div>93            <textarea className="nb-code rc-code" aria-label="Code" aria-describedby={hintId} value={draft} rows={rows} spellCheck={false} autoCapitalize="off" autoCorrect="off" autoComplete="off" data-gramm="false"94              placeholder={runnable ? "console.log(\"Hello\")" : ""} onChange={(e) => { setDraft(e.target.value); save(e.target.value); }} onBlur={() => save.flush()} onKeyDown={onKeyDown} />95          </>96        ) : (97          <>98            <div className="nb-toolbar"><span className="nb-meta">{LANGUAGES.find((l) => l.value === language)?.label ?? language}</span></div>99            <pre className="nb-code rc-code rc-code-ro" tabIndex={0} aria-label="Code">{stored}</pre>100          </>101        )}102        {running && <div className="rc-status nb-meta" role="status">Running… (stops by itself after {SANDBOX_DEFAULT_TIMEOUT_MS / 1000} s)</div>}103        {output && (104          <div className="rc-out" data-error={output.error ? "true" : undefined}>105            <div className="rc-out-head">106              <span className="rc-out-label">{output.error ? "Error" : "Output"}</span>107              <span className="nb-meta">{outputMeta(output)}</span>108              {editable && !running && <NodeButton label="Clear output" text className="rc-clear" onClick={() => update({ output: null })}><Eraser /></NodeButton>}109            </div>110            <pre className="rc-out-text" data-testid="run-output" tabIndex={0} aria-label={output.error ? "Error output" : "Output"}>{output.text === "" ? "(no output)" : output.text}</pre>111          </div>112        )}113      </div>114    </NodeFrame>115  );116}117
Files main
Menu

Theme