Skip to content

Latest commit

 

History

History
536 lines (453 loc) · 29.2 KB

node-graph.md

File metadata and controls

536 lines (453 loc) · 29.2 KB

Node graph

rf-nodegraph is a node editor: boxes with ports, and wires between them. It is for shader graphs, audio and logic graphs, pipelines, state machines and flow charts.

The nodes are real UI. A graph-node is a box that holds any markup: text, live values, sliders, selects, images, your own components. CSS styles it like every other node, and screen readers and the inspector see it like every other node. The graph itself draws only the wires, and it pans and zooms.

The crate is optional. An app that does not use it pays nothing.

[dependencies]
rf-nodegraph = { path = "path/to/renderfi/crates/rf-nodegraph" }

A graph in markup

<box style="width: 640; height: 360; background-color: #16181c; color: #d8dbe0">
  <node-graph id="graph" grid="dots" snap="10" style="flex-grow: 1">
    <graph-node id="noise" x="40" y="40">
      <text class="node-title">Noise</text>
      <box class="node-row"><text class="grow">Value</text><text text={noise.value}>0.50</text><node-port name="out" side="right" kind="float"/></box>
      <slider min="0" max="10" value="4" on-change="noise.scale"/>
    </graph-node>
    <graph-node id="mix" x="320" y="120">
      <text class="node-title">Mix</text>
      <box class="node-row"><node-port name="a" side="left" kind="float"/><text>A</text></box>
      <box class="node-row"><node-port name="b" side="left" kind="float"/><text>B</text></box>
    </graph-node>
    <graph-edge from="noise.out" to="mix.a" animated/>
    <graph-minimap place="bottom-right"/>
  </node-graph>
</box>

Call rf_nodegraph::install once per Ui, before you load markup that uses the types. It adds the node types, the default look (the stylesheet nodegraph) and a hook that runs the graphs inside Ui::input and Ui::update.

// from: crates/rf-nodegraph/examples/guide_nodegraph.rs#setup
const PAGE: &str = r##"
<box style="width: 640; height: 360; background-color: #16181c; color: #d8dbe0">
  <node-graph id="graph" grid="dots" snap="10" style="flex-grow: 1">
    <graph-node id="noise" x="40" y="40">
      <text class="node-title">Noise</text>
      <box class="node-row"><text class="grow">Value</text><text text={noise.value}>0.50</text><node-port name="out" side="right" kind="float"/></box>
      <slider min="0" max="10" value="4" on-change="noise.scale"/>
    </graph-node>
    <graph-node id="mix" x="320" y="120">
      <text class="node-title">Mix</text>
      <box class="node-row"><node-port name="a" side="left" kind="float"/><text>A</text></box>
      <box class="node-row"><node-port name="b" side="left" kind="float"/><text>B</text></box>
    </graph-node>
    <graph-edge from="noise.out" to="mix.a" animated/>
    <graph-minimap place="bottom-right"/>
  </node-graph>
</box>"##;

/// A UI with a node graph. `rf_nodegraph::install` adds the node types,
/// the default look and the hook that runs the graphs.
pub fn setup() -> (Ui, NodeId) {
    let mut ui = Ui::new();
    // the widgets inside the nodes (the slider) run in the UI
    rf_widgets::Widgets::install(&mut ui, &rf_widgets::WidgetsInfo::default()).expect("widgets").attach(&mut ui);
    rf_nodegraph::install(&mut ui).expect("the node graph");
    let root = ui.load_markup(PAGE).expect("markup");
    ui.set_root(root).unwrap();
    ui.set_data("noise.value", "0.50");
    ui.update(640.0, 360.0);
    let graph = ui.find("graph").expect("the graph");
    (ui, graph)
}

Run it: cargo run --release -p rf-nodegraph --example guide_nodegraph (writes out/guide/nodegraph.png). A larger demo is cargo run --release -p rf-nodegraph --example nodegraph (PNGs) and cargo run --release -p nodegraph (a window; NODEGRAPH_NODES=5000 shows a large graph).

The node types

node-graph

property default
zoom, pan-x, pan-y 1, 0, 0 the view: view = graph * zoom + pan. They follow what the user does, and you can set or bind them
min-zoom, max-zoom 0.05, 4 the limits of the zoom
grid dots the background: dots, lines, cross or none
grid-size 20 the distance of the grid marks, in graph units
snap 0 nodes that are dragged snap to this step. 0: no snap
detail-zoom 0.35 below this zoom the nodes are drawn as plain boxes (see How fast)
controlled false the graph only reports edits; the app changes the tree (see Controlled)
readonly false the user can pan, zoom and select, but not edit. The lock of graph-controls turns it on and off
pan-on-scroll false the wheel pans; Ctrl + wheel zooms (React Flow's panOnScroll)
zoom-on-double-click true a double click on the background zooms in by 2 about the pointer

Give the graph a size: a CSS width and height, or flex-grow in a flex container. Its children are graph-node, graph-edge and the parts over the graph (graph-minimap, graph-controls, graph-panel).

graph-node

property
id the name of the node in edges and actions. It must be there, and no two nodes of one graph have the same
x, y the place of the top left corner, in graph units (pixels at zoom 1)
w, h the size. 0 (the default): the size of the content, or what CSS says
selected the node is selected. CSS: graph-node[selected]
draggable, selectable true by default
parent the id of another node: this node moves when that one is dragged (a group)
type a word for CSS: graph-node[type=group]

A node is a flex column. The default look has three helper classes: node-title (the title bar, put it first), node-row (a row for a port, a label and a widget) and grow (takes the free room of a row).

A press on a widget inside a node (a button, a slider, an input, anything with on-click) is the widget's. A press anywhere else in the node selects the node, and a drag moves it.

A custom node type is a component with base="graph-node". It is a graph-node for the graph and for CSS, with its own props and template:

<box style="width: 520; height: 240">
  <component name="demo:gain-node" scoped base="graph-node" props="title gain:float=0.5">
    <text class="node-title">{title}</text>
    <box class="node-row"><node-port name="in" side="left"/><text class="grow">In</text><node-port name="out" side="right"/></box>
    <slider value="{gain}"/>
    <slot/>
  </component>
  <node-graph style="flex-grow: 1">
    <demo:gain-node id="one" x="20" y="20" title="One" gain="0.25"/>
    <demo:gain-node id="two" x="260" y="90" title="Two"><text>More</text></demo:gain-node>
    <graph-edge from="one.out" to="two.in"/>
  </node-graph>
</box>

node-port

A port is a small box. Layout places it like any box, anywhere in the node. The graph reads where it is and ends the wires there.

property
name the name of the port in edges: node.port
side left (the default), right, top or bottom: the side a wire leaves from. Ports on the right and the bottom are outputs, the others are inputs
dir in or out, when the side should not decide
kind a word for what the port carries (float, color). A wire goes from an output to an input of the same kind. A port without a kind takes any
accept for an input: the kinds it takes, with spaces between ("float int", or * for all). It wins over kind

In a node-row the default look puts a port on the border of its node (side="left" at the start of the row, side="right" at the end).

graph-edge

property
from, to the two ports: node.port. from is the output
kind the line: bezier (the default), smooth (right angles with round corners), step (right angles) or straight
animated the dashes of the wire run (see below)
selected the edge is selected. CSS: graph-edge[selected]

CSS styles the wire. The color of the edge is the color of the wire. Variables give the rest:

variable default
--rf-edge-width 2 the width of the line
--rf-edge-dash none lengths of dashes and gaps: 6 4
--rf-edge-dash-offset 0 moves the dashes along the line
--rf-edge-marker-start, --rf-edge-marker-end none arrow or dot at that end
graph-edge { color: #7c8696 }
graph-edge.signal { color: #e0a13c; --rf-edge-width: 3; --rf-edge-marker-end: arrow }
graph-edge[selected] { color: #4a8cff }

animated is plain CSS too. The default look has this rule, and you can write your own:

graph-edge[animated] { --rf-edge-dash: 6 4; animation: graph-edge-flow 0.5s linear infinite }
@keyframes graph-edge-flow { from { --rf-edge-dash-offset: 0 } to { --rf-edge-dash-offset: -10 } }

While an animated edge is there, the graph draws a frame for each step of the animation. With "reduce motion" on, the dashes stand still.

The children of an edge are its label. The graph puts them at the middle of the wire. A label is real UI: a text, a badge, a select.

<box style="width: 520; height: 200">
  <node-graph style="flex-grow: 1">
    <graph-node id="a" x="20" y="20"><text class="node-title">A</text>
      <box class="node-row"><text class="grow">Out</text><node-port name="out" side="right"/></box></graph-node>
    <graph-node id="b" x="320" y="90"><text class="node-title">B</text>
      <box class="node-row"><node-port name="in" side="left"/><text>In</text></box></graph-node>
    <graph-edge from="a.out" to="b.in" kind="smooth">
      <select value="mix"><option value="mix">Mix</option><option value="add">Add</option></select>
    </graph-edge>
  </node-graph>
</box>

All wires of one look are one path and one draw command. A class change on an edge that changes only its variables shows with the next change of the graph; selected, animated and the theme show at once.

Parts over the graph

These children do not pan or zoom. place puts them in a corner or at the middle of a side: top-left, top, top-right, left, right, bottom-left, bottom, bottom-right.

type
graph-minimap a small picture of the whole graph and the part in view. A press or a drag in it moves the view
graph-controls as React Flow's <Controls>: a column of square icon buttons with tooltips: zoom in, zoom out, show all, lock. The zoom buttons are disabled at min-zoom and max-zoom; the lock is checked while the graph is readonly. The skins set its look with the --graph-control-* variables; a page restyles a button with graph-controls::part(button)
graph-panel a box for your own UI (a legend, a toolbar, a status text)
graph-button a button that runs a command of the graph it is in. do: zoom-in, zoom-out, zoom-reset, fit, lock, delete, select-all, copy, cut, paste, undo, redo. It is a Tab stop; a click, Enter or Space runs the command. tooltip shows with rf-widgets. Put it in a panel or in a node

Parts of a node

type
node-toolbar a toolbar over the node. The default look shows it while the node is hovered or selected (graph-node:hover > node-toolbar). Put graph-buttons or your own buttons in it
node-resizer a grip in the bottom right corner. A drag changes w and h of the node

A group is a node with other nodes inside its box: give the inner nodes parent="<id of the group>" and write the group before them, so it is drawn behind them. A drag of the group takes them along. The places of the inner nodes stay graph coordinates.

What the user can do

input
drag a node moves it, and the selected nodes with it. With snap it snaps
click a node, a wire or a label selects it. Shift or Ctrl adds it to the selection or takes it out
drag the background pans. With Shift: a box that selects what it touches
middle drag pans, also over nodes
the wheel zooms about the pointer, by the same factor for each pixel (one notch: 13 %). A touchpad pinch zooms about the fingers; a pinch that comes as Ctrl + wheel (a browser) too
double click the background zooms in by 2 about the pointer (zoom-on-double-click)
drag from a port to a port makes a wire, when the kinds fit. The port lights up when the wire is allowed
drag the end of a wire off its input moves the wire to another input, or takes it off when it is dropped on nothing
Delete, Backspace removes the selection (the wires at a removed node go too)
arrow keys move the selected nodes by snap (10 without it). With Shift: five steps
Page Down, Page Up select the next or the last node and bring it into view
Ctrl+A, Ctrl+C, Ctrl+X, Ctrl+V select all, copy, cut, paste (the keys of Ui::edit_keys)
Ctrl+Z, Ctrl+Shift+Z undo, redo
F, +, -, 0 show all, zoom in, zoom out, zoom 1

The zoom buttons and keys zoom about the middle by 1.2, and "show all" leaves 40 pixels of room. These glide for a short time (0.2 s, show all 0.3 s); a second click goes on from where the first one goes. With less motion (Ui::set_reduced_motion) they are there at once. set_view from code is always at once. | Escape | stops a drag, else clears the selection |

Tab moves the focus through the widgets inside the nodes, as everywhere.

Edits are actions

Every edit comes out of Ui::input as an action with event "emit", the graph as its node and a text payload. rf_nodegraph::changes(&actions) reads them into GraphChange values.

action payload GraphChange
graph.move noise 40 40 60 80 (id, old x and y, new x and y); more nodes with ; between Move
graph.resize noise 170 96 220 140 (id, old w and h, new w and h) Resize
graph.select the selection now: node ids and edge keys Select
graph.connect noise.out->mix.b Connect
graph.reconnect noise.out->mix.a noise.out->mix.b (the old and the new edge) Reconnect
graph.delete node ids and edge keys Delete
graph.copy, graph.paste the ids; the graph point to paste at Copy, Paste
graph.undo, graph.redo Undo, Redo
graph.view pan-x pan-y zoom View

The key of an edge is from->to: noise.out->mix.a.

By default the graph does the edit itself and the app only follows: a drag sets x and y of the node, a new wire adds a graph-edge, Delete removes the nodes, paste adds copies with new ids (noise-2), and undo takes each of these back. The history holds 200 steps per graph.

// from: crates/rf-nodegraph/examples/guide_nodegraph.rs#edits
/// What the app does with the actions of `Ui::input`. The graph has done
/// the edit already (it is not `controlled`): the app only follows.
pub fn follow(actions: &[Action]) -> Vec<String> {
    use rf_nodegraph::GraphChange;
    let mut log = Vec::new();
    for (_graph, change) in rf_nodegraph::changes(actions) {
        match change {
            GraphChange::Move(nodes) => nodes.iter().for_each(|m| log.push(format!("{} is at {} {}", m.id, m.to.0, m.to.1))),
            GraphChange::Connect { from, to } => log.push(format!("{from} feeds {to}")),
            GraphChange::Delete(items) => log.push(format!("{} gone", items.join(", "))),
            _ => {}
        }
    }
    log
}

Paste and undo of a delete make nodes again from their type, their properties and their children. That is right for nodes written in markup and for components. If a node holds state that is not in properties, use a controlled graph.

Controlled: the model is yours

With controlled, the graph changes nothing. It reports the same actions, and the app decides: it changes its document, and the document sets the nodes. Use it when the graph shows data that lives somewhere else: a file format, an rf-store collection, a server.

// from: crates/rf-nodegraph/examples/guide_nodegraph.rs#controlled
/// A controlled graph: the model is the app's (a store, a document). The
/// graph reports, the app changes its model, and the model sets the nodes.
pub fn controlled() -> (f64, usize) {
    use rf_nodegraph::GraphChange;
    let (mut ui, graph) = setup();
    ui.set(graph, "controlled", true).unwrap();
    ui.update(640.0, 360.0);
    let title = middle(&ui, "#noise .node-title");
    let actions = drag(&mut ui, title, (title.0 + 20.0, title.1 + 40.0));
    for (graph, change) in rf_nodegraph::changes(&actions) {
        match change {
            // (an app writes to its store here; a live query then sets x and y)
            GraphChange::Move(nodes) => {
                for m in nodes {
                    let node = ui.find(&m.id).unwrap();
                    ui.set(node, "x", m.to.0 as f64).unwrap();
                    ui.set(node, "y", m.to.1 as f64).unwrap();
                }
            }
            GraphChange::Connect { from, to } => {
                let edge = ui.add(Some(graph), "graph-edge", "").unwrap();
                ui.set(edge, "from", from.as_str()).unwrap();
                ui.set(edge, "to", to.as_str()).unwrap();
            }
            _ => {}
        }
    }
    ui.update(640.0, 360.0);
    let x = ui.get(ui.find("noise").unwrap(), "x").unwrap().as_f32().unwrap() as f64;
    (x, ui.context().node(graph).unwrap().children.len())
}

With rf-store: keep a collection of nodes and one of edges, write to them when a change comes, and let a live query add, change and remove the graph-node and graph-edge nodes (ui.add, ui.set, ui.destroy). The store's undo is then the graph's undo. A change of one node costs that node (see below), so a query that sets many properties is fine.

The view from code

// from: crates/rf-nodegraph/examples/guide_nodegraph.rs#view
/// The view from code: fit it, and convert between graph and window.
pub fn view() -> (f32, (f32, f32)) {
    use rf_nodegraph::{PointInfo, PointSpace, ViewInfo, ViewMode};
    let (mut ui, graph) = setup();
    // show everything, with 30 pixels of room
    rf_nodegraph::set_view(&mut ui, graph, &ViewInfo { mode: ViewMode::Fit, padding: 30.0, ..ViewInfo::default() });
    ui.update(640.0, 360.0);
    let zoom = rf_nodegraph::view(&mut ui, graph).unwrap().zoom;
    // the pointer at (320, 180) in the window: which graph point is that?
    let at = rf_nodegraph::convert_point(&mut ui, graph, &PointInfo { space: PointSpace::ScreenToGraph, x: 320.0, y: 180.0 }).unwrap();
    // put a new node there
    let node = ui.load_markup(r#"<graph-node id="new"><text class="node-title">New</text></graph-node>"#).unwrap();
    ui.set(node, "x", at.0 as f64).unwrap();
    ui.set(node, "y", at.1 as f64).unwrap();
    ui.append_child(graph, node).unwrap();
    ui.update(640.0, 360.0);
    let r = ui.screen_rect(node).unwrap();
    (zoom, (r.x.round(), r.y.round()))
}
function
set_view(ui, graph, &ViewInfo) one function for the view. mode: Set (use pan_x, pan_y, zoom), Fit (show all, with padding), FitSelection, Center (put a graph point in the middle)
view(ui, graph) the pan and zoom now
convert_point(ui, graph, &PointInfo) a point from the graph to the window or back (space). Scrolling and CSS transforms around the graph count
selection(ui, graph) the ids of the selected nodes and the keys of the selected edges
undo(ui, graph), redo(ui, graph) the history of a graph that is not controlled
apply(ui, &actions) does the default for graph actions that did not come out of Ui::input (from Ui::take_actions)

From C there are three functions, with the same info structs: rfNodeGraphSetView, rfNodeGraphGetView and rfNodeGraphConvertPoint (see c-and-bindings.md). Everything else is nodes, properties and actions, which the general functions reach.

Your own rules and lines

// from: crates/rf-nodegraph/examples/guide_nodegraph.rs#validate
/// Your own rule for connections, and your own line for the wires.
pub fn rules(ui: &mut Ui, graph: NodeId) {
    // no wire from a node to itself is the graph's rule; this one adds:
    // a node takes at most one wire from each other node
    rf_nodegraph::set_validator(ui, graph, |c| c.from_node != c.to_node && &*c.to_port != "locked");
    // a wire as one straight line with a kink in the middle
    rf_nodegraph::set_edge_path(ui, graph, |e, out| {
        use renderfi::PathVerb::{LineTo, MoveTo};
        let mid = (e.from.0 + e.to.0) / 2.0;
        out.extend([MoveTo(e.from.0, e.from.1), LineTo(mid, e.from.1), LineTo(mid, e.to.1), LineTo(e.to.0, e.to.1)]);
        true
    });
}
  • set_validator runs while the user drags a wire and on the drop. It comes on top of the rule of the ports.
  • set_edge_path draws every wire. The function gets the two ends in graph units and adds path commands. Return false for an edge to get the line of its kind.

Styling

Everything is CSS. The default look reads these variables with fallbacks, so a theme or a skin of rf-widgets changes it: --rf-graph-bg, --rf-graph-grid, --rf-graph-text, --rf-graph-node, --rf-graph-node-line, --rf-graph-node-radius, --rf-graph-header, --rf-graph-title, --rf-graph-shadow, --rf-graph-port, --rf-graph-wire, --rf-graph-wire-width, --rf-graph-panel, --rf-graph-select (the selection box and the wire that is being pulled) and --rf-graph-lod (a node far away). --rf-minimap-node and --rf-minimap-view color the minimap.

node-graph { --rf-graph-grid: #303540; --rf-graph-select: #ffb43b }
graph-node { min-width: 160px; border-radius: 4px }
graph-node[selected] { border-color: #ffb43b }
node-port[kind=color] { background-color: #e0a13c }

The inspector shows the nodes, ports and edges as nodes of the tree. The wires in view are parts of the graph: node-graph >> edge (see inspecting.md). Screen readers get each wire as a link named noise.out to mix.a.

How fast

Measured with 5,000 nodes (56,000 UI nodes) and 6,600 wires at 1600 x 1000, the work of the UI thread for one frame (cargo run --release -p rf-nodegraph --example graph_bench; pass a number for another size):

what changes time
nothing 0 (no frame)
pan at zoom 1 0.24 ms
zoom 0.27 ms
drag one node 0.25 ms
a text in one node changes 1.4 ms
pan with all 5,000 nodes in view 0.28 ms
the first frame (style and layout of every node) 510 ms

How it gets there:

  • Pan and zoom are no layout. The graph draws the nodes in view in another place, and its wires through another transform. Nothing is styled, laid out or painted again.
  • Nodes out of view are not drawn. Only the nodes in view are in the frame's display list.
  • Far away, nodes are boxes. Below detail-zoom the graph hides the nodes and paints one rectangle per node. The wires stay.
  • One node costs one node. When a text or a property in a node changes, the graph reads and measures that node again, not the others, and makes new lines for the wires at it.
  • Wires are batches. All wires of one look are one path. While nodes are dragged, only their wires are made again each frame.

Write your own

The graph has no special access to the engine. It is a native widget made of blocks that any widget can use:

block
renderfi::native::Viewport pan and zoom: points to and from the plane, the transform for the painter, the matrix for a placed child
Children::place_with, WidgetCx::move_child place child nodes through the view; move them later with no layout
Children::changed(i) did this child change since it was placed? Read only those again
WidgetCx::rect_of(node) where layout put a node below the widget: the anchors of lines
WidgetCx::style_of(node), var_of(node, name), vars_changed_of the CSS of a child that carries the look of something the widget draws
WidgetCx::pointer_target() the node under the pointer, for a widget that sees the pointer over its children
WidgetCx::set_on(node, name, value), request_repaint_of(node) set a property of a child, ask another native widget to paint again
renderfi::links line shapes between two anchors (link), the distance of a point to a path (distance: the hit test of a line), the point at a part of a path (point_at)
Painter::stroke_path stroke a kept path with caps, joins and dashes: many lines, one draw command

A small widget from the same blocks: cards placed by attributes, a line from each card to the next, and a drag that pans.

// from: crates/rf-nodegraph/examples/guide_nodegraph.rs#own
use renderfi::links::{self, LinkShape, Side};
use renderfi::native::{Children, Event, Handled, NativeWidget, Paint, Painter, Rect, Size, StrokeStyle, Viewport, WidgetCx};
use renderfi::{Path, PathVerb};
use std::sync::Arc;

/// `<link-board>`: its children are cards at `left` and `top`; it draws a
/// line from each card to the next one, and a drag pans. The same blocks
/// as the node graph, in 60 lines.
#[derive(Default)]
pub struct LinkBoard {
    view: Viewport,
    /// All lines as one path: made again only when a card moved.
    lines: Option<Arc<Path>>,
    drag: Option<(f32, f32)>,
}

impl NativeWidget for LinkBoard {
    fn places_children(&self) -> bool {
        true
    }

    /// Each child goes where its `data-x` and `data-y` say, through the view.
    fn layout(&mut self, cx: &mut WidgetCx, _size: Size, children: &mut Children) {
        for i in 0..children.len() {
            let node = children.node(i);
            // (a free `data-` attribute is text)
            let at = |name: &str| cx.context().get(node, name).ok().and_then(|v| v.as_str()?.parse::<f32>().ok()).unwrap_or(0.0);
            let size = children.measure(i, Size::new(f32::INFINITY, f32::INFINITY));
            let rect = Rect::new(at("data-x"), at("data-y"), size.width, size.height);
            children.place_with(i, rect, self.view.child_matrix(rect), 1.0);
        }
        self.lines = None;
        cx.request_repaint();
    }

    fn paint(&mut self, cx: &mut WidgetCx, p: &mut Painter) {
        let lines = self.lines.get_or_insert_with(|| {
            // where layout put the children: the anchors of the lines
            let boxes: Vec<Rect> = cx.children().iter().filter_map(|&c| cx.rect_of(c)).collect();
            let mut verbs: Vec<PathVerb> = Vec::new();
            for pair in boxes.windows(2) {
                links::link(&mut verbs, (Side::Right.anchor(pair[0]), Side::Right), (Side::Left.anchor(pair[1]), Side::Left), LinkShape::Bezier);
            }
            Arc::new(Path::new(verbs))
        });
        // one draw command for all lines, through the same view as the children
        p.push_transform(self.view.transform());
        let style = StrokeStyle { width: 2.0, cap: renderfi::native::LineCap::Round, join: renderfi::native::LineJoin::Round, miter_limit: 4.0, dash: Arc::from([]), dash_offset: 0.0 };
        p.stroke_path(lines, Paint::Solid(cx.color_var("--rf-accent", 0xFF4A_8CFF)), style);
        p.pop_transform();
    }

    fn event(&mut self, cx: &mut WidgetCx, event: &Event) -> Handled {
        match *event {
            Event::PointerDown { x, y, .. } => self.drag = Some((x, y)),
            Event::PointerMove { x, y, .. } if self.drag.is_some() => {
                let last = self.drag.replace((x, y)).unwrap();
                self.view.pan = (self.view.pan.0 + x - last.0, self.view.pan.1 + y - last.1);
                // no layout: the children are drawn in another place
                let boxes: Vec<Option<Rect>> = cx.children().iter().map(|&c| cx.rect_of(c)).collect();
                for (i, rect) in boxes.into_iter().enumerate() {
                    if let Some(rect) = rect {
                        cx.move_child(i, self.view.child_matrix(rect), 1.0);
                    }
                }
                cx.request_repaint();
            }
            Event::PointerUp { .. } => self.drag = None,
            _ => return Handled::No,
        }
        Handled::Yes
    }
}

/// The board in a page: two cards and the line between them. Returns
/// where the second card is drawn before and after a pan by (30, 10).
pub fn link_board() -> ((f32, f32), (f32, f32)) {
    let mut ui = Ui::new();
    ui.register_native("link-board", "box", Vec::new(), &[], |_| Box::new(LinkBoard::default())).expect("link-board");
    let root = ui
        .load_markup(
            r##"<box style="background-color: #16181c; color: #d8dbe0">
  <style> .card { padding: 8 12; border-radius: 6; background-color: #2a2e35 } </style>
  <link-board id="board" style="width: 400; height: 200">
    <box class="card" data-x="20" data-y="30"><text>From</text></box>
    <box id="to" class="card" data-x="240" data-y="120"><text>To</text></box>
  </link-board>
</box>"##,
        )
        .expect("markup");
    ui.set_root(root).unwrap();
    ui.update(400.0, 200.0);
    let at = |ui: &Ui| ui.screen_rect(ui.find("to").unwrap()).map(|r| (r.x, r.y)).unwrap();
    let before = at(&ui);
    ui.input(Input::PointerMove { x: 300.0, y: 30.0 });
    ui.input(Input::PointerDown { x: 300.0, y: 30.0, button: PointerButton::Primary, mods: Modifiers::default() });
    ui.input(Input::PointerMove { x: 330.0, y: 40.0 });
    ui.input(Input::PointerUp { x: 330.0, y: 40.0, button: PointerButton::Primary });
    ui.update(400.0, 200.0);
    assert!(!ui.stats().relayout, "a pan is no layout");
    ui.render_to_image(&picture("link_board.png"), &renderfi::ImageOptions::new(400, 200)).expect("png");
    assert!(ui.take_warnings().is_empty(), "{:?}", ui.take_warnings());
    (before, at(&ui))
}