isometric-diagrams
GitHubnpmCloud editor ↗

API reference

Each bundle exports one namespace per layer: import { core, objects, viewer, editor } from '@johnoscott/isometric-engine/editor', /render without editor, /systems with systems. Every public module is also a subpath, @johnoscott/isometric-engine/modules/LAYER/MODULE. Read from the package's declarations (v0.49.2).

core src/iso-core

import { core } from '@johnoscott/isometric-engine/render';      // also in /editor and /systems
import { … } from '@johnoscott/isometric-engine/modules/iso-core/MODULE';

Camera interface camera

interface Camera {
    /** what it looks at: a point, in grid units (the middle of the stage) */
    at: P3;
    /** px on the stage for each of the drawing's units */
    zoom: number;
    /** how far round, in quarter turns, any number (0.5 is 45°): 0 as drawn; 1 brings the side that was on the left to the front */
    turn: number;
}

cameraOf function camera

the camera that shows a view box, all of it, in its middle: it looks at the floor there (or at height z)

function cameraOf(v: ViewBox, stage: Stage, turn?: number, z?: number): Camera;

fitCamera function camera

the camera that has these boxes on the stage, margin px inside it

function fitCamera(boxes: readonly Box[], stage: Stage, o?: {
    turn?: number;
    margin?: number;
}): Camera | undefined;

fromStage function camera

the stage's point (px from its top left) on the drawing, at height z; and where a point is on the stage

function fromStage(c: Camera, stage: Stage, px: number, py: number, z?: number): P2;

isoAt function camera

the projection at a turn: grid units to the drawing's

function isoAt(turn: number, x: number, y: number, z?: number): P2;

mixCamera function camera

between two cameras: even in log-zoom, and the middle goes with the zoom, as a motion document's camera does; the turn evenly, from a's to b's as they are (shortTurn for the short way)

function mixCamera(a: Camera, b: Camera, u: number): Camera;

panBy function camera

moved by px of the stage: the drawing goes that way under it

function panBy(c: Camera, dx: number, dy: number): Camera;

planeAt function camera

and back: the point at height z (the floor: 0) that the drawing shows at px, py

function planeAt(turn: number, px: number, py: number, z?: number): P2;

quarterOf const camera

the nearest whole quarter, 0 to 3

const quarterOf: (turn: number) => 0 | 1 | 2 | 3;

shortTurn const camera

the turn nearest to from that looks the same as to: the short way round

const shortTurn: (from: number, to: number) => number;

Stage interface camera

interface Stage {
    w: number;
    h: number;
}

toStage function camera

function toStage(c: Camera, stage: Stage, p: P3): P2;

turnAt function camera

function turnAt(c: Camera, stage: Stage, by: number, px?: number, py?: number): Camera;

turnBox function camera

a box gone round by whole quarters: still square to the grid

function turnBox(b: Box, quarter: number): Box;

turned function camera

a point of the plane, gone round

function turned(x: number, y: number, turn: number): P2;

ViewBox type camera

a view box, in the drawing's units at the camera's turn: x, y, w, h

type ViewBox = [number, number, number, number];

viewOf function camera

what is on the stage

function viewOf(c: Camera, stage: Stage): ViewBox;

zoomAt function camera

closer by f, or round by a quarter's part, with what is at that stage point (on the floor) staying under it

function zoomAt(c: Camera, stage: Stage, f: number, px?: number, py?: number): Camera;

depthSort function depth

the order to draw them in, the furthest first; at a camera's turn, too (camera.ts), where it is the order of the turn's nearest quarter

function depthSort<T extends Drawable>(list: T[], turn?: number): T[];

Drawable interface depth

interface Drawable {
    box: Box;
    key?: number;
}

Diag interface errors

interface Diag {
    severity: Severity;
    message: string;
    /** 1-based; 0 when the place is unknown */
    line: number;
    col: number;
    /** the JSON path in the document, for tools and tests, e.g. /scenes/0/nodes/2/asset */
    path: string;
    hint?: string;
    /** another file the place is in (a defaults or override file), with its text for the excerpt */
    file?: string;
    source?: string;
}

DiagError class errors

class DiagError extends Error {
    diags: Diag[];
    constructor(diags: Diag[]);
}

didYouMean function errors

The closest candidate, if it is close enough to be a likely typo.

function didYouMean(word: string, candidates: Iterable<string>): string | undefined;

distance function errors

Edit distance where swapping two neighbouring letters counts as one edit (optimal string alignment).

function distance(a: string, b: string): number;

formatDiag function errors

function formatDiag(d: Diag, file: string, source?: string): string;

formatDiags function errors

function formatDiags(diags: Diag[], file: string, source?: string): string;

Severity type errors

type Severity = 'error' | 'warning';

bubble function glyphs

Chat bubble on the top face: a frame with two lines of text (chat servers).

function bubble(k: Kernel, b: Box): string;

envelope function glyphs

Envelope on the top face (a mailbox, an inbox).

function envelope(k: Kernel, b: Box): string;

FacePainter type glyphs

what a screen shows, drawn in its own 2D plane; a host adds its own by name (iso-objects' registerMarks)

type FacePainter = (w: number, h: number) => string;

fileLines function glyphs

Two lines of text on the top face (files, records).

function fileLines(k: Kernel, b: Box): string;

keyGlyph function glyphs

A key glyph on the top face: a bow and a bit.

function keyGlyph(k: Kernel, b: Box): string;

placeholderFace function glyphs

a face the drawing names but nothing has registered: a dashed frame with a question mark, so the gap shows

function placeholderFace(w: number, h: number): string;

screenFaces const glyphs

const screenFaces: Record<string, FacePainter>;

screenGlass function glyphs

function screenGlass(w: number, h: number): string;

socketGlyph function glyphs

A socket: a round opening on the top face.

function socketGlyph(k: Kernel, b: Box): string;

termLines function glyphs

"terminal lines" on the +y (front-left) face

function termLines(k: Kernel, b: Box, n: number): string;

apply const kernel

const apply: (m: Mat, x: number, y: number) => P2;

Attrs type kernel

type Attrs = Record<string, string | number | undefined | null | false>;

Bounds class kernel

class Bounds {
    x0: number;
    y0: number;
    x1: number;
    y1: number;
    add(p: P2): void;
    addRect(x: number, y: number, w: number, h: number): void;
    get empty(): boolean;
}

Box interface kernel

interface Box {
    x0: number;
    y0: number;
    z0: number;
    x1: number;
    y1: number;
    z1: number;
}

C const kernel

const C: number;

center const kernel

const center: (b: Box) => P3;

esc const kernel

const esc: (s: string) => string;

Face type kernel

type Face = 'top' | 'left' | 'right';

faceFrame function kernel

A face's own 2D plane, in pixels: u to the right, v down, origin at the face's top-left corner as seen. left = the +y face (front-left), right = the +x face (front-right), top = the z1 face (u along +x, v along +y).

function faceFrame(b: Box, face: Face): {
    m: Mat;
    w: number;
    h: number;
};

Font interface kernel

interface Font {
    key: FontKey;
    size: number;
    spacing?: number;
}

FontKey type kernel

type FontKey = keyof typeof metrics;

FONTS const kernel

the fonts of the reference CSS classes; metrics are measured at these exact sizes (scripts/measure-fonts.mjs)

const FONTS: {
    lbl: {
        key: "sans700_13";
        size: number;
    };
    sub: {
        key: "mono400_11";
        size: number;
    };
    slabname: {
        key: "sans800_15";
        size: number;
    …
};

iso const kernel

const iso: (x: number, y: number, z?: number) => P2;

Kernel class kernel

One per scene: collects bounds (and text rectangles for layout checks) while assets draw.

class Kernel {
    bounds: Bounds;
    texts: TextRect[];
    /** screen bounds of text drawn in a skewed plane (floor, faces), for label placement */
    planes: {
        x: number;
        y: number;
        w: number;
        h: number;
    }[];
    /** the same, as the actual parallelograms */
    planePolys: P2[][];
    …
}

Mat type kernel

[a b c d e f] as in SVG matrix(): x' = a x + c y + e, y' = b x + d y + f

type Mat = [number, number, number, number, number, number];

matStr const kernel

const matStr: (m: Mat) => string;

n1 const kernel

const n1: (v: number) => string;

P2 type kernel

type P2 = [number, number];

P3 type kernel

type P3 = [number, number, number];

pt const kernel

const pt: (p: P2) => string;

S const kernel

pixels per grid unit, as in the references

const S = 34;

tag function kernel

function tag(name: string, attrs?: Attrs, inner?: string): string;

TextRect interface kernel

interface TextRect {
    x: number;
    y: number;
    w: number;
    h: number;
    text: string;
    owner?: string;
}

textWidth function kernel

function textWidth(str: string, f: Font): number;

withFont function kernel

runs fn (now: it may not wait for anything) with its text measured as that font's

function withFont<T>(f: FontTable | undefined, fn: () => T): T;

contrast function mono

WCAG 2.1 contrast ratio between two colours (1 to 21).

function contrast(a: string, b: string): number;

greyOf function mono

CIE lightness L* (0 to 100) of a #rgb, #rrggbb or hsl(h s% l%) colour.

function greyOf(color: string): number;

MONO const mono

const MONO: {
    light: {
        paper: string;
        ink: string;
        steps: readonly [MonoFace, MonoFace, MonoFace, MonoFace];
    };
    dark: {
        paper: string;
        ink: string;
        steps: readonly [MonoFace, MonoFace, MonoFace, MonoFace];
    };
    patterns: readonly MonoPattern[];
    …
};

MonoLook interface mono

interface MonoLook {
    mode: 'light' | 'dark';
    paper: string;
    ink: string;
    roles: Record<string, MonoRoleLook>;
    kinds: Record<string, MonoRhythm>;
    warnings: string[];
}

monoOf function mono

Map a theme's roles and kinds into deterministic monochrome steps, patterns and line rhythms.

function monoOf(theme: Theme, mode: 'light' | 'dark', use?: {
    roles?: string[];
    kinds?: string[];
}, own?: MonoTable): MonoLook;

MonoPattern type mono

type MonoPattern = 'none' | 'hatch' | 'hatch-wide' | 'dots';

MonoTable interface mono

interface MonoTable {
    roles?: Record<string, {
        step?: MonoStep;
        pattern?: MonoPattern;
    }>;
    kinds?: Record<string, {
        dash?: number[];
        width?: number;
    }>;
}

parse function parse

function parse(source: string): Parsed;

Parsed interface parse

interface Parsed {
    data: unknown;
    /** line/col (1-based) of the value at a JSON path; `key: true` gives the key's place in its map instead */
    locate(path: string, opts?: {
        key?: boolean;
    }): {
        line: number;
        col: number;
    };
    /** the lines (1-based, inclusive) the value at a JSON path spans in the source; undefined if not found */
    span(path: string): {
        start: number;
    …
}

createHash function shims/crypto

function createHash(alg: string): {
    update(s: string): /*elided*/ any;
    digest(_enc: 'hex'): string;
};

sha256Hex function shims/crypto

function sha256Hex(text: string): string;

allowed function svg-dom

may this attribute be set, with this value?

function allowed(name: string, value: string): boolean;

buildSvg function svg-dom

Make the drawing: the tree's first element (an <svg>), as DOM.

function buildSvg(markup: string, d?: Document): SVGSVGElement;

parseSvg function svg-dom

Read the renderer's SVG text into a tree of allowed elements (their attributes filtered, their texts unescaped). A disallowed element is dropped with everything inside it; comments are dropped; anything that isn't the renderer's well-formed output (an unclosed tag, a stray close) throws, so a broken drawing is never half-built.

function parseSvg(markup: string): SvgNode;

SvgNode interface svg-dom

interface SvgNode {
    name: string;
    attrs: [string, string][];
    children: (SvgNode | string)[];
}

colorRef function theme

A colour value usable in CSS: a theme token name or a literal colour.

function colorRef(t: Theme, c: string): string;

extendTheme function theme

The theme with a file's own roles and kinds added.

function extendTheme(t: Theme, roles?: Record<string, RawRole>, kinds?: Record<string, RawKind>): Theme;

loadTheme function theme

function loadTheme(text: string): Theme;

RawKind interface theme

a route kind's look: its colour (or a role's, by like:), its dash and its legend

interface RawKind {
    legend?: string;
    like?: string;
    color?: string;
    dash?: 'solid' | 'dashed' | 'dotted';
}

RawRole interface theme

a colour role: a hue and saturation the theme's shades are made from

interface RawRole {
    h: number;
    s: number;
    top?: string;
    tint?: number;
}

Theme interface theme

a theme: CSS tokens for light and dark, and the route kinds and colour roles drawings name

interface Theme {
    name: string;
    light: Record<string, string>;
    dark: Record<string, string>;
    /** ants: the dash its connectors march with, where it isn't its dash's own */
    kinds: Record<string, {
        color: string;
        dash: 'solid' | 'dashed' | 'dotted';
        legend: string;
        ants?: [number, number];
    }>;
    roles: Record<string, RawRole>;
}

themeCss function theme

function themeCss(t: Theme): string;

themeParts function theme

The theme's CSS in pieces: the light and dark tokens (declarations), and the rules for its roles and kinds.

function themeParts(t: Theme): {
    light: string;
    dark: string;
    rest: string;
};

serialize function vdom

a tree as SVG text (every value escaped; raw text only where the caller says, for its own <style>)

function serialize(n: VNode | string, raw?: Set<string>): string;

vdoc const vdom

a stand-in for document, as far as the painters go

const vdoc: {
    createElementNS: (_ns: string, name: string) => VEl;
};

VEl class vdom

class VEl implements VNode {
    name: string;
    attrs: [string, string][];
    children: (VNode | string)[];
    /** style properties as set (fontSize, transformOrigin…), written out as one style attribute */
    style: Record<string, string>;
    constructor(name: string);
    setAttribute(k: string, v: string): void;
    getAttribute(k: string): string | null;
    append(...ns: (VEl | string)[]): void;
    set textContent(t: string);
    get textContent(): string;
    …
}

VNode interface vdom

interface VNode {
    name: string;
    attrs: [string, string][];
    children: (VNode | string)[];
}

objects src/iso-objects

import { objects } from '@johnoscott/isometric-engine/render';   // also in /editor and /systems
import { … } from '@johnoscott/isometric-engine/modules/iso-objects/MODULE';

ANT_DASH const ants

const ANT_DASH: Record<string, [number, number]>;

ANT_SPEED const ants

const ANT_SPEED: number;

ANT_STILL const ants

const ANT_STILL: string[];

antDash function ants

the dash a connector marches with, or undefined when it stands still

function antDash(kind: string, o?: Pick<AntsOptions, 'dash' | 'kinds' | 'still'>): [number, number] | undefined;

ANTS_CSS const ants

for 'css': one rule and its keyframes. A page stops them, where they are, with --ants: paused.

const ANTS_CSS = "\n.flow.iso-ants{stroke-dasharray:var(--ant-on) var(--ant-off);animation:iso-ants var(--ant-turn) linear infinite;animation-play-state:var(--ants,running)}\n@keyframes iso-ants{to{stroke-dashoffset:var(--ant-to)}}\n";

antsOf function ants

what a scene's ants: in the file asks for, as options; undefined: none

function antsOf(raw: {
    ants?: boolean | string[] | {
        ids?: string[];
        speed?: number;
        dash?: [number, number];
    };
} | undefined): Pick<AntsOptions, 'ids' | 'speed' | 'dash'> | undefined;

AntsOptions interface ants

interface AntsOptions {
    /** how it moves (default: smil); 'none': the dashes, standing still */
    by?: 'css' | 'smil' | 'none';
    /** the connectors that march (default: every one that may) */
    ids?: string[];
    /** units a second, in the drawing's units (default: 32 in 1.1 s) */
    speed?: number;
    dash?: [number, number];
    /** the connectors' dashes, by kind: the theme's `kinds` (a dashed kind marches with its own dash) */
    kinds?: Record<string, {
        dash?: 'solid' | 'dashed' | 'dotted';
        ants?: [number, number];
    …
}

withAnts function ants

The scene's still, as SVG text, with its connectors marching.

function withAnts(scene: Pick<CompiledScene, 'rendered' | 'routes'>, o?: AntsOptions): string;

assembly function assemble

function assembly(layout: Layout, routes: Routed[], vb: [number, number, number, number]): Assembly;

Assembly interface assemble

interface Assembly {
    pieces: Piece[];
    routes: {
        id: string;
        delay: number;
        dur: number;
    }[];
    labels: {
        delay: number;
        dur: number;
    };
    /** ms until everything is in place */
    total: number;
}

Edge type assemble

type Edge = 'left' | 'right' | 'top' | 'bottom';

offscreen function assemble

The edge of the canvas nearest a box, and the offset that puts the box fully outside the canvas beyond it.

function offscreen(b: Rect, vb: [number, number, number, number]): {
    edge: Edge;
    dx: number;
    dy: number;
};

Piece interface assemble

interface Piece {
    id: string;
    kind: 'region' | 'node';
    edge: Edge;
    dx: number;
    dy: number;
    delay: number;
    dur: number;
    bbox: Rect;
}

boxAsset function assets

A plain box, with decorations: the workhorse.

function boxAsset(name: string, description: string, size: [number, number, number], role: string, deco?: RawDeco[], extra?: (k: Kernel, b: Box) => string): NodeAsset;

cloudPath function assets

A puffy cloud outline in a face's 2D plane (w × h px), drawn clockwise with outward bumps.

function cloudPath(w: number, h: number): string;

defaultLabel function assets

function defaultLabel(b: Box, hasSub: boolean): LabelSpot;

drawCloud function assets

A cloud lying on the floor with a little thickness: the side is the outline dropped by the height.

function drawCloud(k: Kernel, b: Box): string;

drawDecos function assets

function drawDecos(k: Kernel, b: Box, decos: RawDeco[] | undefined): string;

facePainter const assets

const facePainter: (name: string) => D.FacePainter | undefined;

iconPainter const assets

const iconPainter: (name: string) => IconPainter | undefined;

IconPainter type assets

an icon a node can wear (deco: icon: NAME), painted on its box

type IconPainter = (k: Kernel, b: Box) => string;

LabelSpot interface assets

interface LabelSpot {
    /** screen pixels: where the label's first line's baseline sits */
    x: number;
    y: number;
    anchor: 'start' | 'middle' | 'end';
}

markCss const assets

the registered marks' styles

const markCss: () => string;

NodeAsset interface assets

interface NodeAsset {
    name: string;
    description: string;
    /** default w (x), d (y), h (z) in grid units */
    size: [number, number, number];
    role: string;
    deco?: RawDeco[];
    /** SVG for the inside of the node's <g class="blk k-ROLE">; b is the node's box */
    draw(k: Kernel, b: Box, n: RawNode): string;
    /** where the label goes; default: centred above the top */
    label?(b: Box, n: RawNode, hasSub: boolean): LabelSpot;
    /** [x, y, z, r]: centre and radius (px) of the step pulse ring; default from the footprint */
    …
}

placeholderIcon function assets

an icon the drawing names but nothing has registered: a dashed square with a question mark on the top face

function placeholderIcon(k: Kernel, b: Box): string;

plate function assets

The plate figures stand on: 1.5 × 1.5, 0.18 high, centred in the box.

function plate(b: Box): Box;

registerMarks function assets

css: the marks' styles; drawingCss() includes them from then on

function registerMarks(marks: {
    icons?: Record<string, IconPainter>;
    faces?: Record<string, D.FacePainter>;
    css?: string;
}): void;

bindAnts function bind-ants

A drawing whose own file asks for ants, and that has nothing to play: a Timeline of no length, whose connectors march on the ambient clock. None when the file doesn't ask.

function bindAnts(drawing: CompiledScene | MotionSource, opts?: BindOptions): Timeline | undefined;

BOARD_3D const board

the 3D board's sizes, in grid units: a card's footprint and height, the gaps, a panel's margin, the channel

const BOARD_3D: {
    W: number;
    D: number;
    H: number;
    GX: number;
    GY: number;
    PAD: number;
    CH: number;
    PANEL_H: number;
};

BOARD_CSS const board

the text on a 3D card's front face

const BOARD_CSS = "\n.blk .card-name{font-size:13px;font-weight:600;fill:var(--ink)}\n.blk .card-sub{font-size:10px;fill:var(--ink);opacity:.75}\n.blk.ghost .card-name,.blk.ghost .card-sub{fill:var(--muted)}\n";

boardCatalog function board

the catalogue a board is drawn with in 3D: a panel (a thin slab, its name on its floor) and a card showing the board's text

function boardCatalog(board: Board): KindCatalog;

boardDiagram function board

a board as an engine drawing (one scene): panels as regions, nested as they hold each other, cards as nodes, links as routes (kinds and roles: the drawing's own, as a document's kinds: and roles:)

function boardDiagram(board: Board, opts?: {
    title?: string;
    kinds?: Record<string, RawKind>;
    roles?: Record<string, RawRole>;
}): RawDiagram;

boardOf function board

the board of a laid-out scene; visible: only what it says is shown (e.g. a step's visible set)

function boardOf(scene: CompiledScene, visible?: (id: string) => boolean): Required<Board>;

cardAsset function board

a card: a slab with its name (and sub) on its front face. The text is the board's (text), not the node's label: a node with a label gets the scene's upright label above it as well

function cardAsset(text: (id: string) => {
    label: string;
    sub?: string;
} | undefined): NodeAsset;

Compiled interface compile

interface Compiled {
    ok: boolean;
    /** the parsed source: positions and spans of every value, for the proof sheet */
    parsed?: Parsed;
    source?: string;
    diags: Diag[];
    doc?: RawDiagram;
    theme?: Theme;
    /** the kinds it was drawn with (a page's legend and stylesheet ask them) */
    catalog: KindCatalog;
    scenes: CompiledScene[];
}

CompiledScene interface compile

interface CompiledScene {
    id: string;
    raw: RawDiagram['scenes'][number];
    layout: Layout;
    routes: Routed[];
    steps: Steps;
    rendered: RenderedScene;
    grid: GridDef;
    assemble: boolean;
    /** the file's `motion:` on this scene, checked against the drawing (a file with errors in it has none) */
    motion?: MotionDoc;
}

compileRaw function compile

function compileRaw(doc: RawDiagram, themeText: string, catalog: KindCatalog, parsed?: Parsed, source?: string, opts?: {
    snap?: number;
}, diags?: Diag[]): Compiled;

noSource const compile

Places for a document that has no source text: every place is unknown (line 0).

const noSource: (data: unknown) => Parsed;

baseCss const css

a page's stylesheet: the page's own rules and the drawing's

const baseCss: (cat: KindCatalog) => string;

drawingCss const css

the drawing's styles for a catalogue, with the marks a host has registered so far (registerMarks)

const drawingCss: (cat: KindCatalog) => string;

GRID_CSS const css

The floor grid and the assemble intro, in the SVG.

const GRID_CSS = "\n.grid{display:none;fill:none;stroke:var(--ink);stroke-width:.6;opacity:.16;pointer-events:none}\nsvg.show-grid .grid{display:inline}\nsvg.pre-assemble > g:not(.g-anim){opacity:0}\n";
export declare const PLAYER_CSS: string;

MARKS_CSS const css

Step marks and step focus, drawn in the SVG (the page, and the editor's canvas).

const MARKS_CSS = "\n/* step marks */\n.xm circle{fill:var(--surface);stroke:var(--blocked);stroke-width:2.5}\n.xm path{stroke:var(--blocked);stroke-width:3;stroke-linecap:round}\n.say rect{fill:var(--surface);stroke-width:1.5}\n.say text{font-size:12px;font-weight:600}\n.badge{cursor:pointer}\n.badge circle{fill:var(--c);stroke:var(--surface);stroke-width:2.5}\n.badge text{font-size:11.5px;font-weight:800;fill:var(--on);text-anchor:middle;dominant-baseline:central;pointer-events:none}\n.tok{stroke:var(--surface);stroke-width:2.5}\n.pulse{fill:none;stroke-width:2.5;transform-box:fill-box;transform-origin:center;animation:pulse 1.5s ease-out infinite}\n@keyframes pulse{from{transform:scale(.35);opacity:.95}to{transform:scale(1.5);opacity:0}}\n.sub{stroke-width:5px}\n\n/* step focus: what a step does not touch dims;

PAGE_CSS const css

The page around a figure (the standalone page only).

const PAGE_CSS = "\n*{box-sizing:border-box}\nhtml,body{margin:0}\nbody{background:var(--bg);color:var(--ink);font:15px/1.55 system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif;-webkit-font-smoothing:antialiased;overflow-x:hidden}\ncode,pre,.mono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}\ncode{font-size:.92em;background:var(--code-bg);padding:1px 5px;border-radius:5px;overflow-wrap:anywhere}\n.wrap{max-width:1180px;margin:0 auto;padding:32px 16px 64px}\nheader.page{display:flex;flex-wrap:wrap;gap:12px 24px;align-items:flex-end;justify-content:space-between;margin-bottom:8px}\nh1{font-size:clamp(24px,4vw,34px);line-height:1.15;margin:0;letter-spacing:-.01em}\n.lede{color:var(--muted);max-width:76ch;margin:8px 0 0}\n.pills{display:flex;gap:8px;align-items:center;flex-wrap:wrap}\n.pill{display:inline-block;font-size:12px;font-weight:600;padding:3px 10px;border-radius:99px;border:1px solid var(--line);color:var(--muted);background:var(--surface)}\n.theme{font:inherit;font-size:12px;border:1px solid var(--line);background:var(--surface);color:var(--muted);border-radius:99px;padding:3px 10px;cursor:pointer}\nh2{font-size:20px;margin:44px 0 4px;letter-spacing:-.005em;text-wrap:balance}\n.sec-sub{color:var(--muted);margin:0 0 14px;font-size:14px;max-width:84ch}\n.figure{background:var(--surface);border:1px solid var(--line);border-radius:16px;margin:12px 0 10px;overflow:hidden}\n.scroller{overflow-x:auto;-webkit-overflow-scrolling:touch}\n.scroller svg{display:block;width:100%;min-width:720px;height:auto}\n.legend{display:flex;flex-wrap:wrap;gap:6px 18px;padding:10px 18px;border-top:1px solid var(--line);font-size:12.5px;color:var(--muted)}\n.legend:empty{display:none}\n.legend span{display:inline-flex;align-items:center;gap:8px}\n.legend i{display:inline-block;width:26px;height:0;border-top:3px solid}\n.legend i.box{height:10px;border-width:1.5px;border-style:solid;border-radius:2px}\nfooter{margin-top:40px;font-size:12.5px;color:var(--muted)}\n";

PLAYER_UI_CSS const css

The player's controls (the page only).

const PLAYER_UI_CSS = "\n/* player */\n.player{display:flex;align-items:flex-start;gap:10px 14px;padding:12px 16px;border-top:1px solid var(--line);flex-wrap:wrap}\n.ctrls{display:flex;gap:6px;flex:none}\n.pbtn{font:inherit;font-size:13px;font-weight:700;display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);background:var(--bg);color:var(--ink);border-radius:99px;padding:6px 14px;cursor:pointer}\n.pbtn.icon{padding:6px 11px}\n.pbtn:hover{border-color:var(--muted)}\n.pbtn:disabled{opacity:.6;cursor:default}\n.pbtn.primary{background:var(--ink);color:var(--surface);border-color:var(--ink);min-width:92px;justify-content:center}\n.pbtn:focus-visible,.dot:focus-visible,.badge:focus-visible{outline:2px solid var(--send);outline-offset:2px}\n.cap{flex:1 1 360px;min-width:0}\n.cap-h{font-size:14.5px;font-weight:700;display:flex;align-items:center;gap:8px}\n.cap-h .cnt{margin-left:auto;font-weight:500;color:var(--muted);font-size:12px;white-space:nowrap}\n.num{flex:none;display:inline-grid;place-items:center;width:22px;height:22px;border-radius:50%;background:var(--c,var(--control));color:var(--on);font-size:11px;font-weight:800}\n.cap-t{font-size:13.5px;color:var(--ink);margin:4px 0 0;max-width:92ch;min-height:3.1em}\n.cap-c{margin:8px 0 0;background:var(--code-bg);border-radius:8px;padding:7px 10px;font-size:12px;line-height:1.5;white-space:pre-wrap;overflow-wrap:anywhere;max-height:9.5em;overflow-y:auto;color:var(--ink)}\n.cap-c:empty{display:none}\n.prog{height:3px;background:var(--line);border-radius:3px;overflow:hidden;margin-top:9px}\n.prog i{display:block;height:100%;width:0;background:var(--c,var(--ink))}\n.dots{display:flex;gap:5px;flex-wrap:wrap;flex-basis:100%;padding-left:2px;order:4}\n.dot{width:10px;height:10px;border-radius:50%;background:var(--line);border:0;padding:0;cursor:pointer}\n.dot.on{background:var(--ink)} .dot.done{background:var(--muted)}\ndetails.steps{margin:0 0 8px;font-size:13.5px}\ndetails.steps summary{cursor:pointer;color:var(--muted);font-size:13px}\ndetails.steps ol{margin:8px 0 0;padding-left:22px;max-width:92ch}\ndetails.steps li{margin:6px 0}\ndetails.steps li code{font-size:11.5px}\n@media (prefers-reduced-motion:reduce){.pulse{animation:none;opacity:.8}}\n@media (max-width:560px){.cap{flex-basis:100%}}\n.still .pulse{animation:none;opacity:.85}\n.still *,.still *::before{transition:none!important}\n.still .prog{display:none}\n.still .ctrls,.still .tools{display:none}\n.tools{display:flex;gap:6px;flex:none;order:3;margin-left:auto}\n.pbtn.small{font-size:12px;padding:4px 11px;font-weight:600;color:var(--muted)}\n.pbtn.small[aria-pressed=\"true\"]{color:var(--ink);border-color:var(--muted);background:var(--surface)}";

DiffOptions interface diff

interface DiffOptions {
    as?: Record<string, string>;
}

diffScenes function diff

function diffScenes(a: CompiledScene, b: CompiledScene, o?: DiffOptions): SceneDiff;

RouteChange interface diff

interface RouteChange {
    id: string;
    was?: string;
    fields: RouteField[];
}

RouteField type diff

type RouteField = 'ends' | 'label' | 'kind' | 'arrow' | 'path';

SceneDiff interface diff

interface SceneDiff {
    added: {
        things: string[];
        routes: string[];
        notes: string[];
    };
    removed: {
        things: string[];
        routes: string[];
        notes: string[];
    };
    /** in both, and not the same: moved (`by`), or other fields changed, or both */
    …
}

ThingChange interface diff

interface ThingChange {
    id: string; /** in the first, where it was renamed */
    was?: string;
    type: 'region' | 'node';
    /** the drawing's units, at turn 0: from where it is in the first to where it is in the second (of the picture's box's middle) */
    by?: [number, number];
    fields: ThingField[];
}

ThingField type diff

type ThingField = 'label' | 'sub' | 'role' | 'look' | 'parent' | 'size';

ChangeSaid interface diff-compare

one thing that changed, in names a reader knows it by

interface ChangeSaid {
    kind: DiffKind;
    what: 'thing' | 'connector' | 'note';
    name: string; /** what it was called, where that changed */
    was?: string;
}

CompareOptions interface diff-compare

interface CompareOptions extends DiffLookOptions {
    duration?: number;
}

compareScenes function diff-compare

The first drawing, the second with its marks, and how to go from one to the other.

function compareScenes(a: CompiledScene, b: CompiledScene, o?: CompareOptions): Comparison;

CompareState interface diff-compare

undefined: not drawn

interface CompareState {
    before: SceneState | undefined;
    after: SceneState | undefined; /** how much of the second there is, 0 to 1 */
    fade: number;
}

Comparison interface diff-compare

interface Comparison {
    /** what is marked, in words: things, then connectors, then notes */
    changes: ChangeSaid[];
    id: string;
    diff: SceneDiff;
    legend: DiffLegend[];
    viewBox: [number, number, number, number];
    duration: number;
    /** the two drawings, on one view, their ids their own: each is drawn in its state, the second over the first */
    before: {
        id: string;
        rendered: RenderedScene;
    …
}

DiffDrawing interface diff-look

interface DiffDrawing {
    id: string;
    diff: SceneDiff;
    rendered: RenderedScene;
    /** what each mark in it means, for a host to draw: a row for each kind there is */
    legend: DiffLegend[];
}

DiffKind type diff-look

type DiffKind = 'added' | 'changed' | 'moved' | 'removed';

DiffLegend interface diff-look

interface DiffLegend {
    kind: DiffKind;
    words: string;
    color: string;
    dash?: string;
    opacity?: number;
}

DiffLookOptions interface diff-look

interface DiffLookOptions extends DiffOptions {
    ghosts?: boolean; /** what its ids begin with (see the head): a letter, then letters, digits, - and _; it throws for another */
    id?: string;
}

drawDiff function diff-look

The second drawing, with what changed since the first marked in it.

function drawDiff(a: CompiledScene, b: CompiledScene, o?: DiffLookOptions): DiffDrawing;

CONSTRAIN_LINES const drag-keys

The eight lines ⇧ keeps a move on, on the grid: x, y and the two diagonals, each way (unit-free directions)

const CONSTRAIN_LINES: readonly (readonly [number, number])[];

constrainMove function drag-keys

A grid move (dx, dy) from where a thing started, kept on the nearest of the eight lines: its projection on that line, and which line it is (for the dotted guide). On a diagonal the two parts are equal (or opposite); the canvas moves from the start on the grid by whole steps along it, so each place it takes is on the line.

function constrainMove(d: readonly [number, number]): {
    d: [number, number];
    line: [number, number];
};

dragStep const drag-keys

The step a drag snaps to: half cells while Ctrl is held (it was ⌥ before 0.31.0: ⌥ now starts a copy)

const dragStep: (e: {
    ctrlKey: boolean;
}) => number;

Board interface flat

the scene description both views are drawn from

interface Board {
    cards: BoardCard[];
    panels?: BoardPanel[];
    links?: BoardLink[];
}

BoardCard interface flat

a card: one thing, at a cell of the grid ([column, row])

interface BoardCard {
    id: string;
    label: string;
    sub?: string;
    role?: string;
    ghost?: boolean;
    cell: [number, number];
}

boardErrors function flat

what is wrong with a board, as messages; layoutFlat refuses a board with any

function boardErrors(board: Board): string[];

BoardLink interface flat

a link between two cards or panels; aOn / bOn: draw that end to a panel (one holding it, or any) instead

interface BoardLink {
    id?: string;
    a: string;
    b: string;
    kind?: string;
    label?: string;
    aOn?: string;
    bOn?: string;
}

BoardPanel interface flat

a panel: a container over a range of cells, [c0, r0, c1, r1] inclusive; panels nest by containment

interface BoardPanel {
    id: string;
    label?: string;
    sub?: string;
    role?: string;
    cells: [number, number, number, number];
}

FLAT_DEFAULTS const flat

const FLAT_DEFAULTS: Readonly<FlatOptions>;

FLAT_FONTS const flat

the 2D view's fonts (its stylesheet's: src/iso-viewer/flat-view.ts), as L0's measured metrics have them

const FLAT_FONTS: Record<FlatFont, Font>;

FlatCard interface flat

interface FlatCard extends BoardCard {
    rect: FlatRect;
}

FlatFont type flat

the fonts a 2D layout measures: a card's name and sub, a panel's title and its subtitle, a link's label

type FlatFont = 'name' | 'sub' | 'title' | 'titleSub' | 'label';

flatHit function flat

which card or panel a point is on (topmost: a card, then the innermost panel)

function flatHit(L: FlatLayout, x: number, y: number): string | undefined;

FlatLabel interface flat

interface FlatLabel {
    x: number;
    y: number;
    anchor: 'start' | 'middle' | 'end';
    box: FlatRect;
    text: string;
}

FlatLayout interface flat

interface FlatLayout {
    cards: FlatCard[];
    panels: FlatPanel[];
    links: FlatLink[];
    /** everything drawn, with the margin */
    bounds: FlatRect;
    options: FlatOptions;
    /** warnings: a link with no clear route (drawn the least bad way) */
    warnings: string[];
}

FlatLink interface flat

interface FlatLink extends BoardLink {
    id: string;
    points: FlatPoint[];
    at?: FlatLabel;
    routed: boolean;
}

FlatOptions interface flat

interface FlatOptions {
    W: number;
    H: number;
    GX: number;
    GY: number;
    PAD: number;
    TITLE: number;
    CH: number;
    /** card and panel corner radii */
    cardRx: number;
    panelRx: number;
    /** the cost model */
    …
}

FlatPanel interface flat

interface FlatPanel extends BoardPanel {
    rect: FlatRect;
    /** the title strip's box (what a link may not cross) */
    title: FlatRect;
    /** the title's baseline */
    titleAt: FlatPoint;
    /** the panel it sits in, if any */
    parent?: string;
    depth: number;
}

FlatPoint type flat

type FlatPoint = [number, number];

FlatRect interface flat

interface FlatRect {
    l: number;
    t: number;
    r: number;
    b: number;
}

layoutFlat function flat

the 2D layout of a board. Throws on a board with errors (boardErrors).

function layoutFlat(board: Board, measure: Measure, opts?: Partial<FlatOptions>): FlatLayout;

Measure type flat

type Measure = (text: string, font: FlatFont) => number;

metricsMeasure const flat

text measured with L0's font metrics: the same in Node and every browser (stills and tests); a page measures its rendered text instead (flat-view.ts: measureIn)

const metricsMeasure: Measure;

placeBoard function flat

where a board's cards and panels go on a grid with the given sizes and gaps (the 2D layout's, in px; the 3D drawing's, in grid units): each card's top-left corner, each panel's rect, and how the panels nest

function placeBoard(board: Board, o: Pick<FlatOptions, 'W' | 'H' | 'GX' | 'GY' | 'PAD' | 'TITLE' | 'CH'>): {
    prect: FlatRect[];
    parentIx: number[];
    depthOf: (i: number) => number;
    pos: (i: number, j: number) => FlatPoint;
    cardAt: (i: number) => FlatPoint;
};

focusView function focus

function focusView(full: number[], box: [number, number, number, number] | undefined): number[];

boxSilhouette function geometry

The outline a box makes on screen: the convex hull of its eight projected corners (a hexagon, seen from above).

function boxSilhouette(b: Box3): [number, number][];

floorOf function geometry

A region's floor: its footprint at the height it stands on, projected (a parallelogram).

function floorOf(b: Box3): [number, number][];

GROW_REACH const geometry

A drag of (dx, dy) grid units, from start (at: in the parent's frame), to a position snapped to step (1: whole cells; 0.5: half cells), then clamped so the item's footprint size stays inside its parent's inner area (parent: its size, pad: its margin). With no parent (the scene), nothing clamps. (0.28.0) parent.grow: a side that grows (a group that fits what it holds, dragged past its right or front edge) isn't held at its edge, only kept within GROW_REACH cells of the furthest the thing has been on that side (reach, its position there; the edge, if it has been no further): no runaway from a fling.

const GROW_REACH = 2;

localAt function geometry

Where an element sits in its parent's frame (what at: means), in grid units.

function localAt(sc: CompiledScene, id: string): [number, number] | undefined;

Move interface geometry

interface Move {
    /** the new at: in the parent's frame */
    at: [number, number];
    /** the grid move actually made (after snapping and clamping) */
    delta: [number, number];
    /** which edges of the parent stopped it */
    clamped: {
        left: boolean;
        right: boolean;
        top: boolean;
        bottom: boolean;
    };
}

overlaps function geometry

Does a footprint overlap any of these (sharing an edge isn't overlapping)?

function overlaps(a: {
    x0: number;
    y0: number;
    x1: number;
    y1: number;
}, others: {
    x0: number;
    y0: number;
    x1: number;
    y1: number;
}[]): boolean;

paddingOf const geometry

a region's inner margin: its own, else its kind's (as place.ts pads it); 0 for a kind the catalogue doesn't have

const paddingOf: (cat: KindCatalog, region: {
    kind?: string;
    padding?: number;
} | undefined) => number;

screenToGrid function geometry

A move on screen (SVG units) as a move on the floor (grid units): the inverse of the iso projection at one height.

function screenToGrid(dx: number, dy: number): [number, number];

snapMove function geometry

function snapMove(start: [number, number], d: [number, number], step: number, size: [number, number], parent?: {
    w: number;
    d: number;
    pad: number;
    grow?: {
        right?: boolean;
        front?: boolean;
        left?: boolean;
        back?: boolean;
        reach?: [number, number];
        reachLo?: [number, number];
    };
}): Move;

KindCatalog interface kinds

interface KindCatalog {
    regions: Record<string, RegionKind>;
    nodes: Record<string, NodeAsset>;
    /** the node kind a node without one (or with an unknown one) is drawn as */
    defaultNode: string;
}

kindsCss const kinds

the kinds' CSS, in the catalogue's order

const kindsCss: (cat: KindCatalog) => string;

nodeKind const kinds

a node kind by name (none: the default); undefined for a name the catalogue doesn't have

const nodeKind: (cat: KindCatalog, name: string | undefined) => NodeAsset | undefined;

nodeKindOr const kinds

a node kind by name, or the default one

const nodeKindOr: (cat: KindCatalog, name: string | undefined) => NodeAsset;

regionKind const kinds

a region kind's data; undefined for a name the catalogue doesn't have

const regionKind: (cat: KindCatalog, name: string | undefined) => RegionKind | undefined;

RegionKind interface kinds

interface RegionKind {
    shape: RegionShape;
    /** inner margin, grid units */
    pad: number;
    /** [z0 offset below the floor it stands on, default height above it] */
    z: [number, number];
    /** children stand on its top, and routes find a floor on it */
    floor: boolean;
    /** the colour role it is drawn in, unless the region says its own */
    role: string;
    /** where its name goes, unless the region says */
    labelStyle: 'face' | 'face-right' | 'floor' | 'none';
    …
}

RegionShape type kinds

How a region is drawn, and how it takes part in layout and routing.

type RegionShape = 
/** a thick base slab: a skirt below its floor (none on another slab), its name large on its front face */
'slab'
/** a plain block children stand on */
 | 'block'
/** a cloud lying on the floor, its name in the middle */
 | 'cloud'
/** a flat tint on the floor: overlays other things on purpose */
 | 'zone'
/** a cage of thin walls with a gate in one: routes go round its walls (or through its gate) */
 | 'walled'
/** a translucent tube over other things: overlays them on purpose */
 | 'tunnel';

wallHeight const kinds

a walled kind's default height: a gate's height follows it

const wallHeight: (cat: KindCatalog) => number;

calloutRect function labels

The rectangle of a callout pill whose text centre line is at y.

function calloutRect(w: number, x: number, y: number, anchor: 'start' | 'middle' | 'end'): Rect;

CalloutSpot interface labels

interface CalloutSpot {
    x: number;
    y: number;
    anchor: 'start' | 'middle' | 'end';
    rect: Rect;
}

convexOverlap function labels

Area of the intersection of two convex polygons (Sutherland–Hodgman, clipping a by each edge of b).

function convexOverlap(a: Poly, b: Poly): number;

inConvex function labels

function inConvex(poly: Poly, q: P2): boolean;

labelRect function labels

The rectangle a label block covers when its first baseline is at (x, y).

function labelRect(t: LabelText, x: number, y: number, anchor: 'start' | 'middle' | 'end'): Rect;

LabelText interface labels

interface LabelText {
    name?: string;
    sub?: string;
}

lineRectArea function labels

How much of a polyline (as 4px-wide strokes) falls inside a rectangle, in px².

function lineRectArea(pts: P2[], r: Rect): number;

Obstacles class labels

class Obstacles {
    polys: {
        poly: Poly;
        owner: string;
    }[];
    rects: {
        r: Rect;
        owner: string;
    }[];
    lines: {
        pts: P2[];
        owner: string;
    …
}

placeCallout function labels

Place a step's callout pill: where the author put it if that is clear, else around its anchor (above first), whichever covers least of the nodes, the labels and the step's other callouts. Callouts move; labels stay.

function placeCallout(w: number, ax: number, ay: number, preferred: {
    x: number;
    y: number;
    anchor: 'start' | 'middle' | 'end';
}, obs: Obstacles): CalloutSpot;

PlacedLabel interface labels

interface PlacedLabel {
    x: number;
    y: number;
    anchor: 'start' | 'middle' | 'end';
    rect: Rect;
}

placeNodeLabel function labels

Place a node's label. Spots, each with a penalty that says how natural it is: above the node clear of its top (the references' place), a little higher, beside it, then below. Each spot costs its penalty plus what it covers; route lines count little, since labels have a halo. The cheapest wins.

function placeNodeLabel(t: LabelText, box: Box, own: Poly, obs: Obstacles, owner: string, preferred?: {
    x: number;
    y: number;
    anchor: 'start' | 'middle' | 'end';
}): PlacedLabel;

Poly type labels

type Poly = P2[];

polyBounds function labels

function polyBounds(p: Poly): Rect;

polyRectArea function labels

Area of a convex polygon clipped to a rectangle (Sutherland–Hodgman).

function polyRectArea(poly: Poly, r: Rect): number;

Rect interface labels

interface Rect {
    x: number;
    y: number;
    w: number;
    h: number;
}

rectArea function labels

function rectArea(a: Rect, b: Rect): number;

silhouette function labels

The outline of a box as seen: six corners, clockwise from the back-top corner.

function silhouette(b: Box): Poly;

drawLooks function looks

Draw a scene's looks into its rendered (none declared: nothing).

function drawLooks(s: CompiledScene, theme: Theme): void;

monoCss function mono-paint

what is each role's and each kind's own: the faces' lightnesses, the connectors' rhythms

function monoCss(look: MonoLook): string;

monoOfDrawing function mono-paint

Everything a compile needs for the treatment: the look, its theme and its rules.

function monoOfDrawing(svg: string, theme: Theme, mode: ThemeMode, kinds: string[], own?: MonoTable): {
    look: MonoLook;
    theme: Theme;
    css: string;
};

monoTheme function mono-paint

the theme in greys, its tokens by the same names, so that everything that names one is grey too

function monoTheme(theme: Theme, look: MonoLook): Theme;

paintMono function mono-paint

The resolved drawing with its patterns, and no hue in it. id: the drawing's own (its patterns' ids begin with it).

function paintMono(svg: string, look: MonoLook, id: string): string;

usedIn function mono-paint

the roles and connector kinds a drawing uses

function usedIn(svg: string, theme: Theme, kinds: string[]): {
    roles: string[];
    kinds: string[];
};

alongPath function motion

a point a fraction of the way along an SVG polyline path ("M x,y L x,y …")

function alongPath(d: string, f: number): [number, number];

animatedSvg function motion

A timeline as one SVG that plays by itself: CSS keyframes inside it, sampled from the same states svgAt draws, so a page that shows the export and one that plays the timeline show the same thing at every sample. No script, no reference outside it; prefers-reduced-motion stops it at rest.

function animatedSvg(scene: Pick<CompiledScene, 'rendered' | 'id'>, tl: {
    duration: number;
    at(t: number, o?: {
        ambient?: number | 'off';
    }): SceneState;
}, o?: AnimatedSvgOptions): AnimatedSvg;

AnimatedSvg interface motion

interface AnimatedSvg {
    svg: string;
    /** ms, one pass */
    duration: number;
    /** what a timeline does that CSS here doesn't play, drawn as in the still instead: 'looks', 'typed', 'clips' */
    skipped: string[];
}

AnimatedSvgOptions interface motion

interface AnimatedSvgOptions {
    /** ms between samples (default 80: 12.5 a second); kept samples are only where something changes */
    step?: number;
    /** what shows with no animation (reduced motion, or a reader without CSS animation): 'still' (the drawing as drawn, the
     *  default), 'start', 'end', or a moment in ms */
    rest?: 'still' | 'start' | 'end' | number;
    /** loop (the default) or play once and stay at the end */
    loop?: boolean;
}

assemble const motion

the drawing arrives: frame(0) is empty, frame(duration) is the still render

const assemble: (s: CompiledScene, o?: AssembleOptions) => ScenePlan;

ASSEMBLE_STYLES const motion

const ASSEMBLE_STYLES: readonly ['edge', 'drop', 'rise', 'fly', 'pop', 'scatter', 'build', 'fade'];

AssembleOptions interface motion

interface AssembleOptions extends CommonOptions {
    style?: AssembleStyle;
}

AssembleStyle type motion

type AssembleStyle = typeof ASSEMBLE_STYLES[number];

Direction type motion

type Direction = 'left' | 'right' | 'top' | 'bottom';

disassemble const motion

the drawing leaves: frame(0) is the still render, frame(duration) is empty

const disassemble: (s: CompiledScene, o?: DisassembleOptions) => ScenePlan;

DISASSEMBLE_STYLES const motion

const DISASSEMBLE_STYLES: readonly ['explode', 'lift-off', 'sink', 'scatter', 'fly-out', 'collapse', 'fade', 'reverse'];

DisassembleOptions interface motion

interface DisassembleOptions extends CommonOptions {
    style?: DisassembleStyle;
    /** explode, collapse: the point (in the drawing's units), or a piece's id (default: the drawing's middle; collapse
     *  into the region that holds each piece: 'region') */
    point?: [number, number] | string;
    /** reverse: the assemble style it plays backwards */
    of?: AssembleStyle;
}

DisassembleStyle type motion

type DisassembleStyle = typeof DISASSEMBLE_STYLES[number];

introSvg const motion

A frame of the page's intro (the default assemble) at t ms, as SVG text.

const introSvg: (s: CompiledScene, t: number) => string;

ItemState interface motion

a thing's block, walls, gate and name: what is not given is as in the still

interface ItemState {
    opacity?: number;
    /** in the drawing's units */
    dx?: number;
    dy?: number;
    /** about `about` (default: the drawing's origin) */
    scale?: number;
    about?: [number, number];
    /** only what is inside this shows (a polygon, before the offset) */
    clip?: [number, number][];
}

LabelState interface motion

a label or a note: faded, or typed so far (0 to 1)

interface LabelState {
    opacity?: number;
    typed?: number;
    dx?: number;
    dy?: number;
}

MOTION_EASINGS const motion

const MOTION_EASINGS: readonly ['linear', 'ease', 'ease-in', 'ease-out', 'settle', 'spring', 'bounce'];

MOTION_ORDERS const motion

const MOTION_ORDERS: readonly ['by-depth', 'by-layer', 'by-region', 'by-flow', 'as-listed', 'random'];

MotionEasing type motion

type MotionEasing = typeof MOTION_EASINGS[number];

motionModel function motion

function motionModel(s: CompiledScene): MotionModel;

MotionModel interface motion

interface MotionModel {
    viewBox: [number, number, number, number];
    pieces: MotionPiece[];
    routes: {
        id: string;
        path: string;
        from?: string;
        to?: string;
    }[];
    /** notes' ids and what they are on (a piece or a route) */
    notes: Record<string, string | undefined>;
    /** the build-time intro's own timing (`edge` with no other timing given plays exactly it) */
    intro: Assembly;
}

motionOrder function motion

the order the pieces move in: what they stand on, or are in, never after them (but as-listed and random)

function motionOrder(m: MotionModel, order: MotionOrder, o?: {
    seed?: number;
    source?: string;
}): MotionPiece[];

MotionOrder type motion

type MotionOrder = typeof MOTION_ORDERS[number];

MotionPiece interface motion

interface MotionPiece {
    id: string;
    kind: 'region' | 'node';
    parent?: string;
    depth: number;
    layer: number;
    key: number;
    bbox: Rect;
    /** the middle of its footprint, and its bottom outline (left, front, right corner), in the drawing's units */
    foot: [number, number];
    base: [number, number][];
    motion?: PieceMotion;
}

MotionPlan interface motion

interface MotionPlan {
    kind: 'assemble' | 'disassemble';
    /** ms */
    duration: number;
    /** when each piece moves, in the order it does */
    pieces: {
        id: string;
        delay: number;
        dur: number;
        style: string;
    }[];
    routes: {
    …
}

paint function motion

The same on a live drawing (a scene's own <svg>). Idempotent, in any order: what the last state changed is put back first, so the same state gives the same DOM; an empty state gives the still back.

function paint(svg: SVGSVGElement, S: SceneState, rendered?: Looks, o?: {
    styles?: 'attribute' | 'cssom';
}): void;

PieceMotion type motion

what one piece's (or a region's contents') motion: in the file may say

type PieceMotion = RawMotion;

planOf function motion

function planOf(m: MotionModel, kind: 'assemble' | 'disassemble', opts?: AnyOptions): MotionPlan;

PlanOptions type motion

either's options: the style is the plan's own kind's

type PlanOptions = Omit<AssembleOptions & DisassembleOptions, 'style'> & {
    style?: AssembleStyle | DisassembleStyle;
};

RouteState interface motion

a connector: how much of it is drawn (0 to 1: its arrowhead shows at 1), stroked in, or growing from its source

interface RouteState {
    opacity?: number;
    drawn?: number;
    by?: 'stroke' | 'grow';
    /** (a timeline's) marching dashes: on and off, and how far they have marched, in the drawing's units along it */
    ants?: {
        dash: [number, number];
        offset: number;
    };
}

ScenePlan interface motion

interface ScenePlan extends MotionPlan {
    /** the scene's SVG at t ms, as text: svgAt(scene, at(t)) */
    frame(t: number): string;
}

SceneState interface motion

Plain JSON. Empty: the still render. What isn't named is as in the still.

interface SceneState {
    items?: Record<string, ItemState>;
    /** by the id of a thing, a connector or a note */
    labels?: Record<string, LabelState>;
    routes?: Record<string, RouteState>;
    /** by the id of a thing: how much of each of its looks is there (the rest is its own), 0 to 1 */
    variants?: Record<string, Record<string, number>>;
    /** the step marks' and badges' layers */
    marks?: {
        opacity: number;
    };
    /** a token on a connector, a fraction (0 to 1) of the way along it */
    …
}

svgAt function motion

A scene as it looks in a state, as SVG text. An empty state is the still render itself, byte for byte.

function svgAt(scene: Pick<CompiledScene, 'rendered' | 'id'>, S: SceneState): string;

CameraVerbs interface motion-builder

interface CameraVerbs<B> {
    focus(on: Ids | [number, number, number, number], o?: Timing & {
        zoom?: number;
        margin?: number;
    }): B;
    fit(o?: Timing): B;
}

motion const motion-builder

Start a motion document.

const motion: (head?: {
    fps?: number;
    seed?: number;
    ambient?: 'on' | 'off';
}) => MotionBuilder;

MotionBuilder class motion-builder

class MotionBuilder extends SeriesBuilder {
    private over;
    private marks;
    private head;
    constructor(head?: {
        fps?: number;
        seed?: number;
        ambient?: 'on' | 'off';
    });
    /** a beat: a sequence with commentary */
    beat(name: string, say: Say, o?: SequenceOptions, fill?: (b: NodesBuilder) => unknown): this;
    /** the whole drawing arrives (a sequence as long as that takes) */
    …
}

NodesBuilder class motion-builder

what is in a sequence (or in a document's layers), in the order it is said

class NodesBuilder {
    /** @internal */
    readonly nodes: MotionNode[];
    private add;
    assemble(o?: Omit<AssembleOptions, 'duration'>, t?: Timing): this;
    disassemble(o?: Omit<DisassembleOptions, 'duration'>, t?: Timing): this;
    /** tokens along connectors, one after another; a nested list at once; "id:kind" */
    travel(routes: (string | string[])[], o?: Timing & {
        each?: MotionTime;
        hold?: MotionTime;
        loop?: boolean;
    }): this;
    …
}

SequenceOptions type motion-builder

a sequence's own keys; read: as long as its words take (true, or how)

type SequenceOptions = Omit<Sequence, 'name' | 'children' | 'layers' | 'series' | 'duration'> & {
    duration?: MotionTime;
    read?: ReadTime['read'];
};

SeriesBuilder class motion-builder

class SeriesBuilder {
    /** @internal */
    readonly items: SeriesItem[];
    sequence(name: string | undefined, o?: SequenceOptions, fill?: (b: NodesBuilder) => unknown): this;
    transition(t: Transition): this;
}

Timing interface motion-builder

interface Timing {
    from?: MotionTime;
    over?: MotionTime;
    easing?: MotionEase;
}

bezier const motion-doc

const bezier: (x1: number, y1: number, x2: number, y2: number) => (x: number) => number;

checkMotion function motion-doc

What is wrong with a document's shape, each with its place (a JSON pointer). Its ids are bindMotion's to check.

function checkMotion(doc: unknown): MotionDiag[];

Curve interface motion-doc

a value over time: Remotion's interpolate, with ms for frames

interface Curve {
    times: MotionTime[];
    values: number[];
    easing?: MotionEase;
    extrapolateLeft?: Extrapolate;
    extrapolateRight?: Extrapolate;
}

curveAt function motion-doc

Remotion's interpolate, for a checked curve: piecewise, the easing in each piece, the ends as asked (extend by default).

function curveAt(c: Curve, t: number, fps?: number): number;

easeOf function motion-doc

An easing as a function of the share of its time done; a spring is given the time's length too.

function easeOf(e: MotionEase | undefined, duration: number, otherwise?: EasingName): (f: number) => number;

EASING_NAMES const motion-doc

const EASING_NAMES: readonly ['linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out', 'settle', 'bounce'];

EasingName type motion-doc

type EasingName = typeof EASING_NAMES[number];

Extrapolate type motion-doc

type Extrapolate = typeof EXTRAPOLATE[number];

EXTRAPOLATE const motion-doc

const EXTRAPOLATE: readonly ['extend', 'clamp', 'wrap', 'identity'];

Focus interface motion-doc

what a beat's focus dims: everything else, or the connectors and notes only

interface Focus {
    lit: string[];
    scope?: 'all' | 'links';
    level?: number;
    always?: string[];
}

MotionDiag interface motion-doc

interface MotionDiag {
    severity: 'error' | 'warning';
    path: string;
    message: string;
    hint?: string;
}

MotionDoc interface motion-doc

interface MotionDoc {
    isomotion: 1;
    fps?: number;
    seed?: number;
    ambient?: 'on' | 'off';
    series?: SeriesItem[];
    layers?: MotionNode[];
    /** named moments: ms, or "beat+1200" */
    markers?: Record<string, MotionTime>;
}

MotionEase type motion-doc

type MotionEase = EasingName | {
    bezier: [number, number, number, number];
} | {
    spring: SpringConfig;
};

MotionNode type motion-doc

type MotionNode = {
    sequence: Sequence;
} | {
    series: SeriesItem[];
} | {
    layers: MotionNode[];
} | ({
    assemble: Omit<PlanOptions, 'duration'>;
} & ChildTiming) | ({
    disassemble: Omit<PlanOptions, 'duration'>;
} & ChildTiming)
/** tokens along connectors: in sequence;

MotionTime type motion-doc

ms, or "1.2s", "450ms", "30f" (frames, at the document's fps)

type MotionTime = number | string;

msOf function motion-doc

a time in ms, or undefined when it isn't one

function msOf(t: unknown, fps?: number): number | undefined;

readMs function motion-doc

how long a beat's words take to read

function readMs(say: Say | undefined, r: ReadTime['read']): number;

ReadTime interface motion-doc

as long as it takes to read it: base + perChar × the text's length, between min and max

interface ReadTime {
    read: true | {
        base?: number;
        perChar?: number;
        min?: number;
        max?: number;
    };
}
interface ChildTiming {
    from?: MotionTime;
    duration?: MotionTime;
    easing?: MotionEase;
}

Sequence interface motion-doc

interface Sequence {
    name?: string;
    from?: MotionTime;
    duration?: MotionTime | ReadTime;
    loop?: boolean | number;
    playbackRate?: number;
    trimBefore?: MotionTime;
    /** in a series: later (or, negative, earlier) than the end of the one before; those after it move too */
    offset?: MotionTime;
    say?: Say;
    /** cumulative: what is there is the fold of every beat to here */
    show?: string[];
    …
}

SeriesItem type motion-doc

type SeriesItem = {
    sequence: Sequence;
} | {
    transition: Transition;
};

springAt function motion-doc

A damped spring from 0 to 1, t ms after it is let go: the closed form, no steps.

function springAt(t: number, c?: SpringConfig): number;

SpringConfig interface motion-doc

interface SpringConfig {
    mass?: number;
    damping?: number;
    stiffness?: number;
    overshootClamping?: boolean;
}

Transition interface motion-doc

interface Transition {
    presentation: 'fade' | 'none';
    timing: {
        linear: MotionTime;
    } | {
        spring: SpringConfig & {
            duration?: MotionTime;
        };
    };
}

MOTION_SCHEMA const motion-schema

const MOTION_SCHEMA: {
    readonly $schema: 'https://json-schema.org/draft/2020-12/schema';
    readonly title: 'isomotion/1';
    readonly type: 'object';
    readonly required: readonly ['isomotion'];
    readonly additionalProperties: false;
    readonly properties: {
        readonly isomotion: {
            readonly const: 1;
        };
        readonly fps: {
            readonly type: 'number';
    …
};

gateBox function place

function gateBox(f: Placed, h: number, w: number, d: number): Box;

Layout interface place

interface Layout {
    items: Placed[];
    byId: Map<string, Placed>;
    roots: Placed[];
    diags: Diag[];
    /** the kinds it was laid out with: drawing and routing ask them too */
    catalog: KindCatalog;
}

Located interface place

interface Located {
    locate(path: string, opts?: {
        key?: boolean;
    }): {
        line: number;
        col: number;
    };
}

overlap2 function place

function overlap2(a: Box, b: Box, e?: number): boolean;

place function place

function place(scene: RawScene, scenePath: string, src: Located, theme: Theme, catalog: KindCatalog, fileRoles?: Record<string, unknown>, snap?: number): Layout;

WALL_T const place

a walled region's wall thickness

const WALL_T = 0.16;

growLeftBack function resize

(0.29.0) A thing dropped past a group's left or back margin lo (at: in the group's frame, less than lo), on the grid step: the pins that make the group grow that way. The thing comes in by s (to the margin), the group moves by -s in its parent's frame (its pin, group.at: where it stands now), and with 'pins' every other thing in it that can be pinned moves by +s. Undefined: not past the margin, or the group can't be pinned (then the side is held).

function growLeftBack(o: {
    name: string;
    at: [number, number];
    lo: number;
    step: number;
    group?: {
        name: string;
        at: [number, number];
    };
    others: {
        name: string;
        at: [number, number];
    …
} | undefined;

GrowLeftBack type resize

(0.29.0) how a group grows on its left or back side, when it does (canvas.ts GROW_SIDES): its other contents' pins move the other way, so nothing but the dragged thing and the edge moves on screen ('pins', the owner's answer to question 2). (0.30.0) The variant not chosen, 'shift' (the whole group moving with the edge), is removed: 0.29.0 has it.

type GrowLeftBack = 'pins';

minSizeFor function resize

The smallest floor a group can have and still hold what it holds: its children's furthest extent, and its margin, from its corner (on the grid step; at least two margins and half a cell, as a fitting group is). Boxes in the same frame as box.

function minSizeFor(box: {
    x0: number;
    y0: number;
}, children: {
    x1: number;
    y1: number;
}[], pad: number, step?: number): [number, number];

minSizeFrom function resize

(0.29.0) The smallest floor for a resize that keeps anchor sides still (a left handle keeps the right edge: what it holds is measured from there). Boxes in one frame.

function minSizeFrom(box: {
    x0: number;
    y0: number;
    x1: number;
    y1: number;
}, children: {
    x0: number;
    y0: number;
    x1: number;
    y1: number;
}[], pad: number, sides: ResizeSides, step?: number): [number, number];

ResizeHandle type resize

(0.28.0) a group's resize handle: its front-right corner (width and depth), or the middle of its right side (width) or of its front side (depth). Left and back wait for the owner (canvas.ts GROW_SIDES).

type ResizeHandle = 'corner' | 'right' | 'front';

resizeSides function resize

(0.29.0) A drag of (dx, dy) on a handle that moves sides: the new floor, snapped, never below min (held), and shift: how far the group's corner moves for a left or back side (positive: it grew that way), so that the opposite edge stays where it is on screen; the group's own pin moves by -shift and what it holds by +shift.

function resizeSides(size0: [number, number], d: [number, number], sides: ResizeSides, step: number, min: [number, number]): {
    size: [number, number];
    held: boolean;
    shift: [number, number];
};

ResizeSides interface resize

(0.29.0) the sides a resize handle moves (its corner, two; the middle of a side, one)

interface ResizeSides {
    left?: boolean;
    right?: boolean;
    back?: boolean;
    front?: boolean;
}

resizeTo function resize

A drag of (dx, dy) grid units on a resize handle, from size0: the new floor, snapped to step, never below min (held: it stopped there). The corner changes both; the right side the width alone; the front side the depth alone.

function resizeTo(size0: [number, number], d: [number, number], handle: ResizeHandle, step: number, min: [number, number]): {
    size: [number, number];
    held: boolean;
};

FONT_STACKS const resolve

const FONT_STACKS: {
    sans: string;
    mono: string;
};

ResolveOptions interface resolve

interface ResolveOptions {
    mode: ThemeMode;
    theme: Theme;
    /** the drawing's stylesheets, in order, after the theme's */
    css: string;
    /** the fonts the texts ask for (a stack each) */
    fonts?: {
        sans: string;
        mono: string;
    };
}

resolveSvg function resolve

The drawing, self-contained, in one of its theme's modes. What its stylesheets hide is left out of the paint (display none); ids, classes and data- attributes stay.

function resolveSvg(svg: string, o: ResolveOptions): string;

ThemeMode type resolve

type ThemeMode = 'light' | 'dark';

floorAt function route

function floorAt(layout: Layout, x: number, y: number): number;

openList function route

A* open list, taking the state with the lowest f, ties to the one earliest in the list, where taking one moves the last into its place (so the order is exactly that of the array scan this replaces, and every route is the same). A binary heap ordered by (f, position): O(log n) a step instead of a scan of the whole list, which on a large drawing (tens of thousands of open states, hundreds of thousands of steps) took minutes.

function openList<T extends {
    f: number;
    idx: number;
    hp: number;
}>(): {
    length: () => number;
    push(s: T): void;
    take(): T;
};

parseEnd function route

function parseEnd(s: string): {
    id: string;
    side?: Side;
};

RawRoute interface route

interface RawRoute {
    id: string;
    from: string;
    to: string;
    kind?: string;
    via?: (number[] | string)[];
    points?: number[][];
    lane?: number;
    arrow?: boolean;
    cross?: boolean;
    label?: string | {
        text: string;
    …
}

ROUTE_BUDGET const route

The search steps routing may take in one scene. The heaviest diagram in this repo takes about 57,000 (the large drawing in corpus/messaging.yaml); a drawing with 40 more nodes took 11 million, and minutes. Past the budget, the routes left are drawn as plain elbows and the scene says so, so a large diagram draws in about a second.

const ROUTE_BUDGET = 500000;

routeAll function route

function routeAll(scene: RawScene, scenePath: string, layout: Layout, src: Located, kinds: Set<string>, snap?: number): RouteResult;

Routed interface route

interface Routed {
    id: string;
    raw: RawRoute;
    path: string;
    kind: string;
    points: P3[];
    from?: Placed;
    to?: Placed;
}

RouteResult interface route

interface RouteResult {
    routes: Routed[];
    diags: Diag[];
}

simplify function route

function simplify(p: [number, number][]): [number, number][];

LABEL_BUDGET const scene

label spots weighed in one scene: the busiest diagram here weighs under 200; a drawing with 80 more nodes, 79,000

const LABEL_BUDGET = 20000;

regionRole const scene

the colour role a region is drawn in: its own, else its kind's

const regionRole: (cat: KindCatalog, r: {
    role?: string;
    kind: string;
}) => string;

RenderedScene interface scene

interface RenderedScene {
    svg: string;
    viewBox: [number, number, number, number];
    /** text rectangles in screen px, for layout tests */
    texts: {
        x: number;
        y: number;
        w: number;
        h: number;
        text: string;
        owner?: string;
    }[];
    …
}

renderScene function scene

function renderScene({ scene, layout, routes, steps, theme, id, gridStep }: SceneInput): RenderedScene;

RenderWarning interface scene

interface RenderWarning {
    path: string;
    message: string;
}

SceneInput interface scene

interface SceneInput {
    scene: RawScene;
    layout: Layout;
    routes: Routed[];
    steps: Steps;
    theme: Theme;
    id: string;
    gridStep?: number;
}

wallsOf function scene

The walls of a walled region's cage, with a gap where its gate is.

function wallsOf(r: Placed): Box[];

Pin type settle

type Pin = [string, [number, number]];

prunePins function settle

(0.30.0) The kept pins a drop needs: each tried without, and left out when the drawing stays the same without it (where everything stands, as where says); what stays is the fewest pins that hold the drawing as the full set does.

function prunePins<D>(pins: readonly Pin[], keep: readonly Pin[], lay: (pins: Pin[]) => D, where: (d: D) => string): Pin[];

settlePins function settle

want: each name and where it is meant to stand (as at measures it); lay: a drawing from pins; at: where a drawing stands a name; drawn: the drawing want already makes, if laid out. The corrected pins, in want's order, and the drawing they make

function settlePins<D>(want: readonly Pin[], lay: (pins: Pin[]) => D, at: (d: D, name: string) => [number, number] | undefined, drawn?: D): {
    pins: Pin[];
    drawn: D;
};

Badge interface steps

interface Badge {
    step: number;
    num: number;
    kind: string;
    p: P3;
}

durationFor function steps

function durationFor(caption: string): number;

Mark interface steps

interface Mark {
    step: number;
    p: P3;
    on?: string;
}

midpoint function steps

The point halfway along a polyline.

function midpoint(pts: P3[]): P3;

RawStep interface steps

interface RawStep {
    id?: string;
    number?: number;
    kind?: string;
    heading: string;
    caption?: string;
    command?: string;
    animate?: (string | Record<string, string> | (string | Record<string, string>)[])[];
    pulse?: string[];
    highlight?: string[];
    show?: string[];
    hide?: string[];
    …
}

resolveSteps function steps

function resolveSteps(scene: RawScene, scenePath: string, layout: Layout, routes: Routed[], src: Located, theme: Theme): Steps;

Say interface steps

A callout: (x, y) is where the author asked for it; (ax, ay) is the point it belongs to, for placement.

interface Say {
    step: number;
    x: number;
    y: number;
    ax: number;
    ay: number;
    text: string;
    kind: string;
    anchor: 'start' | 'middle' | 'end';
}

StepData interface steps

interface StepData {
    n: number;
    num: number;
    kind: string;
    color: string;
    heading: string;
    caption: string;
    command: string;
    phases: Token[][];
    pulses: [number, number, number, number][];
    lit: string[];
    duration: number;
    …
}

Steps interface steps

interface Steps {
    steps: StepData[];
    says: Say[];
    marks: Mark[];
    badges: Badge[];
    /** id → visibility at each step (index 0 = step 1); only for ids whose visibility ever changes */
    vis: Record<string, boolean[]>;
    /** ids of route-bound notes: note index → route id */
    diags: Diag[];
    kindsUsed: string[];
}

Token interface steps

interface Token {
    route: string;
    kind: string;
    color: string;
}

BeatInfo interface timeline

interface BeatInfo {
    name: string;
    index: number;
    start: number;
    end: number;
    say?: Say;
}

bindMotion function timeline

function bindMotion(drawing: CompiledScene | MotionSource, doc: MotionDoc, opts?: BindOptions): Timeline;

BindOptions interface timeline

interface BindOptions {
    /** the connectors' dashes, by kind: the theme's `kinds` (a dashed kind marches with its own dash) */
    kinds?: Record<string, {
        dash?: 'solid' | 'dashed' | 'dotted';
        ants?: [number, number];
    }>;
    /** kinds whose connectors stand still (default: blocked, planned) */
    still?: string[];
}

Cue interface timeline

interface Cue {
    beat: string;
    chapter?: string;
    index: number;
    of: number;
    progress: number;
    say?: Say;
    color?: string;
}

motionOfSteps function timeline

A drawing's own steps as a motion document, so that every drawing with steps has a timeline.

function motionOfSteps(scene: CompiledScene): MotionDoc;

motionSource function timeline

function motionSource(scene: CompiledScene): MotionSource;

MotionSource interface timeline

What binding needs to know of a drawing, as plain JSON: for a page that has the drawing and no compiler.

interface MotionSource {
    model: MotionModel;
    /** each connector's kind */
    kinds: Record<string, string>;
    /** each thing's outline */
    outlines: Record<string, [number, number][]>;
    /** the looks each thing declares */
    looks?: Record<string, string[]>;
    ants?: ReturnType<typeof antsOf>;
    /** the notes on nothing (JSON keeps no undefined) */
    free?: string[];
}

Timeline interface timeline

interface Timeline {
    readonly ok: boolean;
    readonly diags: MotionDiag[];
    /** ms */
    readonly duration: number;
    readonly beats: BeatInfo[];
    readonly markers: Record<string, number>;
    /** the document's own `ambient`: what at(ms) does with none given */
    readonly ambient: 'on' | 'off';
    /** whether anything in it runs on the ambient clock (ants, looping tokens and pulses): a host with none needs no frames while paused */
    readonly loops: boolean;
    /** what the drawing looks like at ms. `ambient`: the ambient clock's time (default: the same; a host that stopped it passes the time it
    …
}

GridDef interface types

interface GridDef {
    snap?: number;
    show?: boolean;
    step?: number;
}

Placed interface types

Something placed: a region or a node, with its absolute box after layout.

interface Placed {
    id: string;
    type: 'region' | 'node';
    /** JSON path into the source, for diagnostics */
    path: string;
    parent?: Placed;
    children: Placed[];
    box: Box;
    /** the z its children stand on */
    floor: number;
    appears?: StepRef;
    disappears?: StepRef;
    …
}

RawDeco type types

type RawDeco = string | {
    terminal?: number;
    icon?: string;
    screen?: string;
};

RawDiagram interface types

interface RawDiagram {
    isodiag: 1;
    title?: string;
    lede?: string;
    pills?: string[];
    theme?: string;
    roles?: Record<string, RawRole>;
    kinds?: Record<string, RawKind>;
    after?: string;
    footer?: string;
    grid?: GridDef;
    assemble?: boolean;
    …
}

RawGate interface types

interface RawGate {
    side: Side;
    at?: number;
    width?: number;
    height?: number;
    node?: string;
}

RawMotion interface types

how one piece (and, a region's, its contents) moves when a drawing assembles or disassembles (motion.ts)

interface RawMotion {
    style?: 'edge' | 'drop' | 'rise' | 'fly' | 'pop' | 'scatter' | 'build' | 'fade';
    out?: 'explode' | 'lift-off' | 'sink' | 'scatter' | 'fly-out' | 'collapse' | 'fade' | 'reverse';
    easing?: 'linear' | 'ease' | 'ease-in' | 'ease-out' | 'settle' | 'spring' | 'bounce';
    from?: 'left' | 'right' | 'top' | 'bottom';
    /** ms after its turn, and ms its own move takes */
    delay?: number;
    duration?: number;
}

RawNode interface types

interface RawNode extends RawPlacement {
    id: string;
    asset?: string;
    role?: string;
    label?: string;
    sub?: string;
    size?: number[];
    z?: number;
    deco?: RawDeco[];
    ghost?: boolean;
    face?: string;
    facing?: number;
    …
}

RawNote interface types

interface RawNote {
    floor?: string;
    face?: string;
    label?: string;
    sub?: string;
    at?: number[];
    on?: string;
    kind?: string;
    dir?: 'x' | 'y';
    anchor?: 'start' | 'middle' | 'end';
    dx?: number;
    dy?: number;
    …
}

RawPlacement interface types

interface RawPlacement {
    in?: string;
    at?: [number, number];
    'right-of'?: string;
    'left-of'?: string;
    below?: string;
    behind?: string;
    gap?: number;
    align?: 'start' | 'center' | 'end';
    shift?: [number, number];
    appears?: StepRef;
    disappears?: StepRef;
}

RawRegion interface types

interface RawRegion extends RawPlacement {
    id: string;
    kind: RegionKindName;
    label?: string;
    'label-style'?: 'face' | 'face-right' | 'floor' | 'none';
    ghost?: boolean;
    role?: string;
    size?: number[];
    padding?: number;
    height?: number;
    z?: number;
    flow?: Flow;
    …
}

RawScene interface types

interface RawScene {
    id: string;
    title: string;
    caption?: string;
    aria?: string;
    gap?: number;
    flow?: Flow;
    /** (0.23.0) compact: every container without a flow of its own lays its children out as a grid (the most square block) */
    layout?: 'compact';
    regions?: RawRegion[];
    nodes?: RawNode[];
    routes?: unknown[];
    …
}

RawVariant interface types

interface RawVariant {
    role?: string;
    ghost?: boolean;
    label?: string;
    sub?: string;
    face?: string;
    deco?: RawDeco[];
}

RegionKindName type types

a region kind's name in the catalogue the drawing is laid out with (src/iso-objects/kinds.ts)

type RegionKindName = string;

Side type types

type Side = 'n' | 'e' | 's' | 'w';

StepRef type types

type StepRef = string | number;

viewer src/iso-viewer

import { viewer } from '@johnoscott/isometric-engine/render';    // also in /editor and /systems
import { … } from '@johnoscott/isometric-engine/modules/iso-viewer/MODULE';

Appear type card-motion

type Appear = 'scale' | 'spin' | 'dissolve' | 'inflate';

APPEARS const card-motion

const APPEARS: [Appear, string][];

cardMotion function card-motion

function cardMotion(host: MotionHost, initial: MotionSettings, { prefix, key, alt }: CardNames): {
    readonly settings: {
        enabled: boolean;
        appear: Appear;
        idle: Idle;
    };
    set(next: Partial<MotionSettings>, cards: Iterable<SVGGElement>): void;
    update: (prev: Map<string, SVGGElement>, cur: Map<string, SVGGElement>, gone: Map<string, boolean>, animateOut: boolean, still?: boolean) => void;
    appear: (card: SVGGElement) => Promise<void>;
    disappear: (card: SVGGElement) => Promise<void>;
    startIdle: (card: SVGGElement, period?: number) => void;
    stopIdle: (card: SVGGElement) => void;
    …
};

CardMotion type card-motion

type CardMotion = ReturnType<typeof cardMotion>;

CardNames interface card-motion

the domain's cards: their class prefix, as the overlay draws them (PREFIX-float, a card that has gone PREFIX-leaving, in the PREFIX-leaving-layer), and the attributes a card's key is read from: key, else alt (removed when it goes)

interface CardNames {
    prefix: string;
    key: string;
    alt: string;
}

Idle type card-motion

type Idle = 'none' | 'jiggle' | 'pirouette' | 'glow' | 'breathe';

IDLES const card-motion

const IDLES: [Idle, string][];

MotionHost interface card-motion

interface MotionHost {
    /** turn a card about its vertical axis (radians), lifted (cells): its faces drawn again */
    spin(card: SVGGElement, theta: number, lift: number): void;
    /** the card as drawn still again */
    restore(card: SVGGElement): void;
    /** where a card that has gone may finish going (outside the state layer, which is reconciled) */
    leavingLayer(): SVGGElement | undefined;
    /** the amber of the cards' edge */
    amber(): string;
}

MotionSettings interface card-motion

interface MotionSettings {
    enabled: boolean;
    appear: Appear;
    idle: Idle;
}

COMPARE_CSS const compare

What a compare adds to the player's stylesheet.

const COMPARE_CSS = "\n.iso-compare-pair{display:inline-flex}\n.iso-compare-pair .iso-play-btn:first-child{border-radius:8px 0 0 8px;border-right-width:0}\n.iso-compare-pair .iso-play-btn:last-child{border-radius:0 8px 8px 0}\n.iso-compare-pair .iso-play-btn[aria-pressed=\"true\"]{background:var(--ip-ink);color:var(--ip-bg)}\n.iso-compare-legend{display:flex;flex-wrap:wrap;gap:4px 18px;margin:0;padding:4px 12px;list-style:none;font-size:13px}\n.iso-compare-legend[hidden]{display:none}\n.iso-compare-legend svg{display:inline-block;vertical-align:middle}\n.iso-compare-list ul{margin:6px 0 0;padding-left:20px}\n.iso-play.frozen .iso-compare-row,.iso-play.frozen .iso-compare-legend{display:none}\n";

ComparePlayer interface compare

interface ComparePlayer extends Player {
    /** how far it is, 0 (the first drawing) to 1 (the second) */
    readonly between: number;
    /** to one of them, the way there played */
    show(which: 'before' | 'after'): void;
    /** straight to a place between */
    seek(f: number): void;
    /** other drawings, where it was */
    compare(c: Comparison, mode?: 'light' | 'dark'): void;
}

ComparePlayerOptions interface compare

interface ComparePlayerOptions extends Pick<PlayerOptions, 'label' | 'controls' | 'autoplay' | 'rate' | 'reducedMotion' | 'mode' | 'zoom' | 'clock'> {
    comparison: Comparison;
}

mountCompare function compare

function mountCompare(host: HTMLElement | ShadowRoot, o: ComparePlayerOptions): ComparePlayer;

h function dom

function h<K extends keyof HTMLElementTagNameMap>(tag: K, attrs?: Record<string, unknown> | null, ...kids: (Node | string | null | undefined | false)[]): HTMLElementTagNameMap[K];

DUAL_VIEW_CSS const dual-view

the switch's and the views' own CSS (unscoped)

const DUAL_VIEW_CSS = "\n.view-switch{display:inline-flex;border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--surface);font:600 12px/1 system-ui,sans-serif;box-shadow:0 1px 4px rgba(0,0,0,.12)}\n.view-switch button{font:inherit;border:0;background:none;color:var(--ink);padding:6px 10px;cursor:pointer}\n.view-switch button+button{border-left:1px solid var(--line)}\n.view-switch button[aria-pressed=true]{background:var(--accent,#2f6fd6);color:#fff}\n.view-switch button:focus-visible{outline:2px solid var(--accent,#2f6fd6);outline-offset:-2px}\n.dual-view [data-id][tabindex]:focus-visible{outline:none}\n.dual-view .blk.sel polygon{stroke:var(--accent,#2f6fd6);stroke-width:2.4}\n.dual-view [data-a].dim{opacity:.3}\n.dual-view [data-a].hot path{stroke-width:3.4}\n";

dualView function dual-view

the scene in both views, in host: the 3D drawing as the engine rendered it, the 2D one laid out from its board

function dualView(host: HTMLElement, scene: CompiledScene, opts?: DualViewOptions): DualView;

DualView interface dual-view

interface DualView {
    readonly mode: ViewMode;
    readonly layout: FlatLayout;
    readonly root: HTMLElement;
    /** switch view, animated (instant with reduced motion); resolves when the view is shown */
    morph(to: ViewMode): Promise<void>;
    select(id: string | undefined): void;
    readonly selected: string | undefined;
    /** the svg of a view */
    svgOf(mode: ViewMode): SVGSVGElement;
    destroy(): void;
}

DualViewOptions interface dual-view

interface DualViewOptions {
    mode?: ViewMode;
    /** the board the 2D view draws; default: boardOf(scene) */
    board?: Board;
    /** link kinds' styles in 2D */
    styles?: Record<string, FlatStyle>;
    flat?: Partial<FlatOptions>;
    /** the svg's label */
    title?: string;
    onSelect?(id: string | undefined): void;
    /** the morph's length, ms */
    duration?: number;
    …
}

storedMode function dual-view

the view a page last showed (localStorage), if any

function storedMode(key?: string): ViewMode | undefined;

viewToggle function dual-view

the 3D | 2D switch: two buttons (aria-pressed), the choice remembered in localStorage; it switches every view given

function viewToggle(host: HTMLElement, views: DualView | DualView[], opts?: {
    storageKey?: string;
    labels?: [string, string];
}): HTMLElement;

morphDrawing function flat-morph

A scene's two views, and the way from one to the other.

function morphDrawing(scene: CompiledScene, o: MorphOptions): MorphDrawing;

MorphDrawing interface flat-morph

interface MorphDrawing {
    id: string;
    from: ViewMode;
    /** the stage, in the 3D view's own units */
    viewBox: [number, number, number, number];
    at(t: number): MorphState;
    /** the frame: at 0 the view it begins in, at 1 the other, each as its own still (in the stage's view) */
    svgAt(t: number): string;
}

MorphOptions interface flat-morph

interface MorphOptions extends Pick<FlatStillOptions, 'board' | 'flat' | 'styles'> {
    theme: Theme;
    mode: ThemeMode;
    /** the view it begins in (default: 3D) */
    from?: ViewMode;
    /** what its ids begin with (default: the scene's id and `-morph`) */
    id?: string;
}
type M = [number, number, number, number, number, number];

MorphState interface flat-morph

interface MorphState {
    out: number;
    in: number;
    things: Record<string, MorphThing>;
}

MorphThing interface flat-morph

a thing's part of the way: each view's shapes, moved by a matrix, and how much of it shows; its face where it has one

interface MorphThing {
    from?: {
        m: M;
        opacity: number;
    };
    to?: {
        m: M;
        opacity: number;
    };
    face?: {
        points: [number, number][];
        fill: string;
    …
}

flatStill function flat-still

A scene's 2D view, self-contained, in the mode and (where the scene is drawn in it) the black and white of its 3D one.

function flatStill(scene: CompiledScene, o: FlatStillOptions): FlatStill;

FlatStill interface flat-still

interface FlatStill {
    svg: string;
    layout: FlatLayout;
    viewBox: [number, number, number, number];
}

FlatStillOptions interface flat-still

interface FlatStillOptions {
    /** the theme it was compiled with (Compiled's), and which of its modes */
    theme: Theme;
    mode: ThemeMode;
    /** what it draws (default: the scene's own board), laid out so */
    board?: Board;
    flat?: Partial<FlatOptions>;
    /** link kinds' styles, over the theme's own */
    styles?: Record<string, FlatStyle>;
    /** what its ids begin with (default: the scene's id and `-flat`) */
    id?: string;
    title?: string;
}

flatCss function flat-view

the 2D view's stylesheet: its fonts (the ones flat.ts's FLAT_FONTS measures), its faces in the theme's role colours, and each link kind's colour and dash. Unscoped: a page scopes it as it scopes the drawing's (view-css.ts). page: false: without what only a page has a use for (the pointer, the keyboard's focus, the page's own font): a still's

function flatCss(styles?: Record<string, FlatStyle>, o?: {
    page?: boolean;
}): string;

FlatStyle interface flat-view

how a link kind is drawn: its ends, its dash, its colour (a theme token, e.g. "send", or any CSS colour)

interface FlatStyle {
    start?: 'arrow' | 'open' | 'diamond' | 'none';
    end?: 'arrow' | 'open' | 'diamond' | 'none';
    dash?: string;
    color?: string;
    width?: number;
}

flatSvg function flat-view

the 2D drawing: panels, connectors, cards, then the connectors' labels. id prefixes its marker ids.

function flatSvg(L: FlatLayout, opts: {
    id: string;
    title?: string;
    styles?: Record<string, FlatStyle>;
}): string;

measureIn function flat-view

a measure from a page's own rendered text: a hidden 2D svg in host (so the view's stylesheet applies), each text measured by getComputedTextLength, remembered

function measureIn(host: Element): Measure & {
    dispose(): void;
};

rectOf const flat-view

the rect of a card or panel in a layout

const rectOf: (L: FlatLayout, id: string) => FlatRect | undefined;

activityOf function history

the activity a result shows (for time breaks): marks, span ends, bins with events, metrics that moved

function activityOf<T extends TimelineTypes = AnyTimeline>(r: Result<T>, mode: Mode, series?: Map<string, 'counter' | 'gauge'>): [number, number][];

modeFor function history

which zoom level a visible span reads at: single events up to a few hours, then minute, hour and day bins

function modeFor(span: number, px: number): Mode;

mountTimeline function history

function mountTimeline<T extends TimelineTypes = AnyTimeline>(el: HTMLElement, o: TimelineMountOptions<T>): {
    el: HTMLElement;
    ready: Promise<void>;
    readonly view: View;
    setView(v: Partial<View>): Promise<void>;
    setRange(t0: number, t1: number): Promise<void>;
    setPlayhead: (t: number | undefined) => Promise<void>;
    setLive: (on: boolean, go?: boolean) => void;
    setTheme: (t?: 'light' | 'dark' | 'system') => void;
    refresh: () => Promise<void>;
    /** for tests and hosts: what is drawn, and the mapping */
    internal: {
    …
};

TimelineHandle type history

type TimelineHandle = ReturnType<typeof mountTimeline>;

TimelineMountOptions interface history

interface TimelineMountOptions<T extends TimelineTypes = AnyTimeline> {
    source: TimelineSource<T>;
    /** the domain's scopes, flags and search links */
    catalog: TimelineCatalog;
    /** classes on the component's root beside its own (the stylesheet it is styled by is scoped to one) */
    rootClass?: string[];
    /** where to start (else the URL's view, else the first host, 1 level down, the last day) */
    view?: Partial<View>;
    /** the owner's time zone (default: the viewer's) */
    tz?: string;
    /** light, dark, or the viewer's (default) */
    theme?: 'light' | 'dark' | 'system';
    …
};

buildLayer function morph

the layer a morph draws on: at(t) paints it t of the way from one view to the other. Both views are in the root and laid out (hidden is fine, display: none is not): a host seeks it frame by frame (0.12.2: exported).

function buildLayer(root: HTMLElement, fromSvg: SVGSVGElement, toSvg: SVGSVGElement, from: ViewMode): MorphLayer;

clamp const morph

const clamp: (v: number) => number;

ease const morph

const ease: (t: number) => number;

markConnectors function morph

a 3D drawing's connectors marked with the ends they join (data-a, data-b), as the 2D ones are: a board's link may be drawn to a panel, so its ends are the board's when given

function markConnectors(svg3: SVGSVGElement, scene: CompiledScene, board?: Board): void;

MorphLayer interface morph

a morph's layer: append svg to the root; at(t) paints it t (0 to 1) of the way, in any order (no clock)

interface MorphLayer {
    svg: SVGSVGElement;
    at(t: number): void;
}

morphSvgs function morph

The morph dualView runs (0.7.5: for the editor's canvas too), from one view's svg to the other's, over root: things move from where they are to where they will be (a 3D top face becoming its 2D card, or back), connectors fade out and draw in. Undefined when the motion option says not to animate (or the duration is 0).

function morphSvgs(root: HTMLElement, fromSvg: SVGSVGElement, toSvg: SVGSVGElement, from: ViewMode, o?: {
    duration?: number;
    motion?: 'auto' | 'always' | 'never';
}): SvgMorph | undefined;

SvgMorph interface morph

A running morph between two drawings already laid out in root (positioned): done resolves when it ends, finish() ends it at once (the layer gone). The caller shows and hides the drawings themselves.

interface SvgMorph {
    readonly done: Promise<void>;
    finish(): void;
}

Box type overlay

type Box = {
    x: number;
    y: number;
    w: number;
    h: number;
};

Box3 type overlay

a box in grid cells

type Box3 = {
    x0: number;
    x1: number;
    y0: number;
    y1: number;
    z0: number;
    z1: number;
};

Card interface overlay

a card standing over what it is about

interface Card {
    /** the box (grid cells) it stands over */
    over: {
        x0: number;
        y0: number;
        x1: number;
        y1: number;
        z1: number;
    };
    /** classes beside the card's own */
    cls: string;
    /** attributes on its group (data-*) */
    …
}

CARD const overlay

the card's size in grid cells (large: the first thing the eye finds), its height above what it stands over, the stack's fan (up and right per card) and the gap between its cards (back to front)

const CARD: {
    half: number;
    h: number;
    t: number;
    above: number;
    lift: number;
    fan: number;
    gap: number;
};

CardGeo interface overlay

a card's model: its middle, the tail's tip (z), the card's box and its stack's boxes

interface CardGeo {
    cx: number;
    cy: number;
    tipZ: number;
    card: Box3;
    panes: Box3[];
}

Ghost interface overlay

a thing that isn't in the drawing, drawn as a ghost where the domain puts it

interface Ghost {
    rect: {
        x: number;
        y: number;
        w: number;
        hgt: number;
        k: number;
    };
    /** classes beside the ghost's own */
    cls: string;
    /** attributes on its group (data-*) */
    data: [string, string][];
    …
}

Glyph type overlay

a badge: a character, or an icon (by name), in a small circle; cls: its tone

type Glyph = {
    g: string;
    cls: string;
} | {
    icon: string;
    cls: string;
};

Mark interface overlay

what is drawn over one object, in this order: its outline, its badge (or, with none, a hit area for its title), badges beside it, a dot at its bottom left and a tag at its bottom right

interface Mark {
    /** what it is drawn over (the host's boxOf and outlinesFor know it) */
    at: string;
    title: string;
    /** the class of its outline: an outline is drawn when it has one */
    outline?: string;
    badge?: Glyph;
    /** no badge: a transparent rect over it, holding its title */
    hit?: boolean;
    /** badges beside the first, each a badge's width further right */
    beside?: {
        glyph: Glyph;
    …
}

Outline type overlay

type Outline = {
    kind: 'poly';
    id: string;
    points: [number, number][];
} | {
    kind: 'route';
    d: string;
};

OverlayCtx interface overlay

interface OverlayCtx {
    /** pixels per unit of the drawing (badges keep their size on screen) */
    k(): number;
    /** an object's box on screen (the view measures its elements; a still render, its layout) */
    boxOf(at: string): Box | undefined;
    outlinesFor(at: string): Outline[];
    /** an icon's reference (the view's sprite, or the still render's own symbols) */
    iconHref(name: string): string;
    /** a card drawn, with its geometry in grid cells (a view turns it in 3D) */
    onCard?(card: Element, geo: CardGeo): void;
}

overlayPaint function overlay

The painters. cards: the class prefix the domain's cards are drawn and styled with (PREFIX-card, PREFIX-face…).

function overlayPaint(ctx: OverlayCtx, cards: string): {
    paintMarks: (d: Document, put: (n: Element) => void, marks: Mark[]) => void;
    paintGhosts: (d: Document, put: (n: Element) => void, ghosts: Ghost[]) => void;
    paintCards: (d: Document, put: (n: Element) => void, list: Card[]) => void;
};

OverlayPaint type overlay

type OverlayPaint = ReturnType<typeof overlayPaint>;

P3 const overlay

const P3: (x: number, y: number, z: number) => [number, number];

pts const overlay

const pts: (ps: [number, number][]) => string;

legend function page

function legend(c: Compiled, s: CompiledScene): string;

md function page

A small Markdown subset for captions: code, bold, em, text, paragraphs.

function md(s: string | undefined): string;

PageOpts interface page

interface PageOpts {
    runtime?: string;
    extraHead?: string;
    extraBody?: string;
}

renderPage function page

function renderPage(c: Compiled, opts?: PageOpts): string;

stepData function page

The data the player runs on, for every scene with steps.

function stepData(c: Compiled): string;

splitStyles function picture

The picture without style elements or style attributes, and its CSS: its own css and its style elements' text, in that order. style(root) puts its style attributes back, as CSSOM, on the picture once it is in the page.

function splitStyles(svg: string, css?: string): {
    svg: string;
    css: string;
    style(root: Element): void;
};

mountPlayer function play

function mountPlayer(host: HTMLElement | ShadowRoot, o: PlayerOptions): Player;

PLAY_CSS const play

The player's stylesheet: its own, under one class; the colours are custom properties a host may set.

const PLAY_CSS = "\n.iso-play{--ip-ink:#1c2026;--ip-muted:#68707c;--ip-line:#dfe3e8;--ip-bg:#fff;--ip-code:#f2f4f7;--ip-focus:#2a64d6;container:iso-play/inline-size;display:block;color:var(--ip-ink);background:var(--ip-bg);font:14px/1.5 system-ui,-apple-system,\"Segoe UI\",sans-serif;border-radius:10px}\n.iso-play[data-mode=\"dark\"]{--ip-ink:#e6e9ee;--ip-muted:#98a1ae;--ip-line:#333a44;--ip-bg:#15181d;--ip-code:#1f242b;--ip-focus:#7aa7ff;color-scheme:dark}\n.iso-play:focus-visible,.iso-play button:focus-visible,.iso-play input:focus-visible,.iso-play summary:focus-visible{outline:2px solid var(--ip-focus);outline-offset:2px}\n.iso-play [hidden]{display:none}\n.iso-play-stage svg{display:block;width:100%;height:auto}\n.iso-play-stage{position:relative}\n.iso-play-stage [data-go]{cursor:pointer}\n.iso-play.closer .iso-play-stage svg{cursor:grab;user-select:none;-webkit-user-select:none}\n.iso-play.dragging .iso-play-stage svg{cursor:grabbing}\n.iso-zoom{position:absolute;top:10px;right:54px;display:flex;gap:6px;opacity:0}\n.iso-play:hover .iso-zoom,.iso-zoom:focus-within,dialog .iso-zoom{opacity:1}\n@media (hover:none){.iso-zoom{opacity:1}.iso-zoom .z-in,.iso-zoom .z-out{display:none}dialog .iso-zoom .z-in,dialog .iso-zoom .z-out{display:block}}\n.iso-zoom .iso-play-btn{box-sizing:border-box;height:36px;min-width:36px;border:1px solid #000;border-radius:10px;background:#fff;color:#000;box-shadow:0 2px 0 #000}\n.iso-zoom .iso-play-btn:disabled{opacity:.55}\n.iso-zoom-hint{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);padding:8px 14px;border-radius:10px;background:rgba(12,12,14,.82);color:#fff;font-size:14px;pointer-events:none;visibility:hidden}\n.iso-zoom-hint.on{visibility:visible}\n.iso-play.frozen .iso-zoom,.iso-play.frozen .iso-zoom-hint{display:none}\n@media print{.iso-zoom,.iso-zoom-hint{display:none}}\n.iso-play-row{display:flex;align-items:center;gap:6px;padding:8px 12px 4px}\n.iso-play-btn{font:inherit;min-width:32px;height:32px;padding:0 8px;border:1px solid var(--ip-line);border-radius:8px;background:none;color:inherit;cursor:pointer}\n.iso-play-btn:hover{border-color:var(--ip-muted)}\n.iso-play-btn.play{background:var(--ip-ink);color:var(--ip-bg);border-color:var(--ip-ink);min-width:44px}\n.iso-play-btn.ambient[aria-pressed=\"false\"]{color:var(--ip-muted);text-decoration:line-through}\n.iso-play-btn.still{font-size:12px;white-space:nowrap}\n.iso-play-btn.still[aria-pressed=\"true\"]{background:var(--ip-ink);color:var(--ip-bg)}\n.iso-play-btn:disabled{opacity:.4;cursor:default}\n.iso-play-bar{flex:1 1 60px;min-width:0;accent-color:var(--ip-ink)}\n.iso-play-time{color:var(--ip-muted);font-size:12px;font-variant-numeric:tabular-nums;white-space:nowrap}\n.iso-play-dots{display:flex;flex-wrap:wrap;gap:4px 12px;padding:2px 12px}\n.iso-play-group{display:inline-flex;gap:0}\n.iso-play-dot{width:24px;height:24px;padding:0;border:0;background:none;cursor:pointer;display:grid;place-items:center}\n.iso-play-dot::before{content:\"\";width:9px;height:9px;border-radius:50%;background:var(--ip-line)}\n.iso-play-dot.done::before{background:var(--ip-muted)}\n.iso-play-dot.on::before{background:var(--ip-ink);width:11px;height:11px}\n.iso-play-say{padding:4px 12px 10px;min-height:5.2em}\n.iso-play-head{display:flex;align-items:baseline;gap:8px;font-weight:700}\n.iso-play-num{flex:none;display:inline-grid;place-items:center;min-width:22px;height:22px;border-radius:11px;background:var(--ip-ink);color:var(--ip-bg);font-size:11px;align-self:center}\n.iso-play-chapter,.iso-play-count{color:var(--ip-muted);font-size:12px;font-weight:500}\n.iso-play-count{margin-left:auto;white-space:nowrap}\n.iso-play-text{max-width:80ch}\n.iso-play-text a{color:inherit}\n.iso-play-code{margin:6px 0 0;padding:6px 10px;border-radius:8px;background:var(--ip-code);font:12px/1.5 ui-monospace,Menlo,monospace;white-space:pre-wrap;overflow-wrap:anywhere}\n.iso-play-facts{display:flex;flex-wrap:wrap;gap:2px 16px;margin:6px 0 0;font-size:12px}\n.iso-play-facts dt{color:var(--ip-muted)}\n.iso-play-facts dd{margin:0 8px 0 -10px;font-weight:600}\n.iso-play-list{padding:0 12px 10px;font-size:13px}\n.iso-play-list summary{color:var(--ip-muted);cursor:pointer}\n.iso-play.frozen>:not(.iso-play-stage){display:none}\n@container iso-play (max-width:420px){.iso-play-time{display:none}.iso-play-row{flex-wrap:wrap}.iso-play-bar{flex-basis:100%;order:9}}\n";

Played type play

what is played: a drawing, painted as the timeline says; or one that paints itself, at each time asked (in any order), as two drawings being compared do. What it changes is its own to put back

type Played = Pick<CompiledScene, 'rendered' | 'id'> & {
    paint?(svg: SVGSVGElement, ms: number): void;
};

Player interface play

interface Player {
    readonly root: HTMLElement;
    readonly transport: Transport;
    /** another drawing, or another document: the place is kept (transport's rebind). Faults are refused, and what plays goes on */
    set(scene: Played, timeline?: Timeline, mode?: 'light' | 'dark'): boolean;
    /** show one moment, still: no clock, no controls (a screenshot, a link) */
    freeze(ms: number): void;
    /** to a beat and through it, stopping before the next */
    step(beat: number): void;
    dispose(): void;
}

PlayerOptions interface play

interface PlayerOptions {
    scene: Played;
    /** none: the drawing alone, with nothing to play */
    timeline?: Timeline;
    /** what a screen reader calls it */
    label?: string;
    /** the controls and the commentary (default true): without them, the drawing alone */
    controls?: boolean;
    /** start at once, or each time most of it is in view (default: neither) */
    autoplay?: boolean | 'visible';
    loop?: boolean;
    rate?: number;
    …
}

attr const still

const attr: (t: VNode, k: string) => string | undefined;

cls const still

const cls: (t: VNode) => string[];

extent function still

every point a tree draws (polygon points, rects, circles), for the overlay's extent

function extent(ts: (VNode | string)[]): Box | undefined;

fitWithOverlay function still

The scale that fits the drawing and its overlay. The overlay's badges keep their size in px, so it is drawn at a scale, measured, and drawn again at the scale that holds both (twice: the scale it ends at is the one it is drawn at).

function fitWithOverlay(drawn: Box, size: {
    width: number;
    height: number;
    pad: number;
}, paint: (k: number) => (VNode | string)[]): {
    k: number;
    box: Box;
    live: (string | VNode)[];
};

n const still

const n: (v: number) => string;

node const still

const node: (name: string, attrs?: Record<string, string | number>, ...children: (VNode | string)[]) => VNode;

prune function still

keep a node? (for thumbs: no text, no titles, no small things, no badges)

function prune(t: VNode | string, drop: (n: VNode) => boolean): VNode | string | undefined;

rewrite function still

"var(--x)" → "var(--iso-x)" (the drawing's tokens, as the stylesheet names them); "#id" → the prefixed id

function rewrite(t: SvgNode | VNode | string, pfx: string): VNode | string;

unite const still

const unite: (a: Box, b?: Box) => Box;

AnyTimeline interface timeline-contract

any domain's (the generic code's own view)

interface AnyTimeline extends TimelineTypes {
    kind: string;
    state: unknown;
    flag: never;
    links: Record<string, string | undefined>;
}

AstTerm interface timeline-contract

a term: any of its matches (the same field twice ORs), or none of them when not

interface AstTerm<T extends TimelineTypes = AnyTimeline> {
    not?: true;
    any: Match<T>[];
}

AttrValue type timeline-contract

an attribute's value: a scalar, never an object; a string is one short line

type AttrValue = string | number | boolean | null;

Bin type timeline-contract

type Bin = typeof BINS[number];

BIN_MS const timeline-contract

a bin's nominal width (a local day may be 23 or 25 hours long)

const BIN_MS: Record<Bin, number>;

BINS const timeline-contract

const BINS: readonly ['1m', '1h', '1d'];

Catalog interface timeline-contract

interface Catalog<T extends TimelineTypes = AnyTimeline> {
    timeline: 1;
    type: 'catalog';
    /** display names, chosen by the host per machine, %-escaped in a scope: never a real hostname */
    hosts: string[];
    sources: SourceInfo<T>[];
    retention: EffectiveRetention[];
    /** labels, flags and renames */
    names?: ScopeName<T>[];
    /** the host's now: the live edge */
    now: number;
}

Days type timeline-contract

days kept; null: kept until the user deletes it

type Days = number | null;

EffectiveRetention interface timeline-contract

The effective retention, per source, as the user set it: the UI says "kept 30 days" and greys out what's gone.

interface EffectiveRetention extends Retention {
    source: string;
    /** user: set by the user; default: the host's default */
    setBy: 'user' | 'default';
    /** the earliest t still kept, for single events and for each bin (absent: nothing kept yet) */
    keptFrom: {
        events?: number;
        rollups: Partial<Record<Bin, number>>;
    };
}

EventBin interface timeline-contract

events over one bin, on one row: how the zoomed-out view draws count bars and heat strips

interface EventBin {
    /** the row's scope */
    scope: Scope;
    t: number;
    bin: Bin;
    count: number;
    /** count by severity (absent keys are 0) */
    severity: Partial<Record<Severity, number>>;
    /** count by kind, for the kinds present (a host may give only the top few, and say so with kindsTruncated: then the
     *  kind counts of a coarser bin can't be made from it) */
    kinds?: Record<string, number>;
    kindsTruncated?: boolean;
}

Filters interface timeline-contract

interface Filters {
    source?: string[];
    kind?: string[];
    severity?: Severity[];
    /** scope prefixes (segment-wise: a prefix matches it and everything under it) */
    scope?: Scope[];
}

KindInfo interface timeline-contract

interface KindInfo {
    name: string;
    title: string;
    /** a span (it has a dur, or is open) */
    span?: boolean;
    /** named, not yet recorded */
    notYet?: boolean;
}

Match type timeline-contract

one test of an event

type Match<T extends TimelineTypes = AnyTimeline> = {
    field: 'text';
    value: string;
} | {
    field: 'kind' | 'source';
    value: string;
    prefix?: true;
} | {
    field: 'severity';
    op: 'eq' | 'ge' | 'gt' | 'le' | 'lt';
    value: Severity;
} | {
    …
};

MetricPoint interface timeline-contract

one sample of a series, at t (a later batch with the same series, scope and t replaces it)

interface MetricPoint {
    series: string;
    scope: Scope;
    t: number;
    value: number;
}

MetricRollup interface timeline-contract

a series over one bin [t, t + bin): what a coarser bin is made of (min of mins, max of maxes, sums of sums and counts)

interface MetricRollup {
    series: string;
    scope: Scope;
    t: number;
    bin: Bin;
    min: number;
    max: number;
    sum: number;
    count: number;
}

Query interface timeline-contract

interface Query<T extends TimelineTypes = AnyTimeline> {
    timeline: 1;
    type: 'query';
    scope: Scope;
    /** rows: the scopes this many levels below scope (0: one row, the scope itself) */
    depth: number;
    /** [from, to), ms; since: and before: already applied */
    from: number;
    to: number;
    /** binned: bins and rollups; absent: single events and points */
    bin?: Bin;
    /** the owner's time zone (IANA, e.g. "Australia/Sydney"): 1d bins start at its midnight, and 1h bins on its hour
    …
}

Retention interface timeline-contract

interface Retention {
    /** single events (and raw metric points) */
    events: Days;
    /** rollups, by bin */
    rollups: Record<Bin, Days>;
}

Row type timeline-contract

A row the component draws: one scope at the query's depth, with its name's flags. Events at a shallower scope than the rows go on their own scope's row, marked own.

type Row<T extends TimelineTypes = AnyTimeline> = {
    scope: Scope;
    /** the last segment's name, or the catalogue's label */
    label: string;
    kind: T['kind'] | 'fleet';
    /** levels below the query's scope */
    depth: number;
    own?: boolean;
    /** scopes one level below this row (the component offers to drill in when > 0) */
    children: number;

Scope type timeline-contract

a scope path: "kind:name" segments, outermost first, joined by "/"; the fleet is ""

type Scope = string;

ScopeName type timeline-contract

A scope's display: its label, the domain's flags, and the scopes it was known as before a rename (their history shows on its row).

type ScopeName<T extends TimelineTypes = AnyTimeline> = {
    scope: Scope;
    label: string;
    aliases?: Scope[];
} & {
    [F in T['flag']]?: boolean;
};

SearchAst interface timeline-contract

every term (different fields AND); since: and before: aren't here: they narrow the query's from and to

interface SearchAst<T extends TimelineTypes = AnyTimeline> {
    all: AstTerm<T>[];
}

SEGMENT_NAME const timeline-contract

a segment's name: no "/", ":", "%" or whitespace, except %-escaped (%2F, %3A, %25, %20)

const SEGMENT_NAME = "(?:[^/:%\\s]|%[0-9A-F]{2})+";

SeriesInfo interface timeline-contract

interface SeriesInfo<T extends TimelineTypes = AnyTimeline> {
    name: string;
    /** e.g. "count", "bytes", "ms", "%" */
    unit: string;
    /** counter: a count per sample, shown as sums only (its mean is meaningless); gauge: a level, shown as its min/max
     *  band and mean */
    type: 'counter' | 'gauge';
    /** the scope kind a series is recorded at */
    at: T['kind'];
    title: string;
}

SEVERITIES const timeline-contract

const SEVERITIES: readonly ['debug', 'info', 'notice', 'warning', 'error'];

Severity type timeline-contract

type Severity = typeof SEVERITIES[number];

SourceInfo interface timeline-contract

interface SourceInfo<T extends TimelineTypes = AnyTimeline> {
    name: string;
    title: string;
    /** kept: the host records it today; not-yet: named in the contract, not yet recorded (the UI lists it, greyed) */
    status: 'kept' | 'not-yet';
    /** the scope kinds its events and series are recorded at */
    at: T['kind'][];
    kinds: KindInfo[];
    /** kinds taken verbatim from the host's own names: any kind matching this (the listed kinds are the known ones) */
    kindPattern?: string;
    series: SeriesInfo<T>[];
    /** the attrs its events may carry */
    …
}

TIMELINE_VERSION const timeline-contract

const TIMELINE_VERSION = 1;

TimelineEvent interface timeline-contract

One thing that happened, at t (or over [t, t + dur) for a span).

interface TimelineEvent<T extends TimelineTypes = AnyTimeline> {
    /** unique within its source and stable: the same record, the same id (a later batch with this id replaces it) */
    id: string;
    /** when, in ms since 1970-01-01T00:00:00Z */
    t: number;
    /** a span's length in ms (so far, while open); absent for a mark */
    dur?: number;
    /** an ongoing span: it lasts to now (its dur, if any, is so far); a later batch gives its end */
    open?: true;
    scope: Scope;
    /** one of the catalogue's sources */
    source: string;
    …
}

TimelineTypes interface timeline-contract

what a domain fills in

interface TimelineTypes {
    /** its scope kinds */
    kind: string;
    /** what a recorded frame holds */
    state: unknown;
    /** the boolean flags a scope's name (and its row) may carry */
    flag: string;
    /** the links an event may carry: each an id, never a text */
    links: object;
}

memorySource function timeline-engine

function memorySource(rec: Recording, cat: TimelineCatalog, o?: MemorySourceOptions): MemorySource;

MemorySource interface timeline-engine

interface MemorySource extends TimelineSource {
    /** new or changed records, and the host's now: subscribers get them as a batch (an id, or a series, scope and t,
     *  given again replaces the first) */
    append(events: TimelineEvent[], metrics?: (MetricPoint | MetricRollup)[], now?: number): void;
    /** the user's retention for a source (what the host's settings would do) */
    setRetention(source: string, r: Retention): void;
    readonly now: number;
    readonly size: {
        events: number;
        samples: number;
    };
}

MemorySourceOptions interface timeline-engine

interface MemorySourceOptions {
    /** the host's now (default: the recording's catalog.now) */
    now?: number;
    /** the state at t, where one was recorded (frames), as the timeline may show it */
    stateAt?(scope: Scope, t: number): Promise<unknown>;
}

toCSV function timeline-export

CSV: the base columns, then attr.* and link.* columns for every key present (spreadsheet formulas defused)

function toCSV<T extends TimelineTypes = AnyTimeline>(events: TimelineEvent<T>[], sensitive?: Iterable<string>): string;

toJSON function timeline-export

sensitive: "source.attr" names to leave out

function toJSON<T extends TimelineTypes = AnyTimeline>(events: TimelineEvent<T>[], sensitive?: Iterable<string>): string;

Cut interface timeline-scale

interface Cut extends Gap {
    x0: number;
    x1: number;
    weight: number;
}

findGaps function timeline-scale

The gaps of [t0, t1): activity intervals are [a, b) (a mark is [t, t]); a gap is a stretch between them (or between the range's edges and them) longer than minFrac of the range and than minMs.

function findGaps(activity: [number, number][], t0: number, t1: number, o?: {
    minFrac?: number;
    minMs?: number;
}): Gap[];

Gap interface timeline-scale

interface Gap {
    from: number;
    to: number;
}

gapKey const timeline-scale

weights: how far each gap is expanded (0: a cut; 1: its own width in time), by gapKey

const gapKey: (g: Gap) => string;

gapLabel function timeline-scale

"14 h", "2 d 3 h", "45 min"

function gapLabel(ms: number): string;

Tick interface timeline-scale

interface Tick {
    t: number;
    x: number;
    label: string;
    major: boolean;
}

ticks function timeline-scale

round times at least minPx apart, in the owner's zone (local hours and days), skipping the cuts

function ticks(s: TimeScale, tz?: string, minPx?: number): Tick[];

timeScale function timeline-scale

function timeScale(t0: number, t1: number, width: number, gaps?: Gap[], o?: {
    cut?: number;
    weights?: Map<string, number>;
}): TimeScale;

TimeScale interface timeline-scale

interface TimeScale {
    t0: number;
    t1: number;
    width: number;
    cuts: Cut[];
    x(t: number): number;
    /** the time at x; inside a cut, its nearer edge */
    t(x: number): number;
    /** the cut at x, if any */
    cutAt(x: number): Cut | undefined;
    /** visible ms per px outside the cuts */
    msPerPx: number;
}

crumbs function timeline-scope

breadcrumbs: the fleet, then each prefix

function crumbs(s: Scope): {
    scope: Scope;
    label: string;
    kind: string;
}[];

escapeName const timeline-scope

a name, escaped for a segment

const escapeName: (n: string) => string;

formatScope const timeline-scope

const formatScope: (segs: Segment[]) => Scope;

hasSegment const timeline-scope

any segment equal to seg ("kind:name")

const hasSegment: (s: Scope, seg: string) => boolean;

join const timeline-scope

const join: (parent: Scope, kind: string, name: string) => Scope;

kindOf const timeline-scope

const kindOf: (s: Scope) => string;

levelOf const timeline-scope

levels below the fleet

const levelOf: (s: Scope) => number;

nameOf const timeline-scope

const nameOf: (s: Scope) => string;

parentOf const timeline-scope

const parentOf: (s: Scope) => Scope;

prefixAt function timeline-scope

the scope's prefix at a level (itself when it is shallower)

function prefixAt(s: Scope, level: number): Scope;

scopeRules function timeline-scope

what a path of this catalogue may say: isScope, parseScope (its segments, names unescaped; throws on a path that isn't one), and wellNested (each segment may sit in its parent's kind)

function scopeRules(cat: Pick<TimelineCatalog, 'kinds' | 'parents'>): {
    isScope: (s: string) => boolean;
    parseScope: (s: Scope) => Segment[];
    wellNested: (s: Scope) => boolean;
};

Segment interface timeline-scope

interface Segment {
    kind: string;
    name: string;
}

within const timeline-scope

segment by segment: a prefix matches itself and everything under it

const within: (s: Scope, prefix: Scope) => boolean;

BASE_FIELDS const timeline-search

the fields every domain's search has; its link fields follow

const BASE_FIELDS: readonly ['kind', 'source', 'severity', 'scope', 'since', 'before'];

Field type timeline-search

type Field = string;

highlights function timeline-search

where the free text (positive terms) hits a line: [start, end) ranges, merged, in order

function highlights(p: ParsedSearch, line: string): [number, number][];

ParsedSearch interface timeline-search

interface ParsedSearch {
    terms: Term[];
    warnings: string[];
}

rangeOf function timeline-search

the range since: and before: narrow [from, to) to (never wider)

function rangeOf(p: ParsedSearch, from: number, to: number): {
    from: number;
    to: number;
};

readTime function timeline-search

a time: 15m, 2h, 3d, 1w back from now; or a date or date-time, local unless it has a zone

function readTime(v: string, now: number): number | undefined;

Search type timeline-search

type Search = ReturnType<typeof searchFor>;

SearchDialect type timeline-search

type SearchDialect = Pick<TimelineCatalog, 'links' | 'linkMatch' | 'topKinds'>;

searchFor function timeline-search

The search language of one domain: its fields (the base ones, then its links), and - parseSearch: the query, read; - toAst: the parse, as a query carries it; - compileSearch: what the component sends: the parse, the range narrowed by since: and before:, and what couldn't be read; - matchAst: the parsed search (as a query carries it) as a test of one event (sensitive: "source.attr" names free text never looks in); - matcher: the search as typed, as a test of one event.

function searchFor(d: SearchDialect): {
    FIELDS: string[];
    parseSearch: (q: string, now?: number) => ParsedSearch;
    toAst: (p: ParsedSearch) => SearchAst;
    compileSearch: (q: string, now: number, from: number, to: number) => {
        where: SearchAst;
        from: number;
        to: number;
        warnings: string[];
    };
    matchAst: (ast: SearchAst | undefined, sensitive?: Iterable<string>) => (e: TimelineEvent) => boolean;
    matcher: (p: ParsedSearch, sensitive?: Iterable<string>) => (e: TimelineEvent) => boolean;
};

severities const timeline-search

a severity filter as a set (for facets)

const severities: (min: Severity) => ("debug" | "error" | "info" | "notice" | "warning")[];

Term interface timeline-search

interface Term {
    neg: boolean;
    /** absent: free text */
    field?: Field;
    /** severity only */
    op?: '=' | '>=' | '>' | '<=' | '<';
    value: string;
    /** since and before: the time read (ms) */
    time?: number;
}

binNext function timeline-time

the start of the next bin after a bin starting at s

function binNext(s: number, tz?: string, bin?: Bin): number;

binStart function timeline-time

the start of the bin t falls in

function binStart(t: number, bin: Bin, tz?: string): number;

isZone const timeline-time

const isZone: (tz: string) => boolean;

offsetAt function timeline-time

the zone's offset from UTC at t, in ms (UTC, or an unknown zone: 0)

function offsetAt(tz: string | undefined, t: number): number;

pageClock function transport

the page's clock: frames, and a timer behind them, so it also goes on where no frames are drawn (a page not shown)

function pageClock(): TransportClock;

transport function transport

function transport(tl0: Timeline, o?: TransportOptions): Transport;

Transport interface transport

interface Transport {
    readonly timeline: Timeline;
    readonly duration: number;
    /** T, ms */
    readonly time: number;
    /** A, ms, or 'off' when it never ran: what at()'s `ambient` takes */
    readonly ambientTime: number | 'off';
    readonly playing: boolean;
    readonly beat: BeatInfo | undefined;
    readonly cue: Cue | undefined;
    rate: number;
    loop: boolean;
    …
}

TransportClock interface transport

interface TransportClock {
    /** ms, going only forward */
    now(): number;
    /** call f soon, once: the next frame; returns what cancel takes */
    next(f: () => void): unknown;
    cancel(id: unknown): void;
}

TransportEvents interface transport

interface TransportEvents {
    /** the drawing is to be painted again: T (ms), and why */
    time: (ms: number, why: 'play' | 'ambient' | 'seek' | 'rebind') => void;
    play: () => void;
    pause: () => void;
    /** it came to its end and stopped (not at each turn of a loop: that is 'loop') */
    end: () => void;
    loop: () => void;
    /** a beat begins: each one passed, in order, while playing; the one landed in, after a seek or a rebind. `at`: where in the timeline it starts, ms */
    beat: (beat: BeatInfo, how: 'play' | 'seek' | 'rebind') => void;
    ambient: (on: boolean) => void;
    rate: (rate: number) => void;
}

TransportOptions interface transport

interface TransportOptions {
    /** start again at the end (default false) */
    loop?: boolean;
    /** how fast (default 1) */
    rate?: number;
    /** default: the document's own */
    ambient?: 'on' | 'off';
    clock?: TransportClock;
}

isoVars const view-css

--name → --iso-name, in declarations and in var() alike

const isoVars: (css: string) => string;

scope function view-css

Scope a stylesheet: every rule under the root class; keyframes renamed iso-*; at-rules kept with their rules scoped.

function scope(css: string, root: string, stateRoot: string): string;

scopeSelector function view-css

One selector under the root class. :root (the theme's tokens) becomes the root class itself; any state it names (data-theme: light or dark) is stateRoot's (the element the theme is set on), not the page's.

function scopeSelector(sel: string, root: string, stateRoot: string): string;

MIN_ZOOM const viewport

const MIN_ZOOM = 0.1, MAX_ZOOM = 8;

View type viewport

type View = {
    x: number;
    y: number;
    w: number;
    h: number;
};

viewport function viewport

function viewport(host: HTMLElement, o: ViewportOpts): {
    /** the view (the drawing's units): set by a pan or a reveal, then applyView(). None: it starts again, and there is nothing the person has moved */
    view: View | undefined;
    /** the scene's whole frame */
    full: View | undefined;
    /** the person has moved the view since the last fit */
    readonly moved: boolean;
    /** the zoom the view was last applied at */
    readonly zoom: number;
    /** the marks were drawn at this zoom (0: none drawn) */
    painted(k: number): void;
    size: () => {
    …
};

Viewport type viewport

type Viewport = ReturnType<typeof viewport>;

ViewportOpts interface viewport

interface ViewportOpts {
    /** the drawing on the stage (its viewBox is the view), if any */
    svg(): SVGSVGElement | undefined;
    /** after each change of the view, at its zoom (pixels per unit): the host's zoom readout */
    onApply(k: number): void;
    /** the marks drawn at another zoom: draw them again */
    onRezoom(): void;
    /** what a fit frames (the drawing's own things, the overlay's shown marks), if not the whole scene */
    itemsBox(): View | undefined;
    /** (0.12.6) what must be on the stage too when the things are fitted (the connectors), a few px from its edges */
    alsoBox?(): View | undefined;
    /** how far out and in it goes (default: MIN_ZOOM and MAX_ZOOM) */
    …
}

editor src/iso-editor

import { editor } from '@johnoscott/isometric-engine/editor';
import { … } from '@johnoscott/isometric-engine/modules/iso-editor/MODULE';

ConnectPlan interface adapter

(0.10.0) what a connection drawn on the canvas writes: a value added to a list (at), or, with name (a base for a fresh one), to a map

interface ConnectPlan {
    at: Path;
    value: unknown;
    name?: string;
    label?: string;
}

DomainAdapter interface adapter

interface DomainAdapter {
    /** the format it reads ("boxes/1") */
    id: string;
    role(text: string): FileRole;
    /** the JSON Schema for a role (completion, hover, the properties panel); `text` (0.8.0) is the file's, for a format whose
     *  version line picks its schema (the same object for the same schema: the editor keeps one navigator per object) */
    schema(role: FileRole, text?: string): object;
    /** the problems in a text, from the domain's reader (with the files it extends, as the host resolved them) */
    read(text: string, o: {
        fileName: string;
        defaults?: {
            name: string;
    …
}

FileRole type adapter

what a file is to the domain: its main kind, a base that files extend, or something else

type FileRole = 'main' | 'base' | 'other';

GroupPlan interface adapter

(0.10.0) the selection made into a new container: where it goes (at, a map), the base of its fresh name, its value, and, given the name it got, what changes in each member (each a set)

interface GroupPlan {
    at: Path;
    name: string;
    value: unknown;
    members(name: string): {
        path: Path;
        value: unknown;
    }[];
    label?: string;
}

ObjectKindInfo interface adapter

one kind of thing a file holds, by name, in a map of its own (its section)

interface ObjectKindInfo {
    /** the kind's name (what references target) */
    kind: string;
    /** where its entries live: their map's path */
    section: Path;
    /** what one is called ("node"), and its group in the outline ("Nodes") */
    singular: string;
    group: string;
    /** what a new one starts as */
    template(): unknown;
    /** whether the outline offers the section where the file has none (default: yes) */
    when?(data: Record<string, unknown>): boolean;
}

ObjectRef interface adapter

a thing at a pointer: its kind, its name and its own pointer

interface ObjectRef {
    kind: string;
    name: string;
    path: string;
}

ReadOutcome interface adapter

what the domain's reader says of a text

interface ReadOutcome {
    diags: Diag[];
    /** each object's tag (the outline shows it), by name */
    tags?: Map<string, string>;
    /** the domain's own reading, for its views */
    read?: unknown;
}

Ref interface adapter

interface Ref {
    /** the JSON pointer of the value (or of the key, for key slots) */
    path: string;
    slot: RefSlot;
    value: string;
    /** the name it refers to, if it refers to one */
    name?: string;
}

RefSlot interface adapter

a place in a file whose value names another thing

interface RefSlot {
    /** path segments; '*' is any name, '#' any list index */
    at: string[];
    /** the kinds a value here may name */
    targets: string[];
    /** words that are allowed here and aren't names */
    extra?: string[];
    /** the name inside a value, or undefined when the value names nothing */
    name?(value: string): string | undefined;
    /** the value with its name replaced */
    rename?(value: string, to: string): string;
    /** what the completion list shows for a name */
    …
}

Clipboard type clipboard

type Clipboard = ReturnType<typeof clipboardFor>;

clipboardFor function clipboard

The clipboard, for one domain.

function clipboardFor(a: ClipboardAdapter): {
    copyText: (text: string, paths: Path[]) => {
        text: string;
        what: string;
    } | undefined;
    pasteCmd: (text: string, clip: string, selection?: Path[]) => PastePlan;
    cutCmd: (text: string, paths: Path[]) => {
        text: string;
        cmd: Command;
    } | undefined;
};

PastePlan interface clipboard

What a paste would do, described (for the menu), or why it can't.

interface PastePlan {
    cmd?: Command;
    what: string;
    names?: Map<string, string>;
    error?: string;
}

chain function commands

Run several splices one after the other, each against the text the previous one left.

function chain(text: string, parts: ((t: string) => Splice)[]): Splice;

Commands type commands

type Commands = ReturnType<typeof commandsFor>;

commandsFor function commands

The commands, for one domain.

function commandsFor(a: CommandsAdapter): {
    describe: (p: Path) => string;
    setCmd: (path: Path, value: unknown, label?: string) => Command;
    pinsCmd: (pins: [string, [number, number]][], label: string) => Command;
    withPinsMoved: (cmd: Command) => Command;
    insertCmd: (mapPath: Path, key: string, value: unknown, opts?: {
        after?: string;
        before?: string;
        label?: string;
    }) => Command;
    insertItemCmd: (listPath: Path, value: unknown, index?: number, label?: string) => Command;
    moveCmd: (path: Path, before?: string) => Command;
    …
};

seqCmd function commands

Several commands as one: each built against the text the one before left; one undo step.

function seqCmd(label: string, cmds: Command[]): Command;

complete function complete

function complete(d: EditorDoc, offset: number, nav: SchemaNav, a: CompleteAdapter): Completion;

Completion interface complete

interface Completion {
    items: Item[];
    start: number;
    path: Path;
    context: 'key' | 'value' | 'item';
}

Item interface complete

interface Item {
    label: string;
    /** text to insert (a Monaco snippet when `snippet`) */
    insert: string;
    kind: 'key' | 'value' | 'ref' | 'snippet';
    detail?: string;
    /** Markdown */
    doc?: string;
    snippet?: boolean;
    /** sorts before the rest */
    preferred?: boolean;
}

namesIn function complete

the names declared in a kind's section

function namesIn(d: EditorDoc, k: ObjectKindInfo): string[];

At interface doc

interface At {
    path: Path;
    where: Where;
    node?: YNode;
}

completionContext function doc

What the caret is completing. In a block map the parent is found by indentation (an empty line has no node); after "key: " it is that key's value; in a "- " item or a [ … ] list, an item of that list; inside { … } a key of that map.

function completionContext(d: EditorDoc, offset: number): CompletionContext;

CompletionContext interface doc

interface CompletionContext {
    /** the path of the map a key is being typed in, or of the value being typed */
    path: Path;
    kind: 'key' | 'value' | 'item';
    /** the word typed so far, and where it starts */
    prefix: string;
    start: number;
    /** a flow collection ({ … } or [ … ]): keys are written inline */
    flow: boolean;
}

EditorDoc class doc

class EditorDoc {
    readonly text: string;
    readonly doc: Document.Parsed;
    readonly lines: LineCounter;
    constructor(text: string);
    get ok(): boolean;
    get data(): unknown;
    /** 1-based line and column of an offset */
    pos(offset: number): {
        line: number;
        col: number;
    };
    …
}

Where type doc

type Where = 'key' | 'value' | 'inside';

LoggedStep interface history-log

A step of the history as data a host can keep (JSON): what undo and redo need, and what a host sees of it.

interface LoggedStep {
    readonly id: number;
    readonly label: string;
    readonly origin: Origin;
    readonly meta?: StepMeta;
    readonly touched?: readonly (readonly (string | number)[])[];
    /** its steps, each against the text the one before produced; and their inverses, in the order they undo */
    readonly steps: readonly Step[];
    readonly inverse: readonly Step[];
    /** when it was made or last joined (the model's clock, ms) */
    readonly time: number;
    /** the selected paths before and after it (the text pane's own selection is not kept: it is the pane's) */
    …
}

restoreLog function history-log

Give a kept history back to the model's text: only when the text's hash is the log's, and only when every step, undone and redone on a copy, gives the text back exactly; else nothing changes and it says why. The text is clean after it (a host restores what it has just read) unless clean: false (RestoreOptions), steps beyond the model's depth are left out, oldest first, and new steps' ids follow the log's.

function restoreLog(m: EditorModel, log: unknown, opts?: RestoreOptions): {
    ok: true;
    steps: number;
} | {
    ok: false;
    why: string;
};

RestoreOptions interface history-log

How restoreLog marks the text: by default clean (a host restores what it has just read from its file). (0.30.0) clean: false for a text that isn't what was saved (a draft kept in the browser): it opens unsaved; with cleanAt, the hash (textHash) of the text that is saved, the text is clean again when undo or redo reaches that text, as if it had been saved there.

interface RestoreOptions {
    readonly clean?: boolean;
    readonly cleanAt?: string;
}

revisionLog function history-log

The model's history as data to keep beside its text (JSON), for restoreLog after a reload. The text pane's selections are not in it.

function revisionLog(m: EditorModel): RevisionLog;

RevisionLog interface history-log

The history of a text, to keep beside it and give back after a reload.

interface RevisionLog {
    readonly format: 'iso-editor-history/1';
    /** a hash of the text it belongs to (53 bits and the length, as hex): restoreLog takes it only for that text */
    readonly hash: string;
    /** what undo goes back through, oldest first; what redo goes forward through, the next one last */
    readonly undo: readonly LoggedStep[];
    readonly redo: readonly LoggedStep[];
}

textHash function history-log

a text's hash for a history (cyrb53, and the length): says whether a text is the one a history was kept with. Not for secrets: restoreLog also proves every step against the text

function textHash(t: string): string;

ApplyOptions interface model

interface ApplyOptions {
    /** the id of an undo step it is part of, where it can be (see apply) */
    joins?: number;
    /** what the host says of the step. One that is joined keeps its own only where this says the same: otherwise it is the step of two */
    meta?: StepMeta;
}

Change interface model

What a view needs to know about a change.

interface Change {
    /** (0.33.0) 'history': the undo and redo history was put in place (restoreLog); the text is as it was, so no steps */
    kind: 'do' | 'undo' | 'redo' | 'load' | 'history';
    origin: Origin;
    label: string;
    /** the steps, in order, each against the text the one before produced */
    steps: Step[];
    version: number;
    /** the text selection to put back (undo/redo of typing), opaque to the model */
    textSel?: unknown;
    /** typing: which text pane typed it (each pane skips only its own; another pane takes it like any change) */
    source?: string;
    …
}

Command interface model

interface Command {
    /** for the menu and the undo button's tooltip: "Delete node web" */
    label: string;
    /** the change, worked out against the text it will apply to */
    build(text: string): Splice;
    /** the paths it touched (for the views to refresh and reveal) */
    touched?: Path[];
    /** (0.12.5) the label of the step it joined (apply's `joins`), given the step's own */
    joined?(label: string): string;
    /** where a path is after the change (a rename moves paths); null when it no longer exists */
    remap?(p: Path): Path | null;
    /** the selection afterwards (default: the old one, remapped) */
    select?: Path[];
}

EditorModel class model

class EditorModel {
    private _text;
    private _doc;
    private _version;
    private undoStack;
    private redoStack;
    private nextId;
    private cleanId;
    private listeners;
    private selListeners;
    private _good;
    /** the selected paths (tree, canvas, properties) */
    …
}

HISTORY_DEPTH const model

const HISTORY_DEPTH = 500;

HistoryEntry interface model

A step of the history, as a host sees it: made anew at each reading (compare ids, not objects). Its id is never another step's, and is kept by undo and redo.

interface HistoryEntry {
    readonly id: number;
    readonly label: string;
    readonly origin: Origin;
    readonly meta?: StepMeta;
    /** (0.22.1) the paths its command said it touched, each once (a joined step: all of them); none for typing, nor for a whole text put in */
    readonly touched?: readonly (readonly (string | number)[])[];
}

Origin type model

type Origin = 'text' | 'tree' | 'canvas' | 'props' | 'menu' | 'api' | 'history' | 'file';

SelectionChange interface model

The selection changed, and which view changed it (a view doesn't react to its own).

interface SelectionChange {
    paths: Path[];
    origin: Origin;
}

StepMeta type model

What a host says of a step, kept with it through undo and redo. The model reads none of it.

type StepMeta = Readonly<Record<string, string>>;

flatten function outline

Every node, depth first (for search and keyboard).

function flatten(n: OutlineNode, out?: OutlineNode[]): OutlineNode[];

NodeKind type outline

type NodeKind = 'root' | 'group' | 'resource' | 'key' | 'item';

outline function outline

@param tags the reader's tags by object name (with the base files merged), when known; without them an object's tag is the adapter's, from this file alone

function outline(d: EditorDoc, a: OutlineAdapter, role?: FileRole, tags?: Map<string, string>): OutlineNode;

OutlineNode interface outline

interface OutlineNode {
    /** the JSON Pointer of the node's path (unique) */
    id: string;
    path: Path;
    kind: NodeKind;
    label: string;
    /** a scalar's text, as written */
    value?: string;
    shape: 'map' | 'list' | 'scalar' | 'missing';
    /** for an object and its group: its kind */
    section?: string;
    /** for an object: its tag (the reader's, else the adapter's from this file) */
    …
}

fromPointer function path

function fromPointer(ptr: string): Path;

isPrefix const path

const isPrefix: (a: Path, b: Path) => boolean;

parentOf const path

const parentOf: (p: Path) => Path | undefined;

Path type path

type Path = Seg[];

samePath const path

const samePath: (a: Path, b: Path) => boolean;

Seg type path

type Seg = string | number;

toPointer const path

const toPointer: (p: Path) => string;

readPins function pins

Each pinned name and where it is, in the file's order; one that isn't a pin is left out.

function readPins(data: unknown, key?: string): ReadonlyMap<string, readonly [number, number]>;

cmSnippet function providers

Completion's snippets are written in Monaco's syntax (${1:name}, ${2|a,b|}, ${0}). CodeMirror's has fields (${1:name}, ${}) but no choices: a choice becomes a field holding its first option (the others are offered as values once the caret is there), and the final ${0} an empty field.

function cmSnippet(monaco: string): string;

docFor function providers

function docFor(text: string): EditorDoc;

mdRuns function providers

The Markdown a hover or completion carries, as runs of text: plain, bold or code, in paragraphs (never markup).

function mdRuns(md: string): {
    kind: 'text' | 'bold' | 'code';
    text: string;
}[][];

problemRange function providers

A problem's range as offsets into the text (its lines and columns are 1-based), clamped to the text.

function problemRange(text: string, p: Pick<Problem, 'startLine' | 'startCol' | 'endLine' | 'endCol'>): [number, number];

Providers type providers

type Providers = ReturnType<typeof providersFor>;

providersFor function providers

What the text panes ask, for one domain: completion, hover and go to definition, and the schema navigator for a text (the main one, or a base file's).

function providersFor(a: ProvidersAdapter): {
    navFor: (text: string) => SchemaNav;
    completionAt: (d: EditorDoc, offset: number) => {
        from: number;
        items: Item[];
    };
    hoverAt: (d: EditorDoc, offset: number) => {
        from: number;
        to: number;
        parts: string[];
    } | null;
    definitionAt: (d: EditorDoc, offset: number) => {
    …
};

rangeOfPath function providers

Where a path is drawn in the text, to mark it: its whole pair, else its value.

function rangeOfPath(d: EditorDoc, p: Path): [number, number] | undefined;

KeyInfo interface schema-nav

interface KeyInfo {
    name: string;
    /** Markdown */
    doc?: string;
    /** the value's shape, for the text inserted after "key:" */
    shape: 'map' | 'list' | 'scalar';
    enumValues: string[];
    examples: unknown[];
}

SchemaNav class schema-nav

class SchemaNav {
    private root;
    private defs;
    constructor(schema: object);
    /** a schema with its $ref and anyOf/allOf branches spread out (each branch is a candidate) */
    private spread;
    /** The candidate schemas at a path. A name in a section map matches additionalProperties; x-* keys match nothing useful. */
    at(path: Path): J[];
    /** The keys a map at this path may have (not counting x-*), given what the map holds now. */
    keys(path: Path, present?: J): KeyInfo[];
    private info;
    /** The words a value at this path may be: enum values, consts, true/false. */
    …
}

applyStep function splice

Apply one step's edits (non-overlapping) to a text.

function applyStep(text: string, step: Step): string;

deleteAt function splice

Remove the entry at a path: a key and its value (with its own comment lines), or a list item.

function deleteAt(text: string, path: Path): Splice;

flowText function splice

A value inline, in flow style: { a: 1, b: [x, y] }

function flowText(v: unknown): string;

insertItem function splice

Add an item to the list at a path, at an index (default: the end).

function insertItem(text: string, listPath: Path, value: unknown, index?: number, order?: readonly string[]): Splice;

insertKey function splice

Add key: value to the map at a path (creating the map, and its parents, when missing). order: the format's top-level key order, for where a new top-level key goes (the adapter's topOrder).

function insertKey(text: string, mapPath: Path, key: string, value: unknown, opts?: {
    after?: string;
    before?: string;
    order?: readonly string[];
}): Splice;

insertRawPair function splice

Add a pair given as source text ("key: value", with its own comments, at indent 0) to the map at a path, re-indented to the map's; the text, comments and all, is kept. A flow map (or one the splices can't place a line in) takes the value's data instead. The map must exist (insertKey makes a missing one).

function insertRawPair(text: string, mapPath: Path, key: string, pairText: string, order?: readonly string[]): Splice;

invertStep function splice

The step that undoes step on the text it produced.

function invertStep(text: string, step: Step): Step;

moveKey function splice

Move a block map's entry (with its comment lines) to before another key, or to the end.

function moveKey(text: string, path: Path, before?: string, order?: readonly string[]): Splice;

pairText function splice

A pair's source text (its own comment lines, the key and its value, a comment after it), at indent 0.

function pairText(text: string, path: Path): string | undefined;

renameKey function splice

Rename a key in place.

function renameKey(text: string, path: Path, to: string): Splice;

scalarText function splice

A scalar as YAML text. Keeps a quoting style when one is given; multi-line text becomes a block literal.

function scalarText(v: unknown, opts: {
    flow: boolean;
    indent: number;
    style?: Style;
}): string;

setValue function splice

Set the value at a path (which must exist: use insertKey for a new key).

function setValue(text: string, path: Path, value: unknown): Splice;

Splice interface splice

interface Splice {
    steps: Step[];
    fallback?: boolean;
}

SpliceError class splice

class SpliceError extends Error {
}

Step type splice

one step: non-overlapping edits against the same text

type Step = TextEdit[];

TextEdit interface splice

interface TextEdit {
    start: number;
    end: number;
    text: string;
}

PREF const storage-keys

const PREF: {
    readonly view: 'view';
    readonly live: 'live';
};

VIEWS const storage-keys

const VIEWS: readonly ['text', 'both', 'canvas'];

Actions type ui/actions

type Actions = ReturnType<typeof actionsFor>;

actionsFor function ui/actions

The shared actions, for one domain.

function actionsFor(kit: ActionsKit): {
    deletePaths: (doc: EditorModel, paths: Path[], origin: 'canvas' | 'props' | 'menu', note?: (t: string, tone?: 'bad') => void) => Promise<boolean>;
    rename: (doc: EditorModel, path: Path, origin: 'canvas' | 'props' | 'menu', note: ((t: string, tone?: 'bad') => void) | undefined, at: RenameAt & {
        joins?: number;
    }) => Promise<boolean>;
    duplicate: (doc: EditorModel, path: Path, origin: 'canvas' | 'menu', note?: (t: string, tone?: 'bad') => void) => void;
    connected: (doc: EditorModel, paths: Path[]) => Path[];
};

ActionsKit interface ui/actions

what the shared actions are given of the domain

interface ActionsKit {
    commands: Pick<Commands, 'deleteCmd' | 'renameCmd' | 'renameKeyCmd' | 'referencesTo' | 'describe' | 'duplicateCmd'>;
    objectOf(ptr: string): ObjectRef | undefined;
    kinds: ObjectKindInfo[];
    nameRule: RegExp;
    nameHint: string;
}

composite function ui/actions

Several commands as one undo step.

function composite(label: string, cmds: Command[]): Command;

run function ui/actions

function run(doc: EditorModel, c: Command, origin: 'canvas' | 'props' | 'menu', note?: (t: string, tone?: 'bad') => void, joins?: number): boolean;

CanvasDrawing interface ui/canvas

what the canvas draws: the domain's drawn document

interface CanvasDrawing {
    scene: CompiledScene;
    /** the frame: the scene's SVG */
    svg: string;
    /** data-id → the JSON pointer in the file it shows */
    pathOf: Map<string, string>;
    /** object name → the id of the element a pin moves */
    pinId: Map<string, string>;
    /** the same for parts with no object of their own: their pins' names */
    partId?: Map<string, string>;
    /** what is dragged with no object of its own: by the id under the pointer, its pin's name (in partId) and what it is called */
    parts?: Map<string, {
    …
}

CanvasKit interface ui/canvas

what the canvas is given of the domain (M: the domain's reading of the file; D: its drawing)

interface CanvasKit<M, D extends CanvasDrawing> {
    draw(model: M, data: unknown, theme: string): D;
    /** the drawing a text would be (a trial: where a drop lands), or undefined */
    trial(text: string, theme: string): D | undefined;
    catalog: KindCatalog;
    objectOf(ptr: string): ObjectRef | undefined;
    kinds: ObjectKindInfo[];
    commands: Pick<Commands, 'setCmd' | 'deleteCmd' | 'insertCmd' | 'insertItemCmd' | 'pinsCmd' | 'withPinsMoved' | 'describe' | 'freshName'>
    /** (0.31.0) with it, ⌥ at the start of a drag drags a copy */  & Partial<Pick<Commands, 'duplicateCmd'>>;
    /** (0.10.0) a connection drawn from one object to another (the adapter's connect): the canvas offers the gesture (a
     *  handle on a selected object, and "Connect to…") only when it is given */
    connect?(from: ObjectRef, to: ObjectRef, data: unknown): ConnectPlan | undefined;
    …
}

CanvasOpts interface ui/canvas

interface CanvasOpts<M, D extends CanvasDrawing, A extends object = object> {
    kit: CanvasKit<M, D>;
    theme: string;
    problems(): Problem[];
    note(t: string, tone?: 'info' | 'warn' | 'bad'): void;
    showInText(p: Path): void;
    showInTree(p: Path): void;
    onZoom(pct: number): void;
    /** the navigation modes, for the status bar */
    onHint?(text: string): void;
    /** (0.22.0) told when the canvas's part of what the person is in the middle of may have changed (a drag, a drop, a link) */
    onBusy?(): void;
    …
}

CanvasUi interface ui/canvas

the canvas's words and names

interface CanvasUi {
    /** the stage's class (the host's canvas CSS is scoped under it), and the drawing's class while the space key is down */
    rootClass: string;
    panKeyClass: string;
    /** the kinds the canvas's menu offers, in order */
    newOrder: string[];
    /** the palette's entries: a kind, and (0.10.0) a preset: what a new one starts as (default: the kind's template) and
     *  the base of its fresh name (default: the kind's singular) */
    palette: PaletteItem[];
    /** (0.12.0) where the palette is: 'floating' (the default: over the canvas, at its top left) or 'docked' (a pane of
     *  its own at the canvas's left, with a search box filtering by label and section, resizable and collapsible; its
     *  width and whether it is collapsed are kept in the host's store as `canvas-palette-dock`) */
    …
}

canvasView function ui/canvas

function canvasView<M, D extends CanvasDrawing, A extends object = object>(host: HTMLElement, doc: EditorModel, opts: CanvasOpts<M, D, A>): {
    addFromPalette: (sec: string, at?: {
        x: number;
        y: number;
    }, item?: PaletteItem) => Path | undefined;
    palette: HTMLDivElement;
    groupSelection: () => void;
    startPick: () => void;
    readonly linking: {
        from: ObjectRef;
        x?: number;
        y?: number;
    …
} & A;

DropInto interface ui/canvas

a drop into a container: what the new object is made as, and the words for it

interface DropInto {
    container: string;
    value(container: string): unknown;
    label(container: string): string;
}

FlatCanvas interface ui/canvas

the 2D view's implementation, handed to the canvas by its host

interface FlatCanvas {
    draw(scene: CompiledScene, stage: Element, o: {
        styles?: Record<string, FlatStyle>;
        title?: string;
        options?: Partial<FlatOptions>;
    }): FlatDrawn;
    /** (0.7.5) the switch's morph, from the view on the stage to the other, both laid out in `root`: undefined when it
     *  shouldn't animate (the motion option, reduced motion); the canvas shows and hides the two drawings itself */
    morph?(root: HTMLElement, scene: CompiledScene, from: {
        svg: SVGSVGElement;
        mode: '3d' | '2d';
    }, to: SVGSVGElement, o: {
    …
}

FlatDrawn interface ui/canvas

a scene drawn in 2D, as the canvas uses it (flat-canvas.ts makes it)

interface FlatDrawn {
    svg: string;
    /** its viewBox */
    full: [number, number, number, number];
    /** the layout (for tests) */
    layout: unknown;
    /** the outlines of these drawn ids: a card's or a panel's rect, a link's path */
    outlines(ids: Set<string>, svg: SVGSVGElement): ({
        kind: 'poly';
        id: string;
        points: [number, number][];
    } | {
    …
}

PaletteItem interface ui/canvas

interface PaletteItem {
    kind: string;
    icon: IconName;
    label: string;
    value?(): unknown;
    name?: string;
    /** (0.11.0) the header it is listed under: entries with one are grouped by it, in order of first use, each group under
     *  a header that collapses (all collapsed but the one last added from, remembered in the host's store as
     *  `canvas-palette`); entries without one are listed as before, where they are */
    section?: string;
}

CanvasCtx interface ui/canvas-layer

what the canvas gives a layer (D: the domain's drawn document)

interface CanvasCtx<D> {
    host: HTMLElement;
    doc: EditorModel;
    cd(): D | undefined;
    svg(): SVGSVGElement | undefined;
    elementsFor(ptr: string): SVGGraphicsElement[];
    boxOf(e: SVGGraphicsElement): Box;
    union(bs: Box[]): Box | undefined;
    outlinesFor(ptr: string): Outline[];
    scale(): number;
    /** the whole drawing's box */
    full(): Box | undefined;
    …
}

CanvasLayer interface ui/canvas-layer

what a layer gives the canvas; A: its calls, added to what the canvas returns

interface CanvasLayer<A extends object> {
    tools?: HTMLElement[];
    marks?: HTMLElement[];
    /** each new drawing: the layer's groups, put after the overlay's */
    groups?(): SVGGElement[];
    /** a new drawing is on the stage */
    drawn?(): void;
    /** what a fit takes in besides the drawing */
    extent?(): Box[];
    /** the layer shows marks (the view keeps them in a fit) */
    showing?(): boolean;
    /** after the overlay's own marks */
    …
}

Outline type ui/canvas-layer

type Outline = {
    kind: 'poly';
    id: string;
    points: [number, number][];
} | {
    kind: 'route';
    d: string;
};

Clip interface ui/clip

interface Clip {
    /** the menu items for what is selected */
    items(): MenuItem[];
    /** handle the clipboard events of a document (the page, or the canvas's frame) */
    attach(d: EventTarget, owns: (target: EventTarget | null) => boolean): () => void;
    copy(): Promise<boolean>;
    cut(): Promise<boolean>;
    paste(text?: string): Promise<boolean>;
}

clipboard function ui/clip

the page's clipboard over the domain's (its copyText, cutCmd and pasteCmd: src/iso-editor/clipboard.ts)

function clipboard(doc: EditorModel, note: (t: string, tone?: 'info' | 'warn' | 'bad') => void, services: Clipboard): Clip;

ask function ui/dialog

function ask(title: string, body: (Node | string)[], buttons: DialogButton[]): Promise<string | null>;

DialogButton interface ui/dialog

interface DialogButton {
    label: string;
    value: string;
    primary?: boolean;
    danger?: boolean;
}

flatCanvas const ui/flat-canvas

const flatCanvas: FlatCanvas;

icon function ui/icons

function icon(name: IconName, cls?: string): SVGSVGElement;

IconName type ui/icons

an icon's name in the sprite

type IconName = string;

KeyGroup type ui/keys

type KeyGroup = {
    where: string;
    keys: [string, string][];
};

keymapWith function ui/keys

The map with a host's own keys added to the first group (the standalone page: ⇧⌘S Save as, ⌘O Open).

function keymapWith(map: KeyGroup[], extra: [string, string][]): KeyGroup[];

keySheet function ui/keys

function keySheet(map: KeyGroup[]): HTMLDialogElement;

isTyping const ui/later

Is this change typing (from a text pane)? Then the structural views can wait.

const isTyping: (c: Change) => boolean;

later function ui/later

A function that runs fn once, ms after the last call; now() runs it at once (and cancels the wait); cancel() drops a pending run (when the editor is disposed).

function later(fn: () => void, ms?: number): {
    (): void;
    now(): void;
    pending(): boolean;
    cancel(): void;
};

TYPING_PAUSE_MS const ui/later

const TYPING_PAUSE_MS = 150;

layer function ui/layer

function layer(): HTMLElement;

setLayer function ui/layer

function setLayer(el: HTMLElement | null): void;

closeMenu function ui/menu

function closeMenu(): void;

MenuItem type ui/menu

type MenuItem = {
    label: string;
    icon?: IconName;
    desc?: string;
    keys?: string;
    danger?: boolean;
    disabled?: boolean;
    why?: string;
    onSelect(): void;
} | {
    sep: true;
} | {
    heading: string;
};

menuOpen const ui/menu

const menuOpen: () => boolean;

openMenu function ui/menu

function openMenu(items: MenuItem[], at: {
    x: number;
    y: number;
} | HTMLElement, label?: string): HTMLElement;

DrawnBox interface ui/mount

(0.22.0, experimental) a box in the drawing's coordinates

interface DrawnBox {
    x: number;
    y: number;
    w: number;
    h: number;
}

Editor interface ui/mount

interface Editor {
    getText(): string;
    /** another file, with a history of its own. `fit` (0.12.5): its drawing is fitted once drawn (default: the view stays where it is) */
    setText(text: string, o?: {
        fit?: boolean;
    }): true;
    /** one whole text for the open file's, as one step (the step, always truthy; or false where it is the same). The host's own act: read-only doesn't stop it */
    setText(text: string, o: {
        fit?: boolean;
        undoable: true;
        label?: string;
        meta?: StepMeta;
    …
}

EditorBusy type ui/mount

(0.22.0, experimental) see Editor.busy

type EditorBusy = 'drag' | 'link' | 'rename' | 'typing' | false;

EditorCanvas interface ui/mount

(0.22.0, experimental) the canvas, for a host

interface EditorCanvas {
    /** the stage, the same element for the mount's life: each drawing is a child of it */
    readonly element: HTMLElement;
    readonly mode: '3d' | '2d';
    /** resolves once drawn in that mode: false where there is no 2D, or it was disposed. remember as setView's (default: not) */
    setMode(mode: '3d' | '2d', o?: {
        remember?: boolean;
    }): Promise<boolean>;
    /** a scale: 1 is 100% */
    readonly zoom: number;
    /** resolves when the text as it is now is drawn and the view still (after the person's drag, if one is under way): true, or false
     *  where it can't be drawn. It never rejects */
    …
}

EditorOptions interface ui/mount

interface EditorOptions {
    text?: string;
    readOnly?: boolean;
    theme?: Theme;
    storage?: {
        get(k: string): string | null;
        set(k: string, v: string | null): void;
    };
    watch?: boolean;
    onSave?(text: string): Promise<SaveResult>;
    onDirtyChange?(dirty: boolean): void;
    host?: HostHooks;
}

EditorSetup interface ui/mount

what the domain gives the mounted editor

interface EditorSetup<R, X, A extends object> {
    kit: MountKit<R, X>;
    tree: TreeKit;
    words: ShellWords;
    features: ShellFeatures & Record<string, unknown>;
    /** every feature's name, and those that can be added to a mounted editor */
    names: readonly string[];
    late: readonly string[];
    load?: (names: readonly string[]) => Promise<{
        name: string;
    }[]>;
    /** the host's deeper check is given (its panel paints "none" otherwise) */
    …
}

EditorState interface ui/mount

The editor's state, for the standalone page and the tests (not part of the component's API).

interface EditorState<R = unknown, X = unknown> {
    problems: Problem[];
    lifetimes: Map<string, string>;
    read: R | undefined;
    plan: X | undefined;
    view: 'canvas' | 'both' | 'text';
    theme: Theme;
    density: 'comfortable' | 'compact';
    readOnly: boolean;
    problemsOpen: boolean;
    problemsSeen: number;
    checks: number;
}

HostHooks interface ui/mount

what a host adds to the shell

interface HostHooks {
    titleStart?: HTMLElement[];
    sideTabs?: {
        id: string;
        label: string;
        icon: string;
        panel: HTMLElement;
    }[];
    keys?(e: KeyboardEvent): boolean;
    keymap?: [string, string][];
    themeControls?: boolean;
    onOpen?(rel: string): void;
    …
}

mountEditor function ui/mount

P3: the editor with the features given (the core alone: the shell, the model, the reader and the tree; read-only unless edit is given).

function mountEditor<R, X, A extends object = object>(el: HTMLElement, opts: EditorOptions, S: EditorSetup<R, X, A>): Editor & {
    internal: Record<string, unknown>;
};

SaveResult type ui/mount

type SaveResult = {
    ok: true;
} | {
    conflict: true;
};

ShellCanvas interface ui/mount

what the shell calls on a canvas

interface ShellCanvas {
    render(model: unknown, data: unknown): Promise<void>;
    setTheme(t: 'light' | 'dark'): void;
    fit(): void; /** (0.12.5) the next drawing is fitted, whatever the person did with the view before */
    fitNext?(): void;
    focus(): void;
    dispose(): void;
}

ShellFeatures interface ui/mount

the views' features, as the shell uses them (a feature not given is never loaded)

interface ShellFeatures {
    text?: {
        textPane(el: HTMLElement, doc: EditorModel, o: Omit<PaneOpts, 'services'>): MonacoPane;
    };
    canvas?: {
        canvasView(host: HTMLElement, doc: EditorModel, o: never): ShellCanvas;
    };
    edit?: {
        propsPanel(body: HTMLElement, doc: EditorModel, o: never): {
            paint(): void;
            dispose(): void;
        };
    …
}

ShellWords interface ui/mount

the shell's words (markup is the setup's constant, never the file's)

interface ShellWords {
    rootClass: string;
    /** the brand mark's markup */
    brand: string;
    sideLabel: string;
    canvasLabel: string;
    problemsLabel: string;
    bottomTabsLabel: string;
    extraTab: string;
    /** more panels' slots under the work area (markup) */
    slots: string;
}

Theme type ui/mount

type Theme = 'light' | 'dark' | 'system';

Checked interface ui/mount-kit

a text, checked (R: the domain's reading; X: a host's deeper check, shown beside Problems)

interface Checked<R, X> {
    problems: Problem[];
    read: R | undefined;
    /** each object's tag (the tree's pills) */
    tags: Map<string, string>;
    /** what the canvas draws (undefined: nothing), and the data it is drawn from */
    model: unknown;
    data: unknown;
    extra: X | undefined;
}

MountKit interface ui/mount-kit

interface MountKit<R, X> {
    /** check a text (prev: the last check's extra); a failure of the host's check is a note, not a throw */
    check(text: string, prev: X | undefined, note: (t: string, tone?: 'info' | 'warn' | 'bad') => void): Promise<Checked<R, X>>;
    role(text: string): FileRole;
    /** the status bar's word for the file's kind */
    kindLabel(text: string): string;
    nav(text: string): SchemaNav;
    /** an object's pointer, by its name, in the reading */
    objectPath(name: string, read: R | undefined): string | undefined;
    /** the host's check beside Problems, in a word (none: '' and '') */
    extraLabel(extra: X | undefined): {
        text: string;
    …
}

PaneOpts interface ui/pane

interface PaneOpts {
    services: TextServices;
    onOpen?(file: string): void;
    onSave?(): void;
    onSaveAs?(): void;
}

TextPane interface ui/pane

interface TextPane {
    id: 'monaco';
    el: HTMLElement;
    setProblems(ps: Problem[]): void;
    /** the path at the caret, for the status bar */
    pathAtCaret(): Path;
    /** mark paths in the text (and move the caret to the first, unless this pane has the focus) */
    showSelection(paths: Path[], move: boolean): void;
    /** put the caret at a path, scroll to it, and focus the pane */
    goTo(path: Path): void;
    /** put the caret at an offset, scroll to it, and focus the pane */
    goToOffset(offset: number): void;
    …
}

TextSel type ui/pane

A text selection as offsets into the text, the form the model keeps for undo (any pane can put it back).

type TextSel = {
    anchor: number;
    head: number;
}[];

TextServices interface ui/pane

what a pane asks of the domain, by offset into the text (the editor core's providers, given an adapter)

interface TextServices {
    docFor(text: string): EditorDoc;
    completionAt(d: EditorDoc, offset: number): {
        from: number;
        items: Item[];
    };
    hoverAt(d: EditorDoc, offset: number): {
        from: number;
        to: number;
        parts: string[];
    } | null;
    definitionAt(d: EditorDoc, offset: number): {
    …
}

Attention interface ui/part

what waits for a person: rows put before the file's problems

interface Attention {
    /** how many (they count as problems seen) */
    count: number;
    /** how many open the list when they appear */
    opens: number;
    /** the list keeps still (neither opens nor closes for these) */
    still: boolean;
    rows: Node[];
    /** their words in the list's label */
    label: string;
}

EditorPart interface ui/part

what a part gives the editor; A: its calls

interface EditorPart<A extends object> {
    now?(ptr: string): unknown;
    attention?(): Attention | undefined;
    start?(): void;
    dispose?(): void;
    api: A;
}

PartCtx interface ui/part

what the editor gives a part

interface PartCtx {
    root: HTMLElement;
    /** one of the shell's elements, by its id (without the prefix) */
    byId<T extends HTMLElement = HTMLElement>(id: string): T;
    doc: EditorModel;
    store: {
        get(k: string): string | null;
        set(k: string, v: string | null): void;
    };
    note(t: string, tone?: 'info' | 'warn' | 'bad'): void;
    /** the editor shows the file for this mount only (nothing it shows is kept) */
    watch: boolean;
    …
}

iconSymbols const ui/plain-icons

symbols of a sprite: one per icon, with the id icon() and the shell's markup use

const iconSymbols: (svgs: Record<string, string>) => string;

PLAIN_ICON_SVG const ui/plain-icons

each icon's SVG body, by name (Lucide, ISC)

const PLAIN_ICON_SVG: Record<string, string>;

PLAIN_ICONS const ui/plain-icons

the names L3 uses

const PLAIN_ICONS: readonly string[];

PLAIN_SPRITE const ui/plain-icons

L3's sprite: every icon it uses

const PLAIN_SPRITE: string;

spriteOf const ui/plain-icons

a sprite of symbols, as the setup's sprite (mountEditor puts it in the editor's root)

const spriteOf: (symbols: string) => string;

PropsKit interface ui/props

what the panel is given of the domain

interface PropsKit {
    commands: Pick<Commands, 'setCmd' | 'deleteCmd' | 'insertItemCmd' | 'referencesTo' | 'describe'>;
    actions: Pick<Actions, 'deletePaths' | 'rename'>;
    slotAt(ptr: string): RefSlot | undefined;
    objectOf(ptr: string): ObjectRef | undefined;
    kinds: ObjectKindInfo[];
    ui: PropsUi;
}

PropsOpts interface ui/props

interface PropsOpts {
    kit: PropsKit;
    nav(): SchemaNav;
    problems(): Problem[];
    /** the domain's reading of the file (the kit's inherited() reads it) */
    read(): unknown;
    note(t: string, tone?: 'info' | 'warn' | 'bad'): void;
    showInText(p: Path): void;
    /** while the host's state is shown, what is true now about an object (the kit's facts() reads it); undefined while not */
    now?(ptr: string): unknown;
}

propsPanel function ui/props

function propsPanel(body: HTMLElement, doc: EditorModel, opts: PropsOpts): {
    paint: () => void;
    dispose: () => void;
};

PropsUi interface ui/props

what the panel shows of the domain

interface PropsUi {
    /** keys worth showing even when unset */
    important(kind: string, value: Record<string, unknown>, external: boolean): string[];
    /** an object that exists elsewhere (only its reference keys apply) */
    isExternal(value: unknown): boolean;
    /** a key one object inherits (its value, and where from), given the domain's reading; and every key it inherits */
    inherited?(path: Path, key: string, read: unknown): {
        value: unknown;
        from?: string;
    } | undefined;
    inheritedKeys?(path: Path, read: unknown): string[];
    /** where inherited values come from, when the reading doesn't say */
    …
}

scopeCss function ui/scope-css

Scope a stylesheet to the root class.

function scopeCss(css: string, root: string): string;

scopeOne function ui/scope-css

One selector under the root: html, body and :root (with any state they name) become the root itself; * is the root and everything in it.

function scopeOne(sel: string, root: string): string;

DomainView interface ui/setup

what a domain gives besides its adapter

interface DomainView<R, D extends CanvasDrawing> {
    /** a reading, drawn (the adapter's read() gives the reading) */
    draw(read: R, data: unknown, theme: string): D;
    catalog: KindCatalog;
    theme: string;
    /** the file's name when the host gives none */
    fileName: string;
    /** what a name must be, and the rule in words */
    nameRule?: RegExp;
    nameHint?: string;
    /** a kind's icon (default: box) */
    icon?(kind: string): IconName;
    …
}

PLAIN_KEYMAP const ui/setup

the plain keymap: the shell's own keys

const PLAIN_KEYMAP: KeyGroup[];

PLAIN_WORDS const ui/setup

the plain shell's words

const PLAIN_WORDS: ShellWords;

setupFor function ui/setup

The kits and features for an adapter (R: its reading; D: its drawing), with the text pane if the host has one.

function setupFor<R, D extends CanvasDrawing>(a: DomainAdapter, v: DomainView<R, D>, textPane?: (el: HTMLElement, doc: EditorModel, o: PaneOpts) => MonacoPane): EditorSetup<R, undefined, object>;

EntryItem interface ui/tree

an entry an entry group offers: its words, its icon, its key (made unique) and its value

interface EntryItem {
    label: string;
    icon: IconName;
    entry: string;
    value: unknown;
    cmdLabel?: string;
    when?: (data: Record<string, unknown>) => boolean;
}

NewItem interface ui/tree

a "New …" entry for a kind's group: its words, its icon, and what it starts as (default: the kind's)

interface NewItem {
    label: string;
    icon: IconName;
    desc?: string;
    template?: () => unknown;
    stem?: string;
}

TreeKit interface ui/tree

what the tree is given of the domain

interface TreeKit {
    outline(d: EditorDoc, role: FileRole, tags: Map<string, string>): OutlineNode;
    commands: Pick<Commands, 'setCmd' | 'insertCmd' | 'insertItemCmd' | 'deleteCmd' | 'renameCmd' | 'renameKeyCmd' | 'duplicateCmd' | 'moveCmd' | 'moveItemCmd' | 'referencesTo' | 'describe' | 'freshName'>;
    slotAt(ptr: string): RefSlot | undefined;
    /** the kinds, in the outline's order */
    kinds: ObjectKindInfo[];
    /** named maps that aren't kinds (their names a pool of their own) */
    entryGroups: Path[];
    /** what a name must be */
    nameRule: RegExp;
    ui: TreeUi;
}

TreeOpts interface ui/tree

interface TreeOpts {
    kit: TreeKit;
    nav(): SchemaNav;
    problems(): Problem[];
    role(): FileRole;
    /** each object's tag as the reader resolved it, with the base files merged */
    lifetimes(): Map<string, string>;
    /** show a path in the text pane and give it the focus */
    showInText(path: Path): void;
    /** Copy, Cut and Paste for the menu */
    clipItems?(): import('./menu.js').MenuItem[];
    /** a message for the person (an edit that can't be made) */
    note(text: string, tone?: 'info' | 'warn' | 'bad'): void;
}

TreeUi interface ui/tree

what the tree shows of the domain, in its words

interface TreeUi {
    /** the tree's aria-label */
    label: string;
    rootIcon: IconName;
    kindIcon(kind: string): IconName;
    /** a top-level key's icon, if it has one */
    keyIcon(key: string): IconName | undefined;
    /** an entry group's entries' icon */
    entryIcon(group: string): IconName;
    /** a kind's group's "New …" entries, in order */
    newItems(kind: string): NewItem[];
    /** an entry group's own add items (its entries made from the file: owned, not yet entered) */
    …
}

treeView function ui/tree

function treeView(el: HTMLElement, doc: EditorModel, opts: TreeOpts): {
    paint: () => void;
    dispose: () => void;
    focus: () => void;
    /** for the tests */
    rows: () => {
        id: string;
        label: string;
        depth: number;
        kind: import("../outline.js").NodeKind;
        value: string | undefined;
        lifetime: string | undefined;
    …
};

analyse function validate

The problems, and what the reader resolved: each object's tag (with the base files merged), and its own reading.

function analyse(a: ReadAdapter, text: string, opts: ValidateOpts & {
    fileName: string;
}): {
    problems: Problem[];
    tags: Map<string, string>;
    read?: unknown;
};

place function validate

A diagnostic as a range in the text (a host's plan problem too: its pointer and line, made a Diag).

function place(a: PlaceAdapter, d: EditorDoc, x: Diag, fileName: string): Problem;

Problem interface validate

interface Problem {
    severity: 'error' | 'warning';
    message: string;
    hint?: string;
    path: string;
    /** 1-based, end exclusive */
    startLine: number;
    startCol: number;
    endLine: number;
    endCol: number;
    /** the other file it is in, when it isn't this one */
    file?: string;
}

ValidateOpts interface validate

interface ValidateOpts {
    fileName?: string;
    defaults?: {
        name: string;
        text: string;
    }[];
    /** problems resolving extends: (loops, missing files), from the server */
    extendsDiags?: Diag[];
    profiles?: string[];
}

BaseToHost type window/protocol

the window's messages every editor sends

type BaseToHost = {
    v: 1;
    type: 'hello';
    capabilities: Capabilities;
} | {
    v: 1;
    type: 'save';
    id: number;
    text: string;
} | {
    v: 1;
    type: 'dirty';
    …
};

BaseToWindow type window/protocol

the host's messages every editor takes (I: the domain's own fields in init)

type BaseToWindow<I extends object = object> = ({
    v: 1;
    type: 'init';
    text: string;
    fileName?: string;
    readOnly?: boolean;
    theme?: Theme;
    features?: string[];
} & I) | {
    v: 1;
    type: 'text';
    text: string;
    …
};

Capabilities interface window/protocol

what a window can do: a newer window tells an older host what it lacks, and the reverse

interface Capabilities {
    protocol: number;
    features: string[];
    messages: string[];
}

isMessage function window/protocol

a message of this protocol, of a type the receiver knows (anything else is ignored, never an error)

function isMessage<T extends {
    type: string;
}>(d: unknown, types: readonly string[]): d is T;

PROTOCOL const window/protocol

const PROTOCOL = 1;

Refused type window/protocol

type Refused = {
    refused: string;
};

systems src/iso-systems

import { systems } from '@johnoscott/isometric-engine/systems';
import { … } from '@johnoscott/isometric-engine/modules/iso-systems/MODULE';

REGION_KINDS const catalog

in this order: the legend's automatic rows follow it (fence, then vm), and so does the kinds' CSS

const REGION_KINDS: Record<string, RegionKind>;

systems const catalog

const systems: KindCatalog;

compile function compile

function compile(source: string, themeText: string, opts?: CompileOptions): Compiled;

CompileError class compile

class CompileError extends Error {
    diags: Diag[];
    constructor(diags: Diag[]);
}

CompileOptions interface compile

interface CompileOptions {
    /** overrides every scene's grid snap (the editor's snap control) */
    snap?: number;
    /** which of the theme's modes a self-contained drawing is in (default: light) */
    mode?: ThemeMode;
    /** (0.15.0) self-contained drawings: each scene's SVG has its colours and text styles on its elements, in `mode`: no
     *  stylesheet, no custom properties, no hsl() or color-mix() (svgAt's frames too) */
    resolveVars?: boolean;
    /** (0.16.0) a self-contained drawing in black and white, in either mode: greys, patterns and line rhythms, and no hue */
    treatment?: 'mono' | 'none';
    /** a host's own table, over the treatment's */
    mono?: MonoTable;
    …
}

BASE_CSS const css

const BASE_CSS: string;

DRAWING_CSS const css

without any marks a host registers: for those, drawingCss(systems) / baseCss(systems) after registering

const DRAWING_CSS: string;

getAsset function nodes

function getAsset(name: string | undefined): NodeAsset | undefined;

NODE_ASSETS const nodes

const NODE_ASSETS: Record<string, NodeAsset>;

renderAnimatedSvg function render

(0.35.0) A diagram's motion as one SVG that plays by itself, for an <img>, a manual or a site: CSS keyframes inside it (no script, nothing outside it), sampled from the same Timeline the page and renderSvg's t use. A scene's ants march by SVG's own animation, as in renderSvg's stills. prefers-reduced-motion stops it at rest (default: the still). Throws, with every fault and its line, when the file or its motion has one.

function renderAnimatedSvg(source: string, o: RenderAnimatedSvgOptions): AnimatedSvg;

RenderAnimatedSvgOptions interface render

interface RenderAnimatedSvgOptions extends AnimatedSvgOptions {
    theme: string;
    mode?: ThemeMode;
    treatment?: 'mono' | 'none';
    mono?: MonoTable;
    /** which scene: its id or its place (default: the first) */
    scene?: string | number;
    /** the motion (default: the scene's own in the file, else its steps as the page's player plays them) */
    motion?: MotionDoc;
}

renderSvg function render

Throws, with every fault and its line, when the file or its motion has one.

function renderSvg(source: string, o: RenderSvgOptions): string;

RenderSvgOptions interface render

interface RenderSvgOptions {
    /** the theme's text */
    theme: string;
    mode?: ThemeMode;
    /** black and white, in either mode, and a host's own table for it */
    treatment?: 'mono' | 'none';
    mono?: MonoTable;
    /** which scene: its id or its place (default: the first) */
    scene?: string | number;
    /** a moment of its motion, ms: the still without it */
    t?: number;
    /** the motion (default: the scene's own in the file) */
    …
}