# Canvas run

A frame's own scripts, run once in a sandboxed document with no network, for the one person who pressed Run in Act.

Live variants: https://design.arcadia.is/components/canvas-run

```tsx
import { canvasRunPolicy, canvasRunHeaders, fromRun, toRun } from "@arcadia/ui";
```

```tsx
import { useState, useRef, useEffect } from "react";

function Run({ initial = "stopped" }: { initial?: RunState } = {}) {
  const [state, setState] = useState<RunState>(initial === "running" ? "starting" : initial);
  const [inst, setInst] = useState("");
  const frame = useRef<HTMLIFrameElement | null>(null);
  const run = useRef<HTMLButtonElement | null>(null);

  useEffect(() => {
    if (!inst) return;
    const dark = (frame.current?.closest<HTMLElement>("[data-theme]")?.dataset.theme ?? document.documentElement.dataset.theme) !== "light";
    let port: MessagePort | null = null;
    let last = performance.now();
    const end = (why: RunState) => { port?.close(); port = null; setInst(""); setState(why); run.current?.focus(); };
    const watch = setInterval(() => { if (port && performance.now() - last > SILENT_MS) end("silent"); }, 250);
    const receive = (event: MessageEvent) => {
      const view = frame.current?.contentWindow;
      if (port || !view || event.source !== view || event.origin !== "null" || fromRun(event.data, inst)?.t !== "ready") return;
      const channel = new MessageChannel();
      port = channel.port1;
      port.onmessage = (message) => {
        const said = fromRun(message.data, inst);
        if (said?.t === "alive") last = performance.now();
        if (said?.t === "escape") end("escaped");
      };
      view.postMessage({ t: "port", inst }, "*", [channel.port2]);
      port.postMessage({ t: "run", inst, source: dark ? sample.replace('data-theme="light"', 'data-theme="dark"') : sample, files: [] });
      last = performance.now();
      setState("running");
      if (document.activeElement === run.current) frame.current?.focus();
    };
    window.addEventListener("message", receive);
    return () => { window.removeEventListener("message", receive); clearInterval(watch); port?.close(); };
  }, [inst])
```

## Accessibility

Run is a button, and the page's state is said in a status line. A running page takes the focus; Escape ends the run and gives the focus back to Run.
