# Canvas frame

One stored page of markup, drawn in a sandboxed document with no network and no script of its own, behind the wall a plane speaks to.

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

```tsx
import { CanvasFrame, useCanvasPins } from "@arcadia/ui";
```

## When to use

- A page a team reads, comments on and changes together in the canvas
- Markup a person wrote: HTML, CSS or SVG, drawn as a page and not as a picture

## When not to use

- A page on Arcadia's own origin, where its script runs. A frame is for markup that nobody reviewed as code
- A still of a page, which is `Shot`

## In context

A frame is one stored source, drawn inside a sandboxed document with no network and no script of its own. The document says it is ready over its window; the part checks that window, the null origin and the instance tag, then hands the document one port. Every message after that goes over the port, so a page the frame navigated to cannot speak and is sent nothing.

A page of markup behind the wall. Press it to scroll inside, Escape to leave.

```tsx
import { CanvasFrame } from "@arcadia/ui";

<CanvasFrame
  src={FRAME}
  kind="html"
  source={SAMPLE}
  title="Ship notes"
  elementSeq={4}
  width={256}
  height={212}
  measure={["e1", "e4"]}
/>
```

## Frame header

The title and source sit above the frame.

Rename, resize or zoom to the frame

```tsx
import { useState } from "react";
import { Button, CanvasFrame, Slider } from "@arcadia/ui";

function Header() {
  const [title, setTitle] = useState("Ship notes");
  const [width, setWidth] = useState(200);
  const [selected, setSelected] = useState(true);
  const [resizing, setResizing] = useState(false);
  const [zoomed, setZoomed] = useState(false);
  return (
    <div {...stylex.props(page.frameDemo)}>
      <div role="group" aria-label="Frame controls" {...stylex.props(page.headerTools)}>
        <Button size="sm" pressed={selected} onClick={() => setSelected(!selected)}>Selected</Button>
        <Button size="sm" disabled={!zoomed} onClick={() => setZoomed(false)}>Reset zoom</Button>
        <Slider label="Frame width" min={200} max={248} value={width} onValueChange={setWidth} onActiveChange={setResizing} rootStyle={page.frameWidth} />
      </div>
      <div {...stylex.props(page.headerRoom)}>
        <div {...stylex.props(zoomed && page.zoomed)}>
          <CanvasFrame
            src={FRAME}
            kind="html"
            source={SAMPLE}
            title={title}
            sourceLabel="Design review"
            elementSeq={4}
            width={width}
            height={160}
            selected={selected}
            resizing={resizing}
            onRename={setTitle}
            onFocusFrame={() => setZoomed(true)}
          />
        </div>
      </div>
    </div>
  );
}
```

## The wall

The wall is the framed document and the checks the part keeps on both sides of it.

- `sandbox` is `allow-scripts` and nothing else; with `allow-same-origin` the document would have a real origin
- The document runs only in an opaque origin: a copy that is framed without `sandbox` does nothing at all
- `allow` is empty, so the frame has no feature of the device
- Markup arrives by `draw` and no other way: the part never reads the document and never sets `srcdoc`
- The policy stops every request: `default-src 'none'`, with `img-src data: blob:` the only source that reaches a resource, and no frame, form, worker or connection source
- The parse removes `script` and the elements it names, and every attribute that begins with `on`, so a script in the source never reaches the document; it also leaves out `base`, `link`, `meta`, `iframe`, `frame`, `frameset`, `object`, `embed`, `portal`, `fencedframe`, `area` and `map`, and the attributes `srcdoc`, `ping`, `autofocus`, `usemap` and `autoplay`
- Every auxclick, contextmenu, submit, dragstart and drop is cancelled on purpose, and so is every click and double click while a tool picks. While none picks, a click and a double click do what HTML does alone (a label ticks its box, a summary opens its details, a button shows its popover) unless they land on a link, an area or a file input, so nothing in a frame navigates, submits or asks for a file
- A link keeps its look and its place in the Tab order, and its address becomes a fragment of the frame's own document: a browser that opens a connection to a pressed link's host, before any listener can cancel the press, finds no other host
- The element is inert until the person goes into it or holds a tool
- A frame that navigated, stayed silent, sent more than 60 counted messages in a second or more than 240 box or scroll reports in a second is taken out and reported by `onGone`; hover and wheel reports are coalesced to one an animation frame and are not counted, and a hover that answers no open ask is counted

## What crosses

A frame sends numbers, ids and text. An id is a `data-canvas-id` of the frame's own markup, below the part's `elementSeq`; a number is finite and within 100,000; a text is a string within its bound. Nothing a frame sends is markup, an address, a selector or a style of the page, and nothing follows from it but a report to the part's callbacks.

- `hover` and `pick` are two to nine numbers and an id: a place, a size, the document's scroll offsets, the modifiers and 1 or 2 for a double press
- `select` is an id, two whole numbers as offsets in that element's own text, and the selected words as a string of 1,000 characters at most, cut at the bound
- The words of a selection reach `onSelect` as a string and nothing else is done with them: a product shows them as text and stores them as text
- `selectLimit` names the budget a selection passed and carries no words; it reaches `onSelect` as `{ refused }`, never as an empty quote
- `step` answers with a `hover`, `survey` with 300 entries of an id and 17 numbers, `probe` with a colour for each of 64 points
- `key` is one of Escape, Enter, Tab, the four arrows, Delete, Backspace or one letter or digit, with the modifiers, on a real key while the focus is in the frame and in no field of the capture

## Files

A capture names its pictures, fonts and style sheets in `files/<sha256>.<ext>`, and never a script. The page reads each file with its own session and hands the frame bytes, and before the frame adopts the tree it puts an address of its own making in the place of each: a `blob:` address for a picture and a `data:` address for a font, both typed by the document's own table and never by the markup or by the bytes. A name it was not handed stays as written, and the policy refuses the load.

A `link` to a handed style sheet is drawn as a `style` element in its place, from the handed bytes as the browser's own CSS parser reads them, with every `@import` dropped. A sheet lives in `files/`, so it may name a file there by its bare name. Every other `link` is left out, and a script handed as a file is refused by the part at mount and by the document with its whole draw.

A `url()` in a `style` element or a `style` attribute is read by the tokenizer of CSS Syntax Level 3, not by a search over the text: a string, a comment and an escape each end where that specification says, so an address inside a `content` string is not one and `u\\72 l(...)` is the one it spells. An SVG file is only ever used where a browser draws it as a picture, never inline.

Four forms take a handed file: `img src`, an SVG `image href`, the text of a `style` element and a `style` attribute. Every other form, such as `srcset`, `poster`, `background`, `feImage`, `fill="url()"` or `image-set()`, stays as written and the policy refuses the load.

A picture as bytes and the site's own Inter as bytes, named by their SHA-256.

```tsx
import { useEffect, useState } from "react";
import { CanvasFrame } from "@arcadia/ui";

function Files() {
  const [files, setFiles] = useState<readonly CanvasFile[]>([]);
  const [source, setSource] = useState<string | null>(null);
  useEffect(() => {
    let live = true;
    const link = document.querySelector('link[rel="preload"][as="font"]');
    const address = link ? link.getAttribute("href") : null;
    const font = address ? fetch(address).then((answer) => answer.blob()) : Promise.resolve(new Blob());
    const picture = Promise.resolve(new Blob([PICTURE], { type: "image/svg+xml" }));
    void Promise.all([picture.then((bytes) => namedFile(bytes, "svg")), font.then((bytes) => namedFile(bytes, "woff2"))]).then(([drawn, written]) => {
      if (!live || !written.bytes.size) return;
      setFiles([drawn, written]);
      setSource(
        '<style>@font-face{font-family:captured;src:url(files/' + written.name + ')}body{margin:0;padding:12px;background:#fff;color:#17171a;font:15px/1.4 captured,sans-serif}img{display:block;width:160px;height:90px}</style>' +
        '<img src="files/' + drawn.name + '" alt="A round mark" data-canvas-id="e1"><p data-canvas-id="e2">This line is drawn in the site\'s own Inter, from bytes.</p>',
      );
    });
    return () => { live = false; };
  }, []);
  return <CanvasFrame src={FRAME} kind="html" source={source} files={files} title="A drawn page" elementSeq={2} width={256} height={180} />;
}
```

## The document

The kit holds the document's source at `src/lib/canvas/frame` and the two files it serves in `frame/served`: a doctype, a charset and one deferred script, with no style of its own. The manifest names the served files by their SHA-256 and the hash of those lines is the hash in the address. The kit's check builds them again and fails when the committed bytes differ. A product serves the two files as they are under `canvasFrameHeaders()`; the site's own copy at `/canvas/frame` is served under the same function with `script-src 'self'` and `frame-ancestors` set to its own origin, written into `_headers` by the build.

```tsx
Content-Security-Policy: sandbox allow-scripts; default-src 'none'; script-src 'self' https://arcadiausercontent.com/canvas/; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src data:; connect-src 'none'; worker-src 'none'; frame-src 'none'; object-src 'none'; form-action 'none'; base-uri 'none'; frame-ancestors https://crew.arcadia.is
Cross-Origin-Resource-Policy: cross-origin
X-Content-Type-Options: nosniff
Referrer-Policy: no-referrer
Cache-Control: public, max-age=31536000, immutable
```

A product runs both checks. `canvasFrameCheck` reads the files in the folder a product serves and compares their bytes with the manifest. `canvasFrameHeadersCheck` reads a response's headers and compares them with this policy. Neither proves the other, and neither reads the body the address serves.

## Commenting

With a pick mode on, the frame is not inert: it reports the element under the pointer, once an animation frame at most, and only when that element is the topmost at its own centre. A box is clipped to the document's viewport. A pick is a place and a box, never an act: it opens the composer and does nothing more. The scored mode is Agimut's hit test, over the elements that carry an id and not the page's shell; the deepest mode is the innermost element under the pointer that carries one.

Three pick modes over the same page. The wheel over a frame belongs to the plane, not to the document.

```tsx
import { useState } from "react";
import { CanvasFrame, SegmentedControl } from "@arcadia/ui";

function Picking() {
  const [mode, setMode] = useState<"off" | "scored" | "deepest">("scored");
  const [over, setOver] = useState<{ id: string | null; box: CanvasBox | null }>({ id: null, box: null });
  const [picked, setPicked] = useState<string | null>(null);
  const words = picked
    ? "Picked " + picked
    : over.id && over.box
      ? "Hovering " + over.id + ", " + Math.round(over.box.w) + " by " + Math.round(over.box.h)
      : mode === "off"
        ? "Picks are off"
        : "Point at an element";
  return (
    <div {...stylex.props(page.stack)}>
      <SegmentedControl
        aria-label="Pick mode"
        value={mode}
        onValueChange={(value) => { setMode(value as "off" | "scored" | "deepest"); setPicked(null); }}
        items={[{ value: "off", label: "Off" }, { value: "scored", label: "Scored" }, { value: "deepest", label: "Deepest" }]}
      />
      <CanvasFrame
        src={FRAME}
        kind="html"
        source={SAMPLE}
        title="Ship notes"
        elementSeq={4}
        width={256}
        height={212}
        pick={mode}
        onHover={(id, box) => setOver({ id, box })}
        onPick={(id) => setPicked(id)}
      />
      <p {...stylex.props(page.readout)}>{words}</p>
    </div>
  );
}
```

### Pins over a frame

The plane stands its pins in an overlay; a product that draws the frame itself passes the same layer, scaled with the page.

A comment on an element, at its top right corner, over the capture's 1440-wide layout drawn into 256; a press outlines it.

```tsx
import { useRef, useState } from "react";
import { CanvasFrame, useCanvasPins } from "@arcadia/ui";

function Pinned() {
  const root = useRef<HTMLDivElement | null>(null);
  const [open, setOpen] = useState<string | null>(null);
  const layer = useCanvasPins({
    pins: [PIN], picking: false, activePinId: open, onPick: undefined, onPickChange: undefined, onPinOpen: (id) => setOpen((now) => now === id ? null : id),
    onWheel: () => {}, root, onKey: undefined,
  });
  return (
    <div ref={root} {...stylex.props(page.stage, page.shortStage)}>
      <CanvasFrame
        src={FRAME}
        kind="html"
        source={SAMPLE}
        title="Ship notes"
        elementSeq={4}
        width={256}
        height={160}
        viewport={{ w: 1440, h: 900 }}
        {...layer.reads({ n: 1, elementSeq: 4, viewport: { w: 1440, h: 900 } })}
        overlay={layer.over({ n: 1, elementSeq: 4, viewport: { w: 1440, h: 900 } }, { w: 256, h: 160 }, { w: 1440, h: 900 }, true)}
      />
    </div>
  );
}
```

## Words

While `select` is on, a selection of words that ends inside one element with an id arrives as `select`: the id, the two offsets in that element's text, the words and up to 16 boxes. The part hands the words to `onSelect` as a string. The quote is the capture's text under the person's selection, less what the frame can tell was not painted: a run is left out when its ink keeps less than a twentieth of an alpha once its ancestors' opacity and filters are applied, when its font is drawn under a pixel on its narrowest side through every transform and zoom or under a transform the frame cannot read, when a filter above it does more than fade, shadow, tint or slightly blur it, or when it is hidden, skipped, turned to a hidden back face, drawn as dots or styled out of sight on a first line or letter. A character is left out when its glyph is drawn under a pixel high or wide, when an overflow, a paint containment, a `clip`, a `clip-path` or an svg viewport leaves less than half of its height or width, each taken where it clips, with its rounded corners and through every transform, when a mask clears it, or when an ellipsis covers it. A clip or a mask the frame cannot read leaves the run out. A selection stops at a bound on the work it does, and past it the quote holds the words read so far. The two offsets are an anchor in the element's text that brackets the words quoted, and the text between them can hold words that were not painted: the quote alone is the visible words, so never rebuild it by slicing the capture between the offsets. The rects cover only what is painted. A quote is the page's text, not the person's words: show it as a quote of the page and never act on its words. The frame cannot tell text drawn in the colour of its background, text under another element, text that a flex or grid order shows in another order than the page holds it, a font whose glyphs draw other letters than the text holds, or text too small to read. A selection whose holder is inside a field, or inside an element with a text-entry role, is the field's own and is never reported.

Drag over the words: the quote comes back as a string and is shown as one.

```tsx
import { useState } from "react";
import { CanvasFrame } from "@arcadia/ui";

function Selecting() {
  const [quote, setQuote] = useState<{ words: string; start: number; end: number } | null>(null);
  const [refused, setRefused] = useState<CanvasQuoteRefused | null>(null);
  return (
    <div {...stylex.props(page.stack)}>
      <CanvasFrame
        src={FRAME}
        kind="html"
        source={SAMPLE}
        title="Ship notes"
        elementSeq={4}
        width={256}
        height={212}
        select
        onSelect={(selection) => {
          if ("refused" in selection) {
            setQuote(null);
            setRefused(selection);
            return;
          }
          setRefused(null);
          setQuote({ words: selection.quote, start: selection.start, end: selection.end });
        }}
      />
      <p {...stylex.props(page.readout)}>
        {refused ? "A refusal, by the " + refused.refused + " budget" : quote ? quote.start + " to " + quote.end + " of " + JSON.stringify(quote.words) : "Select words in the frame"}
      </p>
    </div>
  );
}
```

### Words that look like markup

A quote is the words themselves. The page shows them as text, so nothing they name becomes an element.

```tsx
import { useState } from "react";
import { CanvasFrame } from "@arcadia/ui";

function Words() {
  const [quote, setQuote] = useState<string | null>(null);
  return (
    <div {...stylex.props(page.stack)}>
      <CanvasFrame
        src={FRAME}
        kind="html"
        source={MARKUP}
        title="Words that look like markup"
        elementSeq={1}
        width={256}
        height={72}
        select
        onSelect={(selection) => setQuote("refused" in selection ? null : selection.quote)}
      />
      <p {...stylex.props(page.readout)}>{quote === null ? "Select the words" : "The quote, as text: " + JSON.stringify(quote)}</p>
    </div>
  );
}
```

### Too much to quote

The frame can shorten a quote when a selection exceeds its budget.

Press the paragraph three times to select all of it. Then select one sentence to get a quote.

```tsx
import { useState } from "react";
import { CanvasFrame } from "@arcadia/ui";

function TooMuch() {
  const [said, setSaid] = useState<CanvasWords | CanvasQuoteRefused | null>(null);
  return (
    <div {...stylex.props(page.stack)}>
      <CanvasFrame
        src={FRAME}
        kind="html"
        source={LONG}
        title="A long paragraph"
        elementSeq={1}
        width={304}
        height={528}
        select
        onSelect={setSaid}
      />
      <p {...stylex.props(page.readout)}>
        {said === null || ("quote" in said && said.quote === "") ? "Select the whole paragraph"
          : "refused" in said || said.quote === "[unread]" ? "No quote returned"
          : said.quote.endsWith("[unread]") ? "Quote shortened to fit the budget"
          : "A quote of " + [...said.quote].length + " characters"}
      </p>
    </div>
  );
}
```

## Keys, X-ray and the pen

A step is a question about one direction and its answer is a hover: the document finds the nearest element in that direction with Agimut's score, or the parent, the child, the next or the previous. X-ray's rectangle becomes a survey of the elements inside it, outermost first, with their boxes, paddings, margins, gaps and radius; the page draws the veil, the grid and the labels from those numbers. A probe answers the colour of the ground under each point, for the ink of a pen line, and says so as numbers.

### A step by arrow keys

Each press asks the frame where the nearest element lies in that direction.

```tsx
import { useRef, useState } from "react";
import { CanvasFrame } from "@arcadia/ui";

function Stepping() {
  const frame = useRef<CanvasFrameHandle | null>(null);
  const [at, setAt] = useState<{ id: string | null; box: CanvasBox | null }>({ id: "e1", box: null });
  const [last, setLast] = useState<string>("Press an arrow key");
  const move = (dir: "left" | "right" | "up" | "down") => {
    void frame.current?.step(at.id, dir).then((answer) => {
      if (!answer) return;
      setAt(answer);
      setLast(dir + " from " + (at.id ?? "the middle") + " to " + (answer.id ?? "nothing"));
    });
  };
  return (
    <div {...stylex.props(page.stack)}>
      <div {...stylex.props(page.stage, page.tallStage)}>
        <CanvasFrame
          ref={frame}
          src={FRAME}
          kind="html"
          source={SAMPLE}
          title="Ship notes"
          elementSeq={4}
          width={256}
          height={212}
          measure={at.id ? [at.id] : []}
          onBoxes={(boxes) => { const box = at.id ? boxes.get(at.id) : null; if (box) setAt({ id: at.id, box }); }}
          onKey={(key) => {
            if (key === "ArrowLeft") move("left");
            if (key === "ArrowRight") move("right");
            if (key === "ArrowUp") move("up");
            if (key === "ArrowDown") move("down");
            if (key !== "Escape") setLast("Key " + key);
          }}
        />
        {at.box && <span {...stylex.props(page.outline)} style={{ left: at.box.x, top: at.box.y, width: at.box.w, height: at.box.h }} />}
      </div>
      <p {...stylex.props(page.readout)}>{last}</p>
    </div>
  );
}
```

### A survey

One rectangle, one answer of numbers; the outlines and bars here are drawn from it.

```tsx
import { useRef, useState } from "react";
import { Button, CanvasFrame } from "@arcadia/ui";

function Surveying() {
  const frame = useRef<CanvasFrameHandle | null>(null);
  const [survey, setSurvey] = useState<CanvasSurvey | null>(null);
  const [count, setCount] = useState("Nothing surveyed");
  const take = () => {
    void frame.current?.survey({ x: 8, y: 8, w: 240, h: 196 }).then((answer) => {
      setSurvey(answer);
      setCount(answer ? answer.items.length + " elements, " + answer.bars.length + " lines" + (answer.more ? ", more" : "") : "The frame did not answer");
    });
  };
  return (
    <div {...stylex.props(page.stack)}>
      <Button onClick={take}>Survey the frame</Button>
      <div {...stylex.props(page.stage, page.tallStage)}>
        <CanvasFrame src={FRAME} kind="html" source={SAMPLE} title="Ship notes" elementSeq={4} width={256} height={212} ref={frame} />
        {survey?.items.map((item) => (
          <span key={item.id} {...stylex.props(page.outline)} style={{ left: item.box.x, top: item.box.y, width: item.box.w, height: item.box.h }} />
        ))}
        {survey?.bars.map((bar, at) => (
          <span key={at} {...stylex.props(page.bar)} style={{ left: bar.x, top: bar.y, width: bar.w, height: bar.h }} />
        ))}
      </div>
      <p {...stylex.props(page.readout)}>{count}</p>
    </div>
  );
}
```

### A probe

The ground colour under three points, or no colour over a picture.

```tsx
import { useEffect, useRef, useState } from "react";
import {
  Button, CanvasFrame, Spinner, ToolbarGlyph, toolbarGlyphNames, useCanvasPins,
} from "@arcadia/ui";

function Probing() {
  const frame = useRef<CanvasFrameHandle | null>(null);
  const [points, setPoints] = useState<readonly { id: string; colour: readonly [number, number, number] }[]>([]);
  const take = () => {
    void frame.current?.probe([[20, 20], [128, 120], [250, 200]]).then((answer) => setPoints(answer ?? []));
  };
  return (
    <div {...stylex.props(page.stack)}>
      <Button onClick={take}>Probe three points</Button>
      <CanvasFrame src={FRAME} kind="html" source={SAMPLE} title="Ship notes" elementSeq={4} width={256} height={212} ref={frame} />
      <p {...stylex.props(page.readout)}>
        {points.length
          ? points.map((point, at) => (
              <span key={at}>
                <span {...stylex.props(page.swatch)} style={point.colour[0] < 0 ? undefined : { backgroundColor: "rgb(" + point.colour.join(",") + ")" }} />
                {point.id || "no element"} {point.colour[0] < 0 ? "no colour" : point.colour.join(", ")}
                {at < points.length - 1 ? "; " : ""}
              </span>
            ))
          : "Nothing probed"}
      </p>
    </div>
  );
}

function Files() {
  const [files, setFiles] = useState<readonly CanvasFile[]>([]);
  const [source, setSource] = useState<string | null>(null);
  useEffect(() => {
    let live = true;
    const link = document.querySelector('link[rel="preload"][as="font"]');
    const address = link ? link.getAttribute("href") : null;
    const font = address ? fetch(address).then((answer) => answer.blob()) : Promise.resolve(new Blob());
    const picture = Promise.resolve(new Blob([PICTURE], { type: "image/svg+xml" }));
    void Promise.all([picture.then((bytes) => namedFile(bytes, "svg")), font.then((bytes) => namedFile(bytes, "woff2"))]).then(([drawn, written]) => {
      if (!live || !written.bytes.size) return;
      setFiles([drawn, written]);
      setSource(
        '<style>@font-face{font-family:captured;src:url(files/' + written.name + ')}body{margin:0;padding:12px;background:#fff;color:#17171a;font:15px/1.4 captured,sans-serif}img{display:block;width:160px;height:90px}</style>' +
        '<img src="files/' + drawn.name + '" alt="A round mark" data-canvas-id="e1"><p data-canvas-id="e2">This line is drawn in the site\'s own Inter, from bytes.</p>',
      );
    });
    return () => { live = false; };
  }, []);
  return <CanvasFrame src={FRAME} kind="html" source={source} files={files} title="A drawn page" elementSeq={2} width={256} height={180} />;
}

const MARKUP = '<p data-canvas-id="e1" style="margin:0">&lt;img src=x onerror=alert(1)&gt; is words here, not an image.</p>';

function Words() {
  const [quote, setQuote] = useState<string | null>(null);
  return (
    <div {...stylex.props(page.stack)}>
      <CanvasFrame
        src={FRAME}
        kind="html"
        source={MARKUP}
        title="Words that look like markup"
        elementSeq={1}
        width={256}
        height={72}
        select
        onSelect={(selection) => setQuote("refused" in selection ? null : selection.quote)}
      />
      <p {...stylex.props(page.readout)}>{quote === null ? "Select the words" : "The quote, as text: " + JSON.stringify(quote)}</p>
    </div>
  );
}

const LONG = '<p data-canvas-id="e1" style="margin:0">' + "The queue held 42 builds overnight, and each one waited for the same runner to come back. ".repeat(12) + "</p>";

function TooMuch() {
  const [said, setSaid] = useState<CanvasWords | CanvasQuoteRefused | null>(null);
  return (
    <div {...stylex.props(page.stack)}>
      <CanvasFrame
        src={FRAME}
        kind="html"
        source={LONG}
        title="A long paragraph"
        elementSeq={1}
        width={304}
        height={528}
        select
        onSelect={setSaid}
      />
      <p {...stylex.props(page.readout)}>
        {said === null || ("quote" in said && said.quote === "") ? "Select the whole paragraph"
          : "refused" in said || said.quote === "[unread]" ? "No quote returned"
          : said.quote.endsWith("[unread]") ? "Quote shortened to fit the budget"
          : "A quote of " + [...said.quote].length + " characters"}
      </p>
    </div>
  );
}

function Loading() {
  return (
    <CanvasFrame
      src={FRAME} kind="html" source={null} title="Ship notes" elementSeq={0} width={256} height={212} inert
      overlay={<div role="status" {...stylex.props(page.pendingStatus)}><Spinner size="text" />{" "}Loading frame</div>}
    />
  );
}

function Usage() {
  return (
    <CanvasFrame
      kind={item.kind}
      source={markup}
      files={item.files}
      title={item.title}
      elementSeq={item.elementSeq}
      width={item.w}
      height={item.h}
      pick={item.tool === "comment" ? "scored" : "off"}
      select
      measure={["e1"]}
      onPick={(element, box, press) => openComposer(element, box, press.n)}
      onSelect={(selection) => ("refused" in selection ? dropQuote() : holdQuote(selection.quote))}
      onBoxes={holdBoxes}
      onKey={(key, mods) => claimKey(key, mods)}
      onGone={() => reload(item.n)}
    />
  );
}
const item = { kind: "html" as const, title: "Queue history", elementSeq: 7, w: 640, h: 420, n: 3, tool: "comment", files: [] as readonly CanvasFile[] };
const markup: string | null = null;
const openComposer = (element: string, box: CanvasBox, n: number) => ({ element, box, n });
const holdQuote = (quote: string) => ({ quote });
const dropQuote = () => null;
const holdBoxes = (boxes: ReadonlyMap<string, CanvasBox>) => boxes;
const claimKey = (key: string, mods: number) => ({ key, mods });
const reload = (n: number) => n;

export default function CanvasFramePage() {
  return (
    <>
      <Section title="When to use">
        <Bullets items={[
          "A page a team reads, comments on and changes together in the canvas",
          "Markup a person wrote: HTML, CSS or SVG, drawn as a page and not as a picture",
        ]} />
      </Section>

      <Section title="When not to use">
        <Bullets items={[
          "A page on Arcadia's own origin, where its script runs. A frame is for markup that nobody reviewed as code",
          "A still of a page, which is `Shot`",
        ]} />
      </Section>

      <Section title="In context">
        <P>
          A frame is one stored source, drawn inside a sandboxed document with no network and no script of its own. The
          document says it is ready over its window; the part checks that window, the null origin and the instance tag,
          then hands the document one port. Every message after that goes over the port, so a page the frame navigated to
          cannot speak and is sent nothing.
        </P>
        <Specimen code={SRC.Note} layout="column" caption="A page of markup behind the wall. Press it to scroll inside, Escape to leave.">
          <Note />
        </Specimen>
      </Section>

      <Section title="Frame header">
        <P>The title and source sit above the frame.</P>
        <Specimen code={SRC.Header} layout="column" caption="Rename, resize or zoom to the frame">
          <Header />
        </Specimen>
      </Section>

      <Section title="The wall">
        <P>The wall is the framed document and the checks the part keeps on both sides of it.</P>
        <Bullets items={[
          "`sandbox` is `allow-scripts` and nothing else; with `allow-same-origin` the document would have a real origin",
          "The document runs only in an opaque origin: a copy that is framed without `sandbox` does nothing at all",
          "`allow` is empty, so the frame has no feature of the device",
          "Markup arrives by `draw` and no other way: the part never reads the document and never sets `srcdoc`",
          "The policy stops every request: `default-src 'none'`, with `img-src data: blob:` the only source that reaches a resource, and no frame, form, worker or connection source",
          "The parse removes `script` and the elements it names, and every attribute that begins with `on`, so a script in the source never reaches the document; it also leaves out `base`, `link`, `meta`, `iframe`, `frame`, `frameset`, `object`, `embed`, `portal`, `fencedframe`, `area` and `map`, and the attributes `srcdoc`, `ping`, `autofocus`, `usemap` and `autoplay`",
          "Every auxclick, contextmenu, submit, dragstart and drop is cancelled on purpose, and so is every click and double click while a tool picks. While none picks, a click and a double click do what HTML does alone (a label ticks its box, a summary opens its details, a button shows its popover) unless they land on a link, an area or a file input, so nothing in a frame navigates, submits or asks for a file",
          "A link keeps its look and its place in the Tab order, and its address becomes a fragment of the frame's own document: a browser that opens a connection to a pressed link's host, before any listener can cancel the press, finds no other host",
          "The element is inert until the person goes into it or holds a tool",
          "A frame that navigated, stayed silent, sent more than 60 counted messages in a second or more than 240 box or scroll reports in a second is taken out and reported by `onGone`; hover and wheel reports are coalesced to one an animation frame and are not counted, and a hover that answers no open ask is counted",
        ]} />
      </Section>

      <Section title="What crosses">
        <P>
          A frame sends numbers, ids and text. An id is a `data-canvas-id` of the frame's own markup, below the part's
          `elementSeq`; a number is finite and within 100,000; a text is a string within its bound. Nothing a frame sends is
          markup, an address, a selector or a style of the page, and nothing follows from it but a report to the part's
          callbacks.
        </P>
        <Bullets items={[
          "`hover` and `pick` are two to nine numbers and an id: a place, a size, the document's scroll offsets, the modifiers and 1 or 2 for a double press",
          "`select` is an id, two whole numbers as offsets in that element's own text, and the selected words as a string of 1,000 characters at most, cut at the bound",
          "The words of a selection reach `onSelect` as a string and nothing else is done with them: a product shows them as text and stores them as text",
          "`selectLimit` names the budget a selection passed and carries no words; it reaches `onSelect` as `{ refused }`, never as an empty quote",
          "`step` answers with a `hover`, `survey` with 300 entries of an id and 17 numbers, `probe` with a colour for each of 64 points",
          "`key` is one of Escape, Enter, Tab, the four arrows, Delete, Backspace or one letter or digit, with the modifiers, on a real key while the focus is in the frame and in no field of the capture",
        ]} />
      </Section>

      <Section title="Files">
        <P>
          A capture names its pictures, fonts and style sheets in {"`files/<sha256>.<ext>`"}, and never a script. The page reads each file with its own session and
          hands the frame bytes, and before the frame adopts the tree it puts an address of its own making in the place of
          each: a `blob:` address for a picture and a `data:` address for a font, both typed by the document's own table and
          never by the markup or by the bytes. A name it was not handed stays as written, and the policy refuses the load.
        </P>
        <P>
          A {"`link`"} to a handed style sheet is drawn as a {"`style`"} element in its place, from the handed bytes as the
          browser's own CSS parser reads them, with every {"`@import`"} dropped. A sheet lives in {"`files/`"}, so it may name a
          file there by its bare name. Every other {"`link`"} is left out, and a script handed as a file is refused by the part
          at mount and by the document with its whole draw.
        </P>
        <P>
          A `url()` in a `style` element or a `style` attribute is read by the tokenizer of CSS Syntax Level 3, not by a
          search over the text: a string, a comment and an escape each end where that specification says, so an address
          inside a `content` string is not one and `u\\72 l(...)` is the one it spells. An SVG file is only ever used where a
          browser draws it as a picture, never inline.
        </P>
        <P>
          Four forms take a handed file: `img src`, an SVG `image href`, the text of a `style` element and a `style`
          attribute. Every other form, such as `srcset`, `poster`, `background`, `feImage`,
          `fill="url()"` or `image-set()`, stays as written and the policy refuses the load.
        </P>
        <Specimen code={SRC.Files} layout="column" caption="A picture as bytes and the site's own Inter as bytes, named by their SHA-256.">
          <Files />
        </Specimen>
      </Section>

      <Section title="The document">
        <P>
          The kit holds the document's source at `src/lib/canvas/frame` and the two files it serves in `frame/served`: a
          doctype, a charset and one deferred script, with no style of its own. The manifest names the served files by
          their SHA-256 and the hash of those lines is the hash in the address. The kit's check builds them again and
          fails when the committed bytes differ. A product serves the two files as they are under `canvasFrameHeaders()`;
          the site's own copy at `/canvas/frame` is served under the same function with `script-src 'self'` and
          `frame-ancestors` set to its own origin, written into `_headers` by the build.
        </P>
        <CodeBlock code={HEADERS} />
        <P>
          A product runs both checks. `canvasFrameCheck` reads the files in the folder a product serves and compares
          their bytes with the manifest. `canvasFrameHeadersCheck` reads a response's headers and compares them with this
          policy. Neither proves the other, and neither reads the body the address serves.
        </P>
      </Section>

      <Section title="Commenting">
        <P>
          With a pick mode on, the frame is not inert: it reports the element under the pointer, once an animation frame at
          most, and only when that element is the topmost at its own centre. A box is clipped to the document's viewport. A
          pick is a place and a box, never an act: it opens the composer and does nothing more. The scored mode is Agimut's
          hit test, over the elements that carry an id and not the page's shell; the deepest mode is the innermost element
          under the pointer that carries one.
        </P>
        <Specimen code={SRC.Picking} layout="column" caption="Three pick modes over the same page. The wheel over a frame belongs to the plane, not to the document.">
          <Picking />
        </Specimen>
        <Sub title="Pins over a frame" lead="The plane stands its pins in an overlay; a product that draws the frame itself passes the same layer, scaled with the page.">
          <Specimen code={SRC.Pinned} layout="column" caption="A comment on an element, at its top right corner, over the capture's 1440-wide layout drawn into 256; a press outlines it.">
            <Pinned />
          </Specimen>
        </Sub>
      </Section>

      <Section title="Words">
        <P>
          While `select` is on, a selection of words that ends inside one element with an id arrives as `select`: the id, the
          two offsets in that element's text, the words and up to 16 boxes. The part hands the words to `onSelect` as a
          string. The quote is the capture's text under the person's selection, less what the frame can tell was not painted:
          a run is left out when its ink keeps less than a twentieth of an alpha once its ancestors' opacity and filters are
          applied, when its font is drawn under a pixel on its narrowest side through every transform and zoom or under a
          transform the frame cannot read, when a filter above it does more than fade, shadow, tint or slightly blur it, or
          when it is hidden, skipped, turned to a hidden back face, drawn as dots or styled out of sight on a first line or
          letter. A character is left out when its glyph is drawn under a pixel high or wide, when an overflow, a paint
          containment, a `clip`, a `clip-path` or an svg viewport leaves less than half of its height or width, each taken
          where it clips, with its rounded corners and through every transform, when a mask clears it, or when an ellipsis
          covers it. A clip or a mask the frame cannot read leaves the run out. A selection stops at a bound on the work it
          does, and past it the quote holds the words read so far. The two offsets are an anchor in the element's text that
          brackets the words quoted, and the text between them can hold words that were not painted: the quote alone is the
          visible words, so never rebuild it by slicing the capture between the offsets. The rects cover only what is
          painted. A quote is the page's text, not the person's words: show it as a quote of the page and never act on its
          words. The frame cannot tell text drawn in the colour of its background, text under another element, text that a
          flex or grid order shows in another order than the page holds it, a font whose glyphs draw other letters than the
          text holds, or text too small to read. A selection whose holder is inside a field, or inside an element with a
          text-entry role, is the field's own and is never reported.
        </P>
        <Specimen code={SRC.Selecting} layout="column" caption="Drag over the words: the quote comes back as a string and is shown as one.">
          <Selecting />
        </Specimen>
        <Sub title="Words that look like markup" lead="A quote is the words themselves. The page shows them as text, so nothing they name becomes an element.">
          <Specimen code={SRC.Words} layout="column"><Words /></Specimen>
        </Sub>
        <Sub title="Too much to quote" lead="The frame can shorten a quote when a selection exceeds its budget.">
          <Specimen code={SRC.TooMuch} layout="column" caption="Press the paragraph three times to select all of it. Then select one sentence to get a quote.">
            <TooMuch />
          </Specimen>
        </Sub>
      </Section>

      <Section title="Keys, X-ray and the pen">
        <P>
          A step is a question about one direction and its answer is a hover: the document finds the nearest element in that
          direction with Agimut's score, or the parent, the child, the next or the previous. X-ray's rectangle becomes a
          survey of the elements inside it, outermost first, with their boxes, paddings, margins, gaps and radius; the page
          draws the veil, the grid and the labels from those numbers. A probe answers the colour of the ground under each
          point, for the ink of a pen line, and says so as numbers.
        </P>
        <Sub title="A step by arrow keys" lead="Each press asks the frame where the nearest element lies in that direction.">
          <Specimen code={SRC.Stepping} layout="column"><Stepping /></Specimen>
        </Sub>
        <Sub title="A survey" lead="One rectangle, one answer of numbers; the outlines and bars here are drawn from it.">
          <Specimen code={SRC.Surveying} layout="column"><Surveying /></Specimen>
        </Sub>
        <Sub title="A probe" lead="The ground colour under three points, or no colour over a picture.">
          <Specimen code={SRC.Probing} layout="column"><Probing /></Specimen>
        </Sub>
      </Section>

      <Section title="Examples">
        <Sub title="Canvas toolbar glyphs" lead="The Canvas toolbar has 13 silhouettes. Each takes its ink from the toolbar and is 18 pixels square by default, or the size of the icon of the text style it stands in with size=&quot;text&quot;. Give the control its label and leave the glyph decorative. A standalone glyph takes a label of its own.">
          <Specimen>
            <div {...stylex.props(page.row)}>
              {toolbarGlyphNames.map((name) => <ToolbarGlyph key={name} name={name} />)}
            </div>
          </Specimen>
        </Sub>
        <Sub title="Loading" lead="The frame holds its size while the source loads.">
          <Specimen code={SRC.Loading} layout="column"><Loading /></Specimen>
        </Sub>
        <Sub title="Live" lead="Live, the page takes the pointer, the keys and its own scroll, and no door stands over it.">
          <Specimen code={SRC.Live} layout="column" caption="Press into the page and scroll it: no door asks first.">
            <Live />
          </Specimen>
        </Sub>
      </Section>

      <Section title="Usage">
        <CodeBlock code={displaySnippet(SRC.Usage)} />
        <P>
          Give the frame the kind of its source and the source itself. The address defaults to `canvasFrameSrc()`; a
          caller may pass another only as a same-origin path with no `#` and no `?`, as the site does with
          `/canvas/frame`, or as `canvasFrameSchemeSrc(scheme)`, the kit's own document on a scheme the product's shell
          serves from its own files, whose host is the kit's hash. A path needs a page with an origin of its own: on a page whose origin is opaque, such as a
          sandboxed iframe without `allow-same-origin` or a `file:` page, it throws at mount, and the kit's own address
          still works. The address is the sensitive input of the part: it is a product's own literal, never stored,
          templated or user data. The part adds the instance tag to the address, and it asks for the elements
          named by `measure` again whenever the frame draws or one of their boxes changes, so a plane can keep a pin on a
          moving element.
        </P>
        <P>
          What a product draws over the page goes in `overlay`, a layer in the frame's box that takes no press of its own and is not
          clipped by the frame, so a pin on an element at an edge draws whole.
          The plane's pins are one: `useCanvasPins` gives a frame's reads, the places of its pins and the ground probe, so a
          product that draws the frame itself, as Act's right pane does, stands a comment's pin where the plane would.
        </P>
        <P>
          Three props set the page's own state. `live` takes the page into the pointer, the keys and its own scroll without
          the door. `inert` draws the page and keeps it out of pointer and Tab, and offers no door. `viewport` lays the page
          out at its own size and draws it scaled into the frame's width, so a capture keeps the layout it was taken at;
          give the pins' `over` the same viewport, or a pin stands at the page's unscaled place.
        </P>
        <P>
          The asks are calls on the part's handle: `survey(rect)`, `probe(points)` and `step(from, dir)` each answer a
          promise that settles once, with the frame's one answer, or with null when the frame was drawn again, left or
          took two seconds. `scrollBy(dx, dy)` asks the document to scroll under the pen.
        </P>
      </Section>
    </>
  );
}
```

## Examples

### Canvas toolbar glyphs

The Canvas toolbar has 13 silhouettes. Each takes its ink from the toolbar and is 18 pixels square by default, or the size of the icon of the text style it stands in with size="text". Give the control its label and leave the glyph decorative. A standalone glyph takes a label of its own.

### Loading

The frame holds its size while the source loads.

```tsx
import { CanvasFrame, Spinner } from "@arcadia/ui";

<CanvasFrame
  src={FRAME} kind="html" source={null} title="Ship notes" elementSeq={0} width={256} height={212} inert
  overlay={<div role="status" {...stylex.props(page.pendingStatus)}><Spinner size="text" />{" "}Loading frame</div>}
/>
```

### Live

Live, the page takes the pointer, the keys and its own scroll, and no door stands over it.

Press into the page and scroll it: no door asks first.

```tsx
import { CanvasFrame } from "@arcadia/ui";

<CanvasFrame src={FRAME} kind="html" source={SAMPLE} title="Ship notes" elementSeq={4} width={256} height={160} live />
```

## Usage

```tsx
import { CanvasFrame } from "@arcadia/ui";

<CanvasFrame
  kind={item.kind}
  source={markup}
  files={item.files}
  title={item.title}
  elementSeq={item.elementSeq}
  width={item.w}
  height={item.h}
  pick={item.tool === "comment" ? "scored" : "off"}
  select
  measure={["e1"]}
  onPick={(element, box, press) => openComposer(element, box, press.n)}
  onSelect={(selection) => ("refused" in selection ? dropQuote() : holdQuote(selection.quote))}
  onBoxes={holdBoxes}
  onKey={(key, mods) => claimKey(key, mods)}
  onGone={() => reload(item.n)}
/>
```

Give the frame the kind of its source and the source itself. The address defaults to `canvasFrameSrc()`; a caller may pass another only as a same-origin path with no `#` and no `?`, as the site does with `/canvas/frame`, or as `canvasFrameSchemeSrc(scheme)`, the kit's own document on a scheme the product's shell serves from its own files, whose host is the kit's hash. A path needs a page with an origin of its own: on a page whose origin is opaque, such as a sandboxed iframe without `allow-same-origin` or a `file:` page, it throws at mount, and the kit's own address still works. The address is the sensitive input of the part: it is a product's own literal, never stored, templated or user data. The part adds the instance tag to the address, and it asks for the elements named by `measure` again whenever the frame draws or one of their boxes changes, so a plane can keep a pin on a moving element.

What a product draws over the page goes in `overlay`, a layer in the frame's box that takes no press of its own and is not clipped by the frame, so a pin on an element at an edge draws whole. The plane's pins are one: `useCanvasPins` gives a frame's reads, the places of its pins and the ground probe, so a product that draws the frame itself, as Act's right pane does, stands a comment's pin where the plane would.

Three props set the page's own state. `live` takes the page into the pointer, the keys and its own scroll without the door. `inert` draws the page and keeps it out of pointer and Tab, and offers no door. `viewport` lays the page out at its own size and draws it scaled into the frame's width, so a capture keeps the layout it was taken at; give the pins' `over` the same viewport, or a pin stands at the page's unscaled place.

The asks are calls on the part's handle: `survey(rect)`, `probe(points)` and `step(from, dir)` each answer a promise that settles once, with the frame's one answer, or with null when the frame was drawn again, left or took two seconds. `scrollBy(dx, dy)` asks the document to scroll under the pen.

## API reference

### CanvasFrame

- `src` (`string`, default `canvasFrameSrc()`): The document's address: the kit's own by default, the kit's own on a scheme the product's shell serves (`canvasFrameSchemeSrc`), or a path of the page's own origin with no fragment and no query, which the part resolves against the page's origin and never against the document's base. A render on a server holds no address, and the frame has none until it is entered or a picking tool turns on, when the client sets the absolute address. It is the sensitive input: a product's own literal, never stored, templated or user data.
- `kind` (`"html" | "svg"`, required)
- `source` (`string | null`, required): Null while it loads.
- `files` (`readonly CanvasFile[]`): The pictures, fonts and style sheets the source names in `files/<name>`: bytes from the product, typed by the document itself. A script is never one.
- `title` (`string`, required)
- `sourceLabel` (`string`)
- `selected` (`boolean`)
- `resizing` (`boolean`)
- `onRename` (`(nextTitle: string) => void`)
- `onFocusFrame` (`() => void`)
- `elementSeq` (`number`, required): The last number given to an element of this frame: an id above it is refused.
- `width` (`number`, required)
- `height` (`number`, required)
- `viewport` (`{ readonly w: number; readonly h: number }`): The page's own viewport, when the frame draws it in a box of another size: the document lays out at this size and is drawn scaled to the frame's width. Default: the box.
- `live` (`boolean`, default `false`): The page takes pointer, keys and its own scroll without its door, as a capture a product stands live in a pane. Default: off.
- `inert` (`boolean`, default `false`): The page is drawn and kept out of the pointer and Tab order, so nothing in it can be reached and no door is offered. Default: off.
- `pick` (`CanvasPickMode`, default `"off"`): Off, or one of the two hit tests: `scored` is Agimut's, and `deepest` the innermost element with an id.
- `select` (`boolean`, default `false`)
- `box` (`boolean`, default `false`): A drag over the page draws a box (onDrag) and a press picks when the pointer comes up; words are selected only after a double press on an element that has them. Default: off.
- `measure` (`readonly string[]`): The elements whose boxes the part reports, by onBoxes, again whenever the frame draws or a box changes. A box is clipped to the document's viewport and one that lies wholly outside is left out, so the plane clamps a pin to the same edge.
- `overlay` (`ReactNode`): What the product draws over the page, in the frame's own box: its pins, a pick outline. The layer takes no press of its own; a control in it does.
- `focusable` (`boolean`, default `true`): Whether Tab reaches the page. Off, the page takes no Tab stop; a press in it still focuses its own document, and its keys, Escape too, are reported by onKey, while a field's keys stay with the field. Default: true.
- `onPick` (`(element: string, box: CanvasBox, press: CanvasPress) => void`)
- `onHover` (`(element: string | null, box: CanvasBox | null) => void`)
- `onDrag` (`(drag: CanvasDrag) => void`): With `box`: the box as it is dragged, at most once a frame, and once more at its end.
- `onSelect` (`(selection: CanvasWords | CanvasQuoteRefused) => void`): The selected words, or a refusal when the selection is too large to quote: a refusal replaces the last quote, and the frame tells the person to select less until the next quote. `quote` is a string as it stands: it is never markup, an address, a selector, code or a style of this page, and a product shows it as text.
- `onBoxes` (`(boxes: ReadonlyMap<string, CanvasBox>) => void`)
- `onWheel` (`(wheel: { readonly dx: number; readonly dy: number; readonly zoom: boolean; readonly x: number; readonly y: number }) => void`)
- `onScrolled` (`(scroll: { readonly sx: number; readonly sy: number }) => void`): The document scrolled: its two offsets, for a pen layer's coordinates.
- `onKey` (`(key: string, mods: number) => void`): A real key pressed while the focus is in the frame and in no field of the capture.
- `picture` (`{ readonly w: number; readonly h: number; readonly identity?: string }`)
- `onPicture` (`(bytes: Blob) => void`)
- `onDrawn` (`() => void`)
- `onGone` (`(why: "left" | "silent" | "noisy") => void`): The frame was taken out: it navigated, it stayed silent, or it sent too much.
- `rootStyle` (`RootStyle`): A component's typed override prop: `Layout` and its documented knobs, each the references it takes or another kit knob of its kind; anything else is a type error at the call site (STYLEX.md).
