# Canvas plane

A project's captured pages in sections, one of them entered to fill the plane, with the island at the top and the tools' panel at its side or docked at its foot.

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

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

Open a local page or review changes as a Crew viewer.

Drag from empty space to select frames. Double-click a frame to enter it.

```tsx
import { useState, useRef, useEffect, useLayoutEffect } from "react";
import {
  CanvasPlane, CanvasPreview, Button, CanvasXray, SegmentedControl,
  CommentState, characterFromId, CommentThread, ComposerFrame, IconButton,
  ComposerField, COMPOSER_MAX_HEIGHT, ScrollArea, MessageGroup, Bubble, Avatar,
} from "@arcadia/ui";

function CanvasPlaneStage() {
  const [board, setBoard] = useState({ frames: FRAMES, sections: SECTIONS });
  const edit = (edits: readonly CanvasEdit[]) => {
    setMarks((list) => withEdits(list, edits));
    setBoard((old) => edits.reduce((next, edit) => {
      if (edit.kind === "section.size") return { ...next, sections: next.sections.map((item) => item.n === edit.section ? { ...item, w: edit.w, h: edit.h } : item) };
      if (edit.kind === "section.place") {
        const section = next.sections.find((item) => item.n === edit.section);
        if (section === undefined) return next;
        const x = edit.x - section.x, y = edit.y - section.y;
        const family = new Set([section.n]);
        for (let depth = 0; depth < 4; depth++) {
          for (const item of next.sections) if (item.parent !== undefined && family.has(item.parent)) family.add(item.n);
        }
        return {
          frames: next.frames.map((item) => item.section !== undefined && family.has(item.section) ? { ...item, x: item.x + x, y: item.y + y } : item),
          sections: next.sections.map((item) => family.has(item.n) ? { ...item, x: item.x + x, y: item.y + y } : item),
        };
      }
      if (edit.kind === "frame.remove") return { ...next, frames: next.frames.filter((item) => item.n !== edit.frame) };
      if (edit.kind !== "frame.place" && edit.kind !== "frame.size" && edit.kind !== "frame.section") return next;
      return { ...next, frames: next.frames.map((item) => item.n !== edit.frame ? item
        : edit.kind === "frame.place" ? { ...item, x: edit.x, y: edit.y }
        : edit.kind === "frame.size" ? { ...item, w: edit.w, h: edit.h }
        : { ...item, section: edit.section ?? undefined }) };
    }, old));
  };
  const [selection, setSelection] = useState<CanvasSelection>({ frames: [1], marks: [] });
  const [marks, setMarks] = useState<readonly CanvasMarkItem[]>([]);
  const [pins, setPins] = useState<readonly CanvasPin[]>(PINS);
  const [activePin, setActivePin] = useState<string | null>(null);
  const pin = pins.find((item) => item.id === activePin);
  const frameNumber = pin !== undefined && "frame" in pin.at ? pin.at.frame : undefined;
  const pinnedFrame = board.frames.find((frame) => frame.n === frameNumber);
  return (
    <div {...stylex.props(CanvasPlaneStyles.stage)}>
      <CanvasPlane
        label="Design site pages"
        frames={board.frames}
        sections={board.sections}
        loadSource={source}
        loadPicture={picture}
        frameSrc="/canvas/frame"
        can={{ change: true, comment: true }}
        selection={selection}
        onSelectionChange={setSelection}
        dock
        panelBody={pinnedFrame === undefined ? undefined : <PanelBody frame={pinnedFrame} />}
        marks={marks}
        onEdit={edit}
        pins={pins}
        activePinId={activePin}
        onPinOpen={(id) => setActivePin((current) => current === id ? null : id)}
        onPick={(next) => setPins((list) => [...list.filter((pin) => pin.id !== "draft"), draftPin(next)])}
      />
    </div>
  );
}

function CanvasHostStage() {
  return <HostFixture />;
}

const CanvasPlaneNotes = <>
  <P>
    On the local canvas, select the frame and choose Open live page. Focal has its own page zoom and history. Escape or
    Back to canvas returns to the plane. Review changes shows the file patch and lets you switch between the two crops.
    The Crew viewer can read the canvas and review changes without opening a live page or editing the source.
  </P>
  <P>
    The plane is one tab stop. Its frame header controls and pins follow it. Enter on a header control renames or fits its frame. The arrows walk the frames and sections in
    reading order when nothing is selected. With items selected, the arrows move them one pixel per press, or ten
    with Shift. Delete removes selected frames when the person may change the canvas. With that permission and the select tool, Enter
    selects the focused frame and Enter again enters it; Enter selects the focused section, and for a person who
    may not change the canvas it enters the focused frame at once. Escape puts a tool down first, then leaves the
    entered frame, then lets the selection go. While a tool picks, the page takes no Tab stop, so Escape stays with the
    plane. A frame is heard by its name, where it came from and its status. A pin names its writer, its messages, its
    state in words and the agents at work on its thread, so the waiting mark is never the only sign. A pin with no messages yet, a new comment's draft, draws no number and names
    none. A comment that finds none of its elements says "Element not found". A flag of an agent at work reads its words
    ("Scout is reading"), and the pointers and drags themselves are decoration. Inside an entered frame the arrows are
    left free for the page, except with X-ray or Design mode in hand, where they step from element to element and
    each one's readout is heard. The island follows the plane, and the panel follows the island: its head docks it
    with the arrows, and its bar is one tab stop with the arrow keys moving between the tools. A docked panel has no
    head and no fold: its tools are one group of choices at the canvas's foot, the tool in hand heard as checked,
    the row one tab stop with the arrows, Home and End between the tools. While the pen is in hand its tray stands
    under the island: the inks and the eraser are one tab stop, and the arrows choose between them.
  </P>
  <Keys rows={[
    ["Tab", "Reaches the plane, its frame header controls and pins, then the island, then the pen's tray, then the panel"],
    ["Arrows", "Walks the frames and sections, or nudges the selection by one pixel"],
    ["Shift and arrows", "Nudges the selection by ten pixels"],
    ["Arrows in an entered frame", "With X-ray or Design mode, steps through the page's elements"],
    ["A drag across a frame with X-ray", "Surveys every element in its area, until Escape or the next press"],
    ["Up and Down with the comment tool", "Selects the parent of what is selected, or each element's children"],
    ["Left and Right with the comment tool", "Selects the element before or after, and with Shift adds it; in an entered frame, starts at the first element"],
    ["Enter with the comment tool", "Asks to comment on what is selected"],
    ["Enter", "Selects the focused frame when the person may change it, then enters it; selects the focused section"],
    ["Escape", "Lets the comment tool's selection go, then X-ray's area, then puts a tool down, leaves the entered frame, or lets the selection go"],
    ["Delete", "Removes the selected frame when the person may change the canvas"],
    ["Space and a drag", "Pans without changing tools or selecting a frame. Release Space to return to the current tool"],
    ["Plus and minus", "Zooms in and out"],
    ["Shift 0", "Resets zoom to 100% around the viewport center"],
    ["Shift 1", "Fits the whole canvas"],
    ["Shift 2", "Fits the selected frames"],
    ["Command or Control 0", "Resets zoom to 100% around the center"],
    ["Two-finger scroll", "Pans the plane on both axes"],
    ["Shift and the wheel", "Pans the plane sideways"],
    ["Control or Command and the wheel, or a trackpad pinch", "Zooms about the pointer"],
    ["V, H, C, P, G, T", "Select, Hand, Comment, Draw, X-ray and Design mode, each where the bar or the dock offers it"],
    ["Shift", "While drawing, a straight line from the last point"],
    ["Command or Control D", "Copies the selection when the product supports duplication"],
    ["Alt before moving", "Previews a copy and places it on release when the product supports duplication"],
    ["Alt while moving", "Temporarily turns off snapping"],
    ["Shift and a corner drag", "Resizes a frame in proportion without snapping"],
    ["Alt and a handle drag", "Resizes a frame from its center without snapping. Add Shift on a corner to keep its proportions"],
    ["Option and a drag", "Erases whole lines while the pen is in hand"],
    ["Command Z, Shift Command Z", "Undoes and redoes the lines drawn while the pen is in hand, or Design mode's edits while the plane has the focus"],
  ]} />
</>;

const PREVIEW_FRAMES = FRAMES.filter(({ n }) => n <= 4 || n === 7).map(({ x, y, w, h, picture: name }) => ({
  x, y, w, h, picture: CanvasPlaneFIXTURES + name + ".webp",
}));

function InChat() {
  return <CanvasPreview name="Crew canvas, reorganized" href="/components/canvas-plane" facts="5 frames, changed 2h ago" frames={PREVIEW_FRAMES} />;
}

const CanvasPreviewNotes = <>
  <P>One link, named by the canvas&apos;s name and its facts. The picture is decoration: the frames are hidden from a reader, as the name and the facts say what the card opens.</P>
</>;

const CanvasRunStyles = stylex.create({
  stack: { display: "flex", flexDirection: "column", gap: space["--space-3"], width: "100%", minWidth: 0 },
  bar: { display: "flex", alignItems: "center", gap: space["--space-3"], flexWrap: "wrap" },
  state: { ...stylex.env.text("caption"), color: palette["--text-3"] },
  well: { width: "100%", height: "calc(" + space["--space-16"] + " * 6.5)" },
  page: { display: "block", width: "100%", height: "100%", borderWidth: 0 },
});

export type RunState = "stopped" | "starting" | "running" | "silent" | "escaped";

const STATE_WORDS: Readonly<Record<RunState, string>> = {
  stopped: "Not running. Nothing of the page runs until you press Run.",
  starting: "Starting",
  running: "Running, with no network. Escape or Stop ends it.",
  silent: "Ended: the page said nothing for 5 seconds.",
  escaped: "Ended by Escape.",
};

const runId = () => "run" + crypto.randomUUID().replaceAll("-", "").slice(0, 20);

export 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]);

  const start = () => {
    setState("starting");
    setInst(runId());
  };

  useEffect(() => {
    if (initial === "running") setInst(runId());
  }, [initial]);

  return (
    <div {...stylex.props(CanvasRunStyles.stack)}>
      <div {...stylex.props(CanvasRunStyles.bar)}>
        {!inst && state === "starting" ? <Button loading>Run</Button> : inst ? <Button ref={run} onClick={() => { setInst(""); setState("stopped"); }}>Stop</Button> : <Button ref={run} variant="primary" onClick={start}>Run</Button>}
        <span role="status" {...stylex.props(CanvasRunStyles.state)}>{STATE_WORDS[state]}</span>
      </div>
      {inst && (
        <div {...stylex.props(CanvasRunStyles.well)}>
          <iframe
            ref={frame}
            title="Release notes, running"
            src={new URL("/run/run#" + inst, location.href).href}
            sandbox="allow-scripts allow-forms"
            allow=""
            referrerPolicy="no-referrer"
            {...stylex.props(CanvasRunStyles.page)}
          />
        </div>
      )}
    </div>
  );
}

const CanvasRunNotes = <>
  <P>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.</P>
</>;

const CanvasXrayStyles = stylex.create({
  stack: { display: "flex", flexDirection: "column", alignItems: "flex-start", gap: space["--space-3"], minWidth: 0 },
  stage: { position: "relative", flex: "none", backgroundColor: palette["--bg-inset"], borderRadius: radius["--radius-frame"] },
  card: { position: "absolute", backgroundColor: palette["--bg-card"], borderRadius: radius["--radius-frame"] },
  line: { position: "absolute", backgroundColor: palette["--fill-3"], borderRadius: radius["--radius-inset"] },
  button: { position: "absolute", backgroundColor: palette["--fill-2"], borderRadius: radius["--radius-control"] },
  primary: { backgroundColor: palette["--text-1"] },
});

const PAGE = { w: 320, h: 232 };

const ITEMS: readonly CanvasSurveyItem[] = [
  { id: "e1", box: { x: 0, y: 0, w: 320, h: 232 }, padding: [24, 24, 24, 24], margin: [0, 0, 0, 0], rowGap: 16, columnGap: 0, radius: 12, depth: 1, flags: 2 },
  { id: "e2", box: { x: 24, y: 24, w: 272, h: 24 }, padding: [0, 0, 0, 0], margin: [0, 0, 0, 0], rowGap: 0, columnGap: 0, radius: 0, depth: 2, flags: 0 },
  { id: "e3", box: { x: 24, y: 64, w: 272, h: 60 }, padding: [0, 0, 0, 0], margin: [0, 0, 0, 0], rowGap: 0, columnGap: 0, radius: 0, depth: 2, flags: 0 },
  { id: "e4", box: { x: 24, y: 168, w: 272, h: 40 }, padding: [0, 0, 0, 0], margin: [0, 0, 0, 0], rowGap: 0, columnGap: 8, radius: 0, depth: 2, flags: 0 },
  { id: "e5", box: { x: 112, y: 168, w: 88, h: 40 }, padding: [0, 16, 0, 16], margin: [0, 0, 0, 0], rowGap: 0, columnGap: 0, radius: 8, depth: 3, flags: 1 },
  { id: "e6", box: { x: 208, y: 168, w: 88, h: 40 }, padding: [0, 16, 0, 16], margin: [0, 0, 0, 0], rowGap: 0, columnGap: 0, radius: 8, depth: 3, flags: 1 },
];

const BARS = [
  { x: 24, y: 30, w: 150, h: 12 },
  { x: 24, y: 70, w: 262, h: 9 },
  { x: 24, y: 90, w: 248, h: 9 },
  { x: 24, y: 110, w: 150, h: 9 },
];

const NAMES = [
  { value: "e1", label: "Card" },
  { value: "e2", label: "Title" },
  { value: "e3", label: "Words" },
  { value: "e4", label: "Actions" },
  { value: "e5", label: "Cancel" },
  { value: "e6", label: "Save" },
];

function under(x: number, y: number): string | null {
  let found: CanvasSurveyItem | null = null;
  for (const item of ITEMS) {
    const { box } = item;
    if (x < box.x || y < box.y || x > box.x + box.w || y > box.y + box.h) continue;
    if (found === null || item.depth > found.depth || (item.depth === found.depth && box.w * box.h < found.box.w * found.box.h)) found = item;
  }
  return found?.id ?? null;
}

function Wireframe() {
  const at = (id: string) => ITEMS.find((item) => item.id === id)!.box;
  const place = (box: { x: number; y: number; w: number; h: number }) => ({ left: box.x, top: box.y, width: box.w, height: box.h });
  return (
    <>
      <div {...stylex.props(CanvasXrayStyles.card)} style={place(at("e1"))} />
      {BARS.map((bar) => <div key={bar.y} {...stylex.props(CanvasXrayStyles.line)} style={place(bar)} />)}
      <div {...stylex.props(CanvasXrayStyles.button)} style={place(at("e5"))} />
      <div {...stylex.props(CanvasXrayStyles.button, CanvasXrayStyles.primary)} style={place(at("e6"))} />
    </>
  );
}

function CanvasXrayStage({ hovered, selected, area = null, onHover, onChoose }: {
  readonly hovered: string | null;
  readonly selected: string | null;
  readonly area?: { readonly x: number; readonly y: number; readonly w: number; readonly h: number } | null;
  readonly onHover?: (id: string | null) => void;
  readonly onChoose?: (id: string | null) => void;
}) {
  const point = (event: ReactPointerEvent<HTMLDivElement>) => {
    const box = event.currentTarget.getBoundingClientRect();
    return under(event.clientX - box.left, event.clientY - box.top);
  };
  return (
    <div
      {...stylex.props(CanvasXrayStyles.stage)}
      style={{ width: PAGE.w, height: PAGE.h }}
      onPointerMove={(event) => onHover?.(point(event))}
      onPointerLeave={() => onHover?.(null)}
      onPointerDown={(event) => onChoose?.(point(event))}
    >
      <Wireframe />
      <CanvasXray items={ITEMS} bars={BARS} frame={{ box: { x: 0, y: 0, w: PAGE.w, h: PAGE.h }, page: PAGE }} hovered={hovered} selected={selected} area={area} />
    </div>
  );
}

function Looking() {
  const [hovered, setHovered] = useState<string | null>(null);
  const [selected, setSelected] = useState<string | null>("e3");
  return (
    <div {...stylex.props(CanvasXrayStyles.stack)}>
      <CanvasXrayStage hovered={hovered} selected={selected} onHover={setHovered} onChoose={setSelected} />
      <SegmentedControl aria-label="Element" size="sm" items={NAMES} value={selected ?? ""} onValueChange={setSelected} />
    </div>
  );
}

const CanvasXrayNotes = <>
  <P>
    With nothing chosen the overlay is out of the way of a reader. With an element chosen it is one image whose name
    is the readout: the element, its size and each spacing it carries. It takes no focus and no pointer of its own.
    With an area, it is one image named for the area's size and the number of elements it reaches.
    On a plane, the arrows step the chosen element through an entered frame, and each one's readout is heard.
  </P>
  <Keys rows={[
    ["Arrows", "On a plane with X-ray in hand and a frame entered, steps through the page's elements"],
    ["A drag across a frame", "On a plane with X-ray in hand, surveys every element in its area"],
    ["Escape", "Lets the area go"],
  ]} />
</>;

const AT = 1_766_000_000_000;

const CommentStateMAYA: Actor = { kind: "person", name: "Maya" };

const LEILA = { name: "Leila" };

const CommentStateSCOUT: CommentAgent = { kind: "agent", name: "Scout", avatar: characterFromId("agt_scout_maya"), person: { name: "Maya" } };

const CommentStateStyles = stylex.create({
  list: { display: "flex", flexDirection: "column", gap: space["--space-5"], width: "calc(" + space["--space-16"] + " * 20)", maxWidth: "100%" },
});

function States() {
  return (
    <div {...stylex.props(CommentStateStyles.list)}>
      <CommentState state="open" opener={CommentStateMAYA} />
      <CommentState state="agent" opener={CommentStateMAYA} holder={CommentStateSCOUT} />
      <CommentState state="agent" opener={CommentStateMAYA} holder={CommentStateSCOUT} working />
      <CommentState state="person" opener={CommentStateSCOUT} holder={CommentStateSCOUT} waitsOn={LEILA} />
      <CommentState state="person" opener={CommentStateSCOUT} holder={CommentStateSCOUT} waitsOn={LEILA} you />
      <CommentState state="done" opener={CommentStateMAYA} holder={CommentStateSCOUT} done={{ by: CommentStateSCOUT, at: AT }} />
    </div>
  );
}

function CommentStateNotes() {
  return (
    <>
      <Section title="Accessibility">
        <P>
          The state is said in words, so neither the glyph nor the light carries it alone. The glyph is hidden from
          assistive technology. The waiting mark stands only for the person the comment waits on, and it keeps its own
          shape under forced colours. A working agent's loader is the neutral running glyph.
        </P>
      </Section>
    </>
  );
}

const CommentThreadAT = 1_766_000_000_000;

const CommentThreadMAYA: Actor = { kind: "person", name: "Maya" };

const SCOUT_LOOK = characterFromId("agt_scout_maya");

const CommentThreadSCOUT: CommentAgent = { kind: "agent", name: "Scout", avatar: SCOUT_LOOK, person: { name: "Maya" } };

const COMMENT_SELECTION: CommentThreadSelection = {
  elements: 4,
  lines: [
    "e1k button[submit]: Sign up free",
    "e1m p: No card needed. Cancel any time.",
    "e20 div",
    "e21 a: Compare plans",
  ],
};

const CommentThreadStyles = stylex.create({
  thread: { width: "calc(" + space["--space-16"] + " * 8)", maxWidth: "100%", minWidth: 0 },
  stream: { display: "flex", flexDirection: "column", gap: space["--space-4"] },
  scroll: { maxHeight: `calc(${space["--space-16"]} * 4)`, minHeight: 0 },
  card: { maxHeight: "none" },
});

const scout = <><Avatar kind="agent" avatar={SCOUT_LOOK} name="Scout" size={16} aria-hidden />Scout</>;

function Messages({ words }: { readonly words: readonly { readonly text: string; readonly animate: boolean }[] }) {
  const viewport = useRef<HTMLDivElement>(null);
  useLayoutEffect(() => {
    if (words.length > 0) viewport.current?.scrollTo({ top: viewport.current.scrollHeight });
  }, [words.length]);
  return (
    <ScrollArea label="Messages" viewportRef={viewport} rootStyle={CommentThreadStyles.scroll}>
      <div {...stylex.props(CommentThreadStyles.stream)}>
        <MessageGroup side="end">
          <Bubble side="end">Can the button use Body?</Bubble>
        </MessageGroup>
        <MessageGroup author={scout}>
          <Bubble variant="outline">Done. The heading stays at Title&nbsp;3.</Bubble>
        </MessageGroup>
        {words.map(({ text, animate }, at) => (
          <MessageGroup key={at} side="end">
            <Bubble side="end" enter={animate ? "send" : undefined}>{text}</Bubble>
          </MessageGroup>
        ))}
      </div>
    </ScrollArea>
  );
}

function Composer({ send = "Send", onSend }: { readonly send?: string; readonly onSend: (text: string, animate: boolean) => void }) {
  const [text, setText] = useState("");
  const go = (animate: boolean) => {
    if (text.trim() === "") return;
    onSend(text.trim(), animate);
    setText("");
  };
  return (
    <ComposerFrame compact end={<IconButton icon="arrow-up" label={send} variant="inverse" disabled={text.trim() === ""} onClick={(event) => go(event.detail > 0)} />} aria-label="Reply">
      <ComposerField
        minRows={1}
        maxHeight={COMPOSER_MAX_HEIGHT}
        value={text}
        onChange={(event) => setText(event.target.value)}
        onKeyDown={(event) => {
          if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return;
          event.preventDefault();
          go(false);
        }}
        placeholder="Reply"
        aria-label="Reply to this comment"
      />
    </ComposerFrame>
  );
}

function Thread() {
  const [words, setWords] = useState<readonly { readonly text: string; readonly animate: boolean }[]>([]);
  const [done, setDone] = useState(false);
  return (
    <div {...stylex.props(CommentThreadStyles.thread)}>
      <CommentThread
        rootStyle={CommentThreadStyles.card}
        state={done
          ? <CommentState state="done" opener={CommentThreadMAYA} holder={CommentThreadSCOUT} done={{ by: CommentThreadMAYA, at: CommentThreadAT }} />
          : <CommentState state="agent" opener={CommentThreadMAYA} holder={CommentThreadSCOUT} working />}
        selection={COMMENT_SELECTION}
        actions={done
          ? <Button size="sm" variant="secondary" onClick={() => setDone(false)}>Reopen</Button>
          : <Button size="sm" variant="secondary" onClick={() => setDone(true)}>Mark done</Button>}
        composer={<Composer send={done ? "Reopen and send" : "Send"} onSend={(text, animate) => { setWords((old) => [...old, { text, animate }]); setDone(false); }} />}
      >
        <Messages words={words} />
      </CommentThread>
    </div>
  );
}

function CommentThreadNotes() {
  return (
    <>
      <Section title="Keyboard">
        <Keys rows={[
          ["Tab", "Reaches Close, the selection, the acts, then the product's messages and composer"],
          [["Enter", "Space"], "On the selection, folds its lines"],
        ]} />
      </Section>
      <Section title="Accessibility">
        <P>
          The thread is a region named Comment. The selection is a button that says whether it is expanded, and its
          lines are inert while folded. The close button is named Close. What the product puts in the frame keeps its
          own names and its own announcements.
        </P>
      </Section>
    </>
  );
}

export const FIXTURES: Record<string, CatalogSpec> = {
  "canvas-design-panel": { examples: [{ Preview: Editing, code: SOURCES.Editing, size: "tall", layout: "fill", caption: "A Save button's values as its page reported them. Change one, undo it, then Finish or Discard." }], accessibility: Notes },
  "canvas-panel": { examples: [{ Preview: Stage, code: SOURCES.Stage, layout: "fill", caption: "The panel docked left and bottom, over the plane's ground. Drag its head, or press the head and use the arrows." }], accessibility: CanvasPanelNotes },
  "canvas-plane": { examples: [{ Preview: CanvasHostStage, size: "tall", layout: "fill", caption: "Open a local page or review changes as a Crew viewer." }, { Preview: CanvasPlaneStage, code: SOURCES.CanvasPlaneStage, size: "tall", layout: "fill", caption: "Drag from empty space to select frames. Double-click a frame to enter it." }], accessibility: CanvasPlaneNotes },
  "canvas-preview": { examples: [{ Preview: InChat, code: SOURCES.InChat }], accessibility: CanvasPreviewNotes },
  "canvas-run": { examples: [{ Preview: Run, code: SOURCES.Run, size: "compact" }], accessibility: CanvasRunNotes },
  "canvas-xray": { examples: [{ Preview: Looking, code: SOURCES.Looking, layout: "column", caption: "A small page and its survey. Point for its boxes, or choose one below for its marks and its readout." }], accessibility: CanvasXrayNotes },
  "comment-state": { examples: [{ Preview: States, code: SOURCES.States, size: "tall" }], Notes: CommentStateNotes },
  "comment-thread": { examples: [{ Preview: Thread, code: SOURCES.Thread, size: "tall", surface: "pane", caption: "Mark done, then write a reply: a done comment sends with Reopen and send." }], Notes: CommentThreadNotes },
};
```

## Accessibility

On the local canvas, select the frame and choose Open live page. Focal has its own page zoom and history. Escape or Back to canvas returns to the plane. Review changes shows the file patch and lets you switch between the two crops. The Crew viewer can read the canvas and review changes without opening a live page or editing the source.

The plane is one tab stop. Its frame header controls and pins follow it. Enter on a header control renames or fits its frame. The arrows walk the frames and sections in reading order when nothing is selected. With items selected, the arrows move them one pixel per press, or ten with Shift. Delete removes selected frames when the person may change the canvas. With that permission and the select tool, Enter selects the focused frame and Enter again enters it; Enter selects the focused section, and for a person who may not change the canvas it enters the focused frame at once. Escape puts a tool down first, then leaves the entered frame, then lets the selection go. While a tool picks, the page takes no Tab stop, so Escape stays with the plane. A frame is heard by its name, where it came from and its status. A pin names its writer, its messages, its state in words and the agents at work on its thread, so the waiting mark is never the only sign. A pin with no messages yet, a new comment's draft, draws no number and names none. A comment that finds none of its elements says "Element not found". A flag of an agent at work reads its words ("Scout is reading"), and the pointers and drags themselves are decoration. Inside an entered frame the arrows are left free for the page, except with X-ray or Design mode in hand, where they step from element to element and each one's readout is heard. The island follows the plane, and the panel follows the island: its head docks it with the arrows, and its bar is one tab stop with the arrow keys moving between the tools. A docked panel has no head and no fold: its tools are one group of choices at the canvas's foot, the tool in hand heard as checked, the row one tab stop with the arrows, Home and End between the tools. While the pen is in hand its tray stands under the island: the inks and the eraser are one tab stop, and the arrows choose between them.

- Tab: Reaches the plane, its frame header controls and pins, then the island, then the pen's tray, then the panel
- Arrows: Walks the frames and sections, or nudges the selection by one pixel
- Shift and arrows: Nudges the selection by ten pixels
- Arrows in an entered frame: With X-ray or Design mode, steps through the page's elements
- A drag across a frame with X-ray: Surveys every element in its area, until Escape or the next press
- Up and Down with the comment tool: Selects the parent of what is selected, or each element's children
- Left and Right with the comment tool: Selects the element before or after, and with Shift adds it; in an entered frame, starts at the first element
- Enter with the comment tool: Asks to comment on what is selected
- Enter: Selects the focused frame when the person may change it, then enters it; selects the focused section
- Escape: Lets the comment tool's selection go, then X-ray's area, then puts a tool down, leaves the entered frame, or lets the selection go
- Delete: Removes the selected frame when the person may change the canvas
- Space and a drag: Pans without changing tools or selecting a frame. Release Space to return to the current tool
- Plus and minus: Zooms in and out
- Shift 0: Resets zoom to 100% around the viewport center
- Shift 1: Fits the whole canvas
- Shift 2: Fits the selected frames
- Command or Control 0: Resets zoom to 100% around the center
- Two-finger scroll: Pans the plane on both axes
- Shift and the wheel: Pans the plane sideways
- Control or Command and the wheel, or a trackpad pinch: Zooms about the pointer
- V, H, C, P, G, T: Select, Hand, Comment, Draw, X-ray and Design mode, each where the bar or the dock offers it
- Shift: While drawing, a straight line from the last point
- Command or Control D: Copies the selection when the product supports duplication
- Alt before moving: Previews a copy and places it on release when the product supports duplication
- Alt while moving: Temporarily turns off snapping
- Shift and a corner drag: Resizes a frame in proportion without snapping
- Alt and a handle drag: Resizes a frame from its center without snapping. Add Shift on a corner to keep its proportions
- Option and a drag: Erases whole lines while the pen is in hand
- Command Z, Shift Command Z: Undoes and redoes the lines drawn while the pen is in hand, or Design mode's edits while the plane has the focus

## API reference

### CanvasPlane

- `canvasId` (`string | number`): The canvas's identity when the product reuses this plane for another canvas.
- `label` (`string`, required): Its name for assistive technology, in the product's words.
- `frames` (`readonly CanvasFrameItem[]`, required)
- `sections` (`readonly CanvasSection[]`, default `[]`)
- `marks` (`readonly CanvasMarkItem[]`): Each mark's body is `markToSvg`'s, from its box's corner. A mark that sits on a frame is drawn over it, moves with it and scrolls with its page; a mark on a removed frame, a mark on no frame and a body `markFromSvg` refuses are not drawn.
- `pins` (`readonly CanvasPin[]`): The comments' pins. An element's pin stands at its element's top right corner, measured in a frame drawn from its source and at the box Crew keeps in one that shows its picture; a resolved pin draws nothing.
- `activePinId` (`string | null`): The pin whose thread is open: its element keeps its outline.
- `thread` (`CanvasPinnedThread | null`): The open pin's thread, in the kit's CommentThread, drawn beside that pin; the product owns its messages and its close.
- `peers` (`readonly CanvasPeer[]`): The people and agents on the canvas: a pointer with a name, a drag's outline, and an agent at work on a frame, an element or a comment thread.
- `frameSrc` (`string`): The address of the document that draws a frame, without a fragment.
- `loadSource` (`(frame: CanvasFrameItem) => Promise<string>`): A frame's source. The part asks only for frames it draws from source, and keeps each answer by its digest.
- `renderPage` (`(frame: CanvasFrameItem, interactive?: boolean) => ReactNode`)
- `onOpenPage` (`(frame: CanvasFrameItem) => boolean`)
- `loadFile` (`(name: string) => Promise<Blob>`): The bytes of a file a frame's files name. Successful reads are shared across the plane. A listed stylesheet is required and a rejected read is retried once. Images and fonts may be left out when unavailable or over the frame's bounds.
- `loadPicture` (`(frame: CanvasFrameItem) => Promise<Blob>`): The picture of a frame's page, as bytes. Only image/png, image/jpeg and image/webp are drawn; any other type is refused.
- `can` (`{ readonly change?: boolean; readonly comment?: boolean }`): What this person may do: change the canvas, which moves, sizes and deletes frames and sections and draws lines on them, and comment on them. Default: neither, so a plane without it is read-only.
- `tools` (`readonly CanvasTool[]`): The tools the bar offers, in its order. Select is always there; Comment stands where this person may comment and the product takes a pick (`onPick`), Draw where they may change the canvas and the product takes edits (`onEdit`), X-ray where `xray` is on, and Design mode where `design` is on and the product takes the finish (`onDesignFinish`). A product that draws X-ray or Design mode itself names them here and leaves `xray` and `design` unset; set to false, they stand nowhere. Default: Select, Comment and Draw, then X-ray and Design mode where the plane draws them.
- `tool` (`"select" | "hand" | "comment" | "draw" | "xray" | "design"`): The plane's tools: the bar's choices, and the state a product keeps.
- `defaultTool` (`"select" | "hand" | "comment" | "draw" | "xray" | "design"`, default `"select"`): The plane's tools: the bar's choices, and the state a product keeps.
- `onToolChange` (`(tool: CanvasTool) => void`)
- `selection` (`CanvasSelection`)
- `onSelectionChange` (`(selection: CanvasSelection) => void`)
- `view` (`CanvasView | "fit"`): `"fit"`: the plane shows the fit of its present room, and follows it as the room, the chrome or the frames change.
- `defaultView` (`CanvasView | "fit"`): Where the view starts, the fit when not given. `"fit"` is the view the fit button and the 0 key bring too: every frame and section in the room the plane's controls, its panel and its tray leave, a gap clear of them, with the titles' line above. The plane follows the fit until a gesture, a zoom key or the bar moves the view.
- `onViewChange` (`(view: CanvasView, fit: boolean) => void`): The view as it changes, once the plane knows its size, with `fit` true while that view is the fit: a product that controls `view` keeps following the fit by holding `"fit"` then.
- `entered` (`number | null`): The frame the plane shows alone, with the view brought to it. Null: every frame in view.
- `defaultEntered` (`number | null`, default `null`)
- `onEnteredChange` (`(frame: number | null) => void`)
- `device` (`"captured" | "desktop" | "tablet" | "phone"`): The width every page is drawn at. As captured: each page keeps the size it was captured at.
- `defaultDevice` (`"captured" | "desktop" | "tablet" | "phone"`, default `"captured"`)
- `onDeviceChange` (`(device: CanvasDevice) => void`)
- `renderControls` (`(controls: CanvasPlaneControls) => ReactNode`)
- `renderToolbar` (`(toolbar: CanvasPlaneToolbar) => ReactNode`)
- `panel` (`{ side: "left" | "right"; anchor: "top" | "bottom"; collapsed?: boolean }`): Where the side panel stands.
- `defaultPanel` (`{ side: "left" | "right"; anchor: "top" | "bottom"; collapsed?: boolean }`, default `DEFAULT_PANEL`)
- `onPanelChange` (`(place: CanvasPanelPlace) => void`)
- `panelBody` (`ReactNode`): The panel's body: a comment panel, Design mode's controls.
- `panelFill` (`boolean`): The panel's body fills it and scrolls on its own, as CanvasPanel's `fill`: a thread's list with its field at its foot.
- `dock` (`boolean`, default `false`): The panel stands as the plane's dock: the tools alone, one row of icon buttons pinned at the bottom centre of the canvas with the panel's body above them, outside the canvas the view moves. No head, no fold and no sheet at any width. Default: the side panel, where the product keeps it.
- `liveFrame` (`number`): The frame a product draws itself, live, in the part's own place: the plane draws nothing in its box and keeps reporting it.
- `onLiveBoxes` (`(boxes: { readonly view: CanvasBox; readonly bar: CanvasBox } | null) => void`): While a frame is entered: the frame's box and the island's room, in CSS pixels of the part's own root, whole numbers.
- `onEdit` (`(edits: readonly CanvasEdit[]) => void`): What the person changed, when a gesture ends. The part shows it at once and holds it until frames or sections say the same.
- `onRenameFrame` (`(id: string, title: string) => void`): With can.change, saves a frame name. The ID is the frame number as text; pass the new title back in frames.
- `onDuplicate` (`(ids: readonly string[], offset: CanvasPoint) => void`)
- `onMotion` (`(motion: { readonly pointer?: { readonly x: number; readonly y: number }; readonly drag?: CanvasPeer["drag"] }) => void`): What moves and is not yet a change, for the others who have the canvas open.
- `onPick` (`(pick: CanvasPick) => void`): With the comment tool, for a person who may comment, the person asks to comment on what the tool holds: a press on an element of a frame drawn from its source, the end of a box dragged over one, words selected in an element after a double press, or Enter. A box on a frame drawn from its picture, or one that begins on the board and covers one frame whole, gives that frame with no elements. It opens nothing by itself.
- `onPickChange` (`(pick: CanvasPick | null) => void`): Every change of what the comment tool holds, by the pointer or by the keys, and null once it holds nothing.
- `onPinOpen` (`(id: string) => void`)
- `onPaste` (`(paste: CanvasPaste) => void`)
- `onFrameOpen` (`(frame: number) => void`): A frame was entered.
- `xray` (`boolean`): X-ray, drawn by the plane: over the frame under the pointer, the boxes, spacings and text lines of the element there, its parent and children, and the guides and readout of the one pressed; a drag across a frame surveys every element in its area until Escape or the next press. It reads the frame's survey: the frame's own answer while it is drawn from its source, else `xraySurvey`'s. Default: off.
- `xraySurvey` (`(frame: CanvasFrameItem) => CanvasSurvey | null | undefined`): A frame's survey where the plane cannot ask the frame: one drawn from its picture or its title. Its boxes are in the page's pixels at the frame's viewport.
- `element` (`CanvasDesignAnchor | null`): The element X-ray and Design mode hold: the one last pressed, or stepped to by the arrows in an entered frame. It is held in one version of its frame, and a new version lets it go.
- `defaultElement` (`CanvasDesignAnchor | null`, default `null`)
- `onElementChange` (`(element: CanvasDesignAnchor | null) => void`)
- `design` (`boolean`): Design mode, drawn by the plane: the element is held as in X-ray, and the panel shows its layout, spacing, type, surface and words, read from the survey where it has them, with the edits counted under them. Default: off.
- `designEdits` (`CanvasDesignSession`): Design mode's edits, where the product keeps them: the part stores none when the prop is given.
- `onDesignEdit` (`(edits: CanvasDesignSession) => void`): Every change of the edits: a value, an undo or a redo, a discard, a finish that cleared them, and a new version or the removal of a frame, which drops the edits and the values read of that frame.
- `onDesignPreview` (`(entries: readonly CanvasDesignPreview[]) => void`): The edits in force after every change. The plane already sends each frame drawn from its source the entries of its own elements, and the frame's document shows them, so a product only reads these.
- `onDesignFinish` (`(edits: CanvasDesignSession) => unknown`): Finish: the edits handed over. A promise holds Finish busy until it settles: fulfilled, the edits are cleared and the bar says they were applied; refused, they stay. Anything else clears them at once.
- `onDesignDiscard` (`() => void`): Discard: every pending edit dropped, and its steps with it.
- `designStatus` (`CanvasDesignStatus`): How the finish stands, where the product says so: it wins over the plane's own reading of the promise.
- `designProblem` (`string`): Why a finish failed, in the product's words.
- `rootStyle` (`CanvasPlaneStyle`)
- `ref` (`ReactRef<CanvasPlaneHandle>`): The comment tool's two steps and its letting go, for a composer's Select parent, Select children and Escape.
