slint-node-editor 1.0.0

A flexible, generic Slint component library for building visual graph editors
Documentation
# Component reference

[README](../README.md) · [Integration guide](integration-guide.md)

Components: [NodeEditor](#nodeeditor), [BaseNode](#basenode), [Pin](#pin),
[Link](#link). Rust helpers: [NodeEditorController](#nodeeditorcontroller),
[GeometryTracker](#geometrytracker), [Sugiyama layout](#sugiyama-layout).

## NodeEditor

`NodeEditor` inherits `FocusScope`; call `editor.focus()` to focus it
programmatically. For press focus, expose this function on the window:

```slint
public function focus-editor() {
    editor.focus();
}
```

`wire_node_editor!` connects `NodeEditorInternalCallbacks.take-editor-focus`
to that function. Manual integrations must install the same synchronous
callback. Canvas, node, pin, minimap, and reserved marquee presses focus the
editor; embedded controls that accept the press retain their own focus.
Application callbacks may then move focus elsewhere. Do not defer this callback:
a delayed focus request can steal focus from a newly opened control.

Key bindings remain application-owned. Handle them in a parent `FocusScope`.

**Properties:**
```slint
in-out property <length> pan-x;          // Pan offset (x)
in-out property <length> pan-y;          // Pan offset (y)
in-out property <float> zoom;            // Zoom factor (1.0 = 100%)
in property <float> min-zoom: 0.1;       // Minimum zoom level
in property <float> max-zoom: 3.0;       // Maximum zoom level

// Host-side convenience values: pass these to custom node delegates that
// implement LOD or minimum sizing. NodeEditor does not resize nodes itself.
in property <float> lod-full-threshold: 0.5;
in property <float> lod-simplified-threshold: 0.25;
in property <length> min-node-width: 80px;
in property <length> min-node-height: 40px;

in property <length> grid-spacing: 24px;       // Grid cell size
in property <color> grid-color: #404040;       // Grid line color
in property <brush> background-color: #1a1a1a; // Background color

in property <length> link-hover-distance: 8px; // Click tolerance for links
in property <length> pin-hit-radius: 10px;     // Hit radius for pins
in property <int> link-hit-samples: 20;        // Bezier samples for hit-testing
in property <float> bezier-min-offset: 50.0;   // Min horizontal offset for curves
in property <bool> box-selection-on-empty: true;
in property <BoxSelectionModifier> box-selection-modifier: BoxSelectionModifier.ctrl;

// Minimap
in property <bool> minimap-enabled: false;
in property <MinimapPosition> minimap-position: bottom-right;

// Selection lives in the application — see "Callbacks (Selection)" below.
// The editor stores none of it; `selected` is per-row data on your node models
// and on LinkData.

// Geometry & Rendering
in-out property <string> grid-commands;         // SVG path generated by wire_node_editor!
in-out property <int> geometry-version <=> GeometryVersion.version;
in property <[MinimapNode]> minimap-nodes: [];  // Minimap data
in-out property <length> graph-min-x;           // Graph bounds
in-out property <length> graph-max-x;
in-out property <length> graph-min-y;
in-out property <length> graph-max-y;

// State outputs (read-only)
out property <bool> is-selecting;               // User is dragging selection box
out property <length> selection-x;              // Selection box position
out property <length> selection-y;
out property <length> selection-width;          // Selection box size
out property <length> selection-height;

out property <bool> is-creating-link;           // User is dragging to create link
out property <length> link-start-x;             // Link preview start
out property <length> link-start-y;
out property <length> link-end-x;               // Link preview end
out property <length> link-end-y;
out property <int> link-start-pin-id;           // Which pin started the link

out property <length> context-menu-x;           // Right-click position
out property <length> context-menu-y;

out property <int> hovered-link-id;             // Link under mouse
```

**Callbacks (Computation):**

Link picking remains a host callback because it needs the host's link model:

```slint
/// Compute which link is at world position (x, y)
callback compute-link-at(x: length, y: length) -> int;
```

The standard Rust computations live on the exported
`NodeEditorComputations` global. `wire_node_editor!` installs their default
implementations and synchronizes `grid-spacing` and `bezier-min-offset` with
the controller. Applications that replace a handler do so on this global; the
last installed handler wins.

```slint
NodeEditorComputations.compute-pin-at(world-x, world-y, world-radius);
NodeEditorComputations.compute-link-path(start-pin, end-pin, geometry-version); // world geometry
NodeEditorComputations.compute-link-preview-path(screen-start-x, screen-start-y,
                                                  screen-end-x, screen-end-y,
                                                  zoom, world-offset);
NodeEditorComputations.request-grid-update();
```

BaseNode double-clicks are emitted through the exported public event global:

```slint
NodeEditorEvents.node-double-clicked(node-id) => { /* handle event */ }
```

**Callbacks (Selection):**

Selection lives in the `selected` fields of your node rows and `LinkData`.
The editor reports gestures and renders those flags; `wire_selection!` updates
them using the standard selection policy.

```slint
/// A node was clicked (or dragged while unselected):
/// replace the selection with it, or toggle it when shift-held
callback node-selected(node-id: int, shift-held: bool);

/// A link was clicked — same semantics
callback select-link(link-id: int, shift-held: bool);

/// The background was clicked: drop the whole selection
callback selection-cleared();

/// A marquee was released over this world-coordinate rectangle:
/// hit-test it and select the hits, extending the selection when shift-held
callback box-selection-committed(x: length, y: length, w: length, h: length, shift-held: bool);
```

Handlers for selection intents that can affect a subsequent drag must update
the rows' `selected` flags before returning; the live multi-node preview and
drag commit read those flags. `wire_selection!` provides this behavior.
Applications that defer selection projection must also own their drag policy
and commit. Selection changes during an active drag are otherwise unspecified.

On the Rust side the `selection` module holds the policy — `resolve_click` and
`resolve_box` turn a gesture and the current set into the new set, and
`project_selection` writes a set into the rows. Every intent resolves to an
**absolute set**, never a delta, and both resolvers are order-stable.

`wire_selection!` composes them for the common case — rows with `id` and
`selected` fields — and keeps no state of its own. This wiring fragment uses
the models and setup constructed in the [quick start](integration-guide.md):

```rust
let setup = NodeEditorSetup::new({
    let nodes = nodes.clone();
    move |dragged, dx, dy| GraphLogic::commit_drag(&nodes, dragged, dx, dy)
});

wire_node_editor!(window, setup);
wire_selection!(window, setup, nodes);          // nodes only
wire_selection!(window, setup, nodes, links);   // …or nodes and links
```

Applications with several node models or their own gesture semantics wire the
four callbacks by hand out of the `selection` module — see the `advanced`
example, which spans two node models sharing one id space.

`GraphLogic::commit_drag` moves the dragged
node plus every row the model shows as selected, which is the same data the
editor renders.

`box-selection-modifier` reserves a left-button marquee over every editor
surface, including links, nodes, pins, and controls embedded in nodes. `ctrl`
also accepts Command/Meta. `none` reserves no gestures; ordinary input reaches
each surface and `box-selection-on-empty` still controls background marquees.
The editor observes modifier keys without consuming them, so application
shortcuts continue to receive the same key events.

Pointer cancellation, release outside, focus loss, hiding, and disabling clear
transient drag, link, pan, context-menu, and marquee state. A host that removes
an editor conditionally should call `cancel-interactions()` before removal.

**Callbacks (Events):**

```slint
/// User completed a link (dragged from one pin to another)
callback link-requested(start-pin-id: int, end-pin-id: int);

/// The host cancelled link creation through cancel-link-creation()
callback link-cancelled();

/// User hovered over a link
callback link-hovered();

/// User right-clicked (context menu)
callback context-menu-requested();
```

**Functions (Helper API):**

```slint
/// Report node geometry through the canonical lifecycle and schedule a refresh.
function report-node-rect(id: int, x: length, y: length, w: length, h: length);

/// Report pin geometry through the canonical lifecycle and schedule a refresh.
function report-pin-position(pin-id: int, node-id: int, pin-type: int, rel-x: length, rel-y: length);

/// Start link creation from a pin
function start-link-from-pin(pin_id: int, x: length, y: length);

/// Update link end position during creation
function update-link-end(x: length, y: length);

/// Complete link creation (checks for pin at end pos)
function complete-link-creation();

/// Force re-computation of all link paths
function refresh-links();
```

## BaseNode

Base component for creating custom nodes. Provides drag handling and selection.

**Properties:**
```slint
in property <int> node-id;             // Unique node ID
in property <length> world-x;          // X position in graph space
in property <length> world-y;          // Y position in graph space
in property <bool> selected: false;    // Selection state — bind it from your model row
in property <length> node-width: 150px;
in property <length> node-height: 100px;
out property <length> screen-x;         // Includes the current global zoom/pan
out property <length> screen-y;
```

`BaseNode` reads zoom and pan from `ViewportState`; consumers do not pass those
values into each node.

## Pin

Represents a connection point on a node.

**Properties:**
```slint
in property <int> pin-id;           // Pin ID (encoded by application)
in property <int> node-id;          // Parent node ID
in property <int> pin-type;         // PinTypes.input or .output (or custom)
in property <color> base-color: #888;
in property <color> hover-color: #aaa;
in property <length> node-screen-x; // Required for drag handling
in property <length> node-screen-y; // Required for drag handling
in property <length> parent-offset-x: 0px; // For pins inside wrappers
in property <length> parent-offset-y: 0px;
in property <int> refresh-trigger: 0;      // Force geometry re-reporting
```

## Link

Renders a Bezier curve between two pins. Used internally by `NodeEditor` but can be used for custom rendering.

The element is sized to the curve, not to the canvas. That is what lets a
partial renderer repaint one link's strip instead of the whole graph — so a
`LinkPath` whose box does not contain what its `commands` draw leaves stale
pixels. `Link` pads the box for the stroke itself; the box is the centreline's.

**Properties:**
```slint
in property <LinkPath> geometry;           // commands relative to x/y, plus the box
in property <color> link-color: #888;
in property <length> line-width: 2px;
in property <bool> selected: false;
in property <bool> hovered: false;
```

**`LinkPath`:**
```slint
struct LinkPath {
    commands: string,   // SVG path, relative to x/y (e.g., "M 0 0 C 50 50 100 100")
    x: length, y: length,
    width: length, height: length,
}
```

`CubicBezier::to_link_path` takes a constructor closure so it works with either
the crate's `LinkPath` or a locally generated Slint type. Supply the endpoints
and your `LinkPath` type:

```rust
use slint_node_editor::path::CubicBezier;

let curve = CubicBezier::from_endpoints(sx, sy, ex, ey, 1.0, 50.0);
curve.to_link_path(|commands, x, y, width, height| LinkPath {
    commands: commands.into(),
    x,
    y,
    width,
    height,
})
```

## Rust helpers

The library provides Rust helpers to reduce boilerplate.

### NodeEditorController

The `NodeEditorController` is a high-level helper that manages geometry tracking, zoom state, and link path computation. It provides ready-to-use callback implementations.

```rust
// Fragment from the quick start linked above.
let setup = NodeEditorSetup::new(move |dragged, dx, dy| {
    GraphLogic::commit_drag(&nodes, dragged, dx, dy);
});
let controller = setup.controller().clone();
wire_node_editor!(window, setup);
```

Prefer `NodeEditorSetup` plus `wire_node_editor!` for the standard integration.
Use the cloned controller for host policies such as validation, custom picking
and deletion. If an application wires globals manually, the macro source in
[`src/lib.rs`](../src/lib.rs) is the canonical list of handlers and units.

Node and pin geometry is a projection of the application's graph model. Retire
that projection whenever the model removes an object, and reset it after
replacing the whole graph. This fragment uses the generated window and IDs
from the [quick start](integration-guide.md):

```rust
let lifecycle = window.global::<NodeEditorInternalCallbacks>();

// Remove connected logical links in the host model, then:
lifecycle.invoke_remove_pin(pin_id);
lifecycle.invoke_remove_node(node_id); // also retires pins owned by the node

// After installing another graph model (including one that reuses IDs):
lifecycle.invoke_reset_graph();
```

These functions also clear editor interactions that refer to retired objects.
Call the controller's `remove_pin`, `remove_node`, or `reset_graph` methods when
there is no Slint component instance. A hidden or disabled `Pin` remains
available to route existing links, but it is excluded from pin hit testing
until eligible again. Pin picking chooses the nearest eligible pin within the
radius; exact distance ties choose the lowest pin ID, independent of cache
insertion order.

### GeometryTracker

For lower-level integrations without `NodeEditorSetup`, `GeometryTracker`
provides callback closures that update a standalone cache. This fragment leaves
the application's IDs and world-space coordinates as local variables:

```rust
use slint_node_editor::GeometryTracker;

let tracker = GeometryTracker::new();
let report_node = tracker.node_rect_callback();
let report_pin = tracker.pin_position_callback();

report_node(node_id, x, y, width, height);
report_pin(pin_id, node_id, pin_type, relative_x, relative_y);
let cache = tracker.cache();
```

All coordinates in these callbacks are world-space `f32` values. When using
live `BaseNode` and `Pin` components, `wire_node_editor!` already installs the
equivalent lifecycle and a second tracker is unnecessary.

### Sugiyama layout

Enable the `layout` Cargo feature to use these helpers.

`sugiyama_layout` accepts node-ID edges;
`sugiyama_layout_from_cache` accepts pin-ID edges resolved through a
`GeometryCache`. Both entry points produce the same canonical result: the
first size for each node ID wins, valid nodes and edges are ordered by ID,
and duplicate edges, self-loops, and edges with missing endpoints are ignored.
Nodes with non-finite or non-positive dimensions are omitted. Disconnected
components are ordered by their lowest node ID and packed along the axis
perpendicular to the layout direction without overlap.