Skip to main content

slint_node_editor/
lib.rs

1//! # Slint Node Editor Library
2//!
3//! A flexible, generic Slint component library for building visual graph editors.
4//! Supports data flow diagrams, state machines, shader graphs, and any visual
5//! node-based interface.
6//!
7//! ## Features
8//!
9//! - **Generic Design** - Works with any node and link data structures
10//! - **Trait-Based Architecture** - Zero coupling via `NodeGeometry` and `LinkModel` traits
11//! - **Callback-Based Computation** - Delegates expensive operations to Rust for performance
12//! - **Opaque Pin IDs** - Library never prescribes pin encoding; applications choose
13//! - **Extensible** - Easy to customize pins, styling, node types, and behaviors
14//!
15//! ## Quick Start
16//!
17//! This is a composition fragment. The
18//! [compiled downstream quick start](https://github.com/tilladam/slint-node-editor/tree/main/smoke/downstream)
19//! contains the Cargo manifest, build script, Slint UI and Rust host.
20//!
21//! ```slint
22//! import { NodeEditor, BaseNode, Pin, PinTypes } from "@nodeeditor";
23//!
24//! export component MainWindow inherits Window {
25//!     NodeEditor {
26//!         // Your nodes and links here
27//!     }
28//! }
29//! ```
30//!
31//! ## Core Components
32//!
33//! These are Slint components, imported from `@nodeeditor`. Only the top-level
34//! editor has a generated Rust counterpart ([`nodeeditor::NodeEditor`]); the
35//! rest exist solely in `.slint`.
36//!
37//! - `NodeEditor` - Main graph editor component
38//! - `BaseNode` - Base component for creating custom nodes
39//! - `Pin` - Connection point component
40//! - `Link` - Bezier curve link component
41//! - `BaseGroup` / `GroupSheet` - Backing sheet behind a group of nodes
42//! - `Minimap` - Bird's-eye view component
43//!
44//! ## Accessibility
45//!
46//! Library components include accessibility roles for screen readers and MCP
47//! introspection. When creating custom node components, set `accessible-label`
48//! to the node's display title:
49//!
50//! ```slint
51//! component MyNode inherits BaseNode {
52//!     in property <string> title;
53//!     accessible-label: title;  // override default "Node <id>"
54//! }
55//! ```
56//!
57//! ## Rust Helpers
58//!
59//! This crate provides Rust helper functions for common operations:
60//!
61//! - [`generate_grid_commands`] - Generate SVG path for grid rendering
62//! - [`generate_bezier_path`] - Generate SVG path for bezier curves
63//! - [`find_pin_at`] - Hit-test pins in a shared coordinate space
64//! - [`find_link_route_at`] - Hit-test rendered link routes in a shared coordinate space
65//! - [`GeometryCache`] - Cache node and pin geometry for fast lookups
66//! - [`selection`] - Resolve selection gestures and project the result into rows
67//! - [`GraphLogic`] - Helper for managing node graph state
68//! - [`groups`] - Node groups: membership, movement, collapse and bounds
69//!
70//! ## Limitations
71//!
72//! **One NodeEditor per window.** The library uses Slint globals (`ViewportState`,
73//! `DragState`, `NodeEditorInternalCallbacks`, etc.) for internal communication between
74//! `BaseNode`/`Pin` components and the `NodeEditor`. Since Slint globals are
75//! window-level singletons, only one `NodeEditor` instance per `Window` is
76//! supported. Multiple editors in separate windows work fine. This limitation
77//! will be lifted once Slint introduces component-scoped globals.
78//!
79//! See the [README](https://github.com/tilladam/slint-node-editor)
80//! for detailed documentation and examples.
81
82/// The Slint components, compiled as a library module.
83///
84/// A Slint consumer reaches these through `import { … } from "@nodeeditor";`
85/// and never names this module directly — but the code the Slint compiler
86/// generates on their side resolves to `slint_node_editor::nodeeditor::…`,
87/// so the path has to exist and has to match `rust_module` in `build.rs`.
88pub mod nodeeditor {
89    include!(concat!(env!("OUT_DIR"), "/node-editor.rs"));
90}
91
92pub mod controller;
93pub mod graph;
94pub mod grid;
95pub mod groups;
96pub mod hit_test;
97#[cfg(feature = "layout")]
98pub mod layout;
99pub mod links;
100pub mod path;
101pub mod selection;
102pub mod setup;
103pub mod state;
104pub mod tracking;
105
106// Re-export the data types declared in the Slint sources.
107//
108// A consumer's own generated code re-exports the *globals* it imports from
109// `@nodeeditor` but not the structs and enums (slint 1.18's `as_library`
110// forwards those only into its private inner module), so without this a
111// consumer building a `LinkData` has no name to reach for.
112pub use nodeeditor::{
113    BoxSelectionModifier, GroupData, LinkCreationState, LinkData, LinkPath, MinimapNode,
114    MinimapPosition,
115};
116
117// Re-export traits and functions
118pub use grid::generate_grid_commands;
119pub use hit_test::{
120    distance_to_polyline, find_link_at, find_link_route_at, find_pin_at, links_in_selection_box,
121    nodes_in_selection_box, BezierLinkRoute, LinkGeometry, LinkRoute, NodeGeometry, PinGeometry,
122    PolylineLinkRoute, SimpleLinkGeometry, SimpleNodeGeometry,
123};
124pub use path::{generate_bezier_path, generate_partial_bezier_path};
125pub use state::{GeometryCache, StoredPin};
126// `selection` is deliberately NOT re-exported at the crate root: it is the
127// host's half of selection, a family of its own, and a bare `resolve_click`
128// would say nothing about what it resolves.
129pub use controller::NodeEditorController;
130pub use graph::{
131    validate_and_normalize_link,
132    BasicLinkValidator,
133    CompositeValidator,
134    GraphLogic,
135    LinkModel,
136    // Link validation framework
137    LinkValidator,
138    MovableNode,
139    NoDuplicatesValidator,
140    NormalizedLink,
141    SimpleLink,
142    ValidationError,
143    ValidationResult,
144};
145pub use groups::{Bounds, Dragged, GroupLogic, GroupMember, GroupModel};
146#[cfg(feature = "layout")]
147pub use layout::{
148    sugiyama_layout, sugiyama_layout_from_cache, Direction, NodePosition, RankAlignment,
149    SugiyamaConfig,
150};
151pub use links::LinkManager;
152pub use setup::NodeEditorSetup;
153pub use tracking::GeometryTracker;
154
155/// Wire up all NodeEditor callbacks with a single macro call.
156///
157/// This macro sets up default behavior for geometry tracking, computations, grid updates,
158/// and keyboard focus on editor presses.
159/// You can override any callback after calling this macro - the last `.on_*()` call wins.
160///
161/// The window must expose `grid-commands`, `width_`, `height_`, and
162/// `public function focus-editor() { editor.focus(); }`.
163///
164/// # Generated-UI integration
165///
166/// This fragment assumes the generated globals and window members from the
167/// [compiled quick start](https://github.com/tilladam/slint-node-editor/tree/main/smoke/downstream).
168///
169/// ```text
170/// use slint_node_editor::{NodeEditorSetup, wire_node_editor};
171///
172/// let setup = NodeEditorSetup::new(|node_id, dx, dy| {
173///     // Update your model
174/// });
175///
176/// wire_node_editor!(window, setup);
177///
178/// // Override specific callbacks if needed:
179/// // window.global::<NodeEditorComputations>().on_compute_pin_at(|x, y, radius| { ... });
180/// ```
181#[macro_export]
182macro_rules! wire_node_editor {
183    ($window:expr, $setup:expr) => {{
184        // Geometry tracking
185        let gc = $window.global::<NodeEditorInternalCallbacks>();
186        gc.on_report_node_rect($setup.report_node_rect());
187        gc.on_report_pin_position($setup.report_pin_position());
188        gc.on_remove_node_from_cache($setup.remove_node());
189        gc.on_remove_pin_from_cache($setup.remove_pin());
190        gc.on_reset_graph_cache($setup.reset_graph());
191        gc.on_start_node_drag($setup.start_node_drag());
192        gc.on_cancel_node_drag($setup.cancel_node_drag());
193        gc.on_end_node_drag($setup.end_node_drag());
194
195        // Groups: sheet geometry, the collapse visibility projection, and the
196        // sheet drag. The drag commit itself is installed by
197        // `setup.on_group_drag_committed` or `wire_groups!`.
198        gc.on_report_group_rect($setup.report_group_rect());
199        gc.on_remove_group_from_cache($setup.remove_group());
200        gc.on_set_node_hidden($setup.set_node_hidden());
201        gc.on_start_group_drag($setup.start_group_drag());
202        gc.on_end_group_drag($setup.end_group_drag());
203
204        // Focus synchronously, before the press's consequences can focus another control.
205        let w = $window.as_weak();
206        gc.on_take_editor_focus(move || {
207            if let Some(w) = w.upgrade() {
208                w.invoke_focus_editor();
209            }
210        });
211
212        // Computations
213        let computations = $window.global::<NodeEditorComputations>();
214        computations.on_compute_link_path($setup.controller().compute_link_path_callback(
215            |commands, x, y, width, height| LinkPath {
216                commands: commands.into(),
217                x,
218                y,
219                width,
220                height,
221            },
222        ));
223
224        let ctrl = $setup.controller().clone();
225        computations
226            .on_compute_pin_at(move |x, y, radius| ctrl.cache().borrow().find_pin_at(x, y, radius));
227
228        computations.on_compute_link_preview_path(
229            |start_x, start_y, end_x, end_y, zoom, bezier_offset| {
230                $crate::generate_bezier_path(start_x, start_y, end_x, end_y, zoom, bezier_offset)
231                    .into()
232            },
233        );
234
235        // Keep the Rust controller aligned with the component's public settings.
236        $setup
237            .controller()
238            .set_grid_spacing(computations.get_grid_spacing());
239        $setup
240            .controller()
241            .set_bezier_offset(computations.get_bezier_min_offset());
242
243        let ctrl = $setup.controller().clone();
244        computations.on_configuration_changed(move |grid_spacing, bezier_offset| {
245            ctrl.set_grid_spacing(grid_spacing);
246            ctrl.set_bezier_offset(bezier_offset);
247        });
248
249        // Viewport state and grid generation are separate public contracts:
250        // viewport changes update coordinates, while request-grid-update also
251        // covers resize and spacing changes. viewport-resized is left available
252        // for hosts that track the editor's dimensions independently of the grid.
253        let ctrl = $setup.controller().clone();
254        computations.on_viewport_changed(move |zoom, pan_x, pan_y| {
255            ctrl.set_viewport(zoom, pan_x, pan_y);
256        });
257
258        let ctrl = $setup.controller().clone();
259        let w = $window.as_weak();
260        computations.on_request_grid_update(move || {
261            if let Some(w) = w.upgrade() {
262                w.set_grid_commands(ctrl.generate_current_grid(w.get_width_(), w.get_height_()));
263            }
264        });
265
266        // Initial grid
267        let ctrl = $setup.controller().clone();
268        let w = $window.as_weak();
269        if let Some(w) = w.upgrade() {
270            w.set_grid_commands(ctrl.generate_current_grid(w.get_width_(), w.get_height_()));
271        }
272    }};
273}
274
275/// Wire the editor's selection intents, using your model rows as the store.
276///
277/// The editor holds no selection state: it reports gestures (`node-selected`,
278/// `select-link`, `selection-cleared`, `box-selection-committed`) and renders
279/// whatever `selected` flag it finds on the rows. This macro closes that loop
280/// without introducing a second copy of the selection — each gesture reads the
281/// current set back out of the rows, resolves it through
282/// [`resolve_click`] / [`resolve_box`], and projects the result in. There is
283/// nothing to keep in sync, because there is only ever one record of what is
284/// selected.
285///
286/// Rows need an `id` and a `selected` field.
287///
288/// Three arms: node selection alone, nodes and links together, or nodes,
289/// links and groups. Applications with several node models or their own
290/// gesture semantics wire the callbacks by hand out of the [`selection`]
291/// module — see the `advanced` example.
292///
293/// [`resolve_click`]: crate::selection::resolve_click
294/// [`resolve_box`]: crate::selection::resolve_box
295/// [`selection`]: crate::selection
296///
297/// # Generated-UI integration
298///
299/// This fragment assumes the generated callbacks and models from the
300/// [compiled quick start](https://github.com/tilladam/slint-node-editor/tree/main/smoke/downstream).
301///
302/// ```text
303/// wire_node_editor!(window, setup);
304/// wire_selection!(window, setup, nodes);
305/// // …or, with selectable links:
306/// wire_selection!(window, setup, nodes, links);
307/// // …or, with groups as well (the window exposes `group-selected`):
308/// wire_selection!(window, setup, nodes, links, groups);
309/// ```
310#[macro_export]
311macro_rules! wire_selection {
312    // A click on one kind: a plain click first clears every other kind (and
313    // the clicked kind itself, which the click then replaces), shift extends.
314    (@click $window:expr, $on:ident, $target:expr, [$($model:expr),*]) => {{
315        $window.$on({
316            let target = $target.clone();
317            let clearers: Vec<Box<dyn Fn()>> = vec![$({
318                let model = $model.clone();
319                Box::new(move || $crate::selection::clear_selection(&*model, |r| &mut r.selected))
320                    as Box<dyn Fn()>
321            }),*];
322            move |id, shift| {
323                if !shift {
324                    for clear in &clearers {
325                        clear();
326                    }
327                }
328                $crate::selection::apply_click(&*target, |r| r.id, |r| &mut r.selected, id, shift)
329            }
330        });
331    }};
332
333    // The background was clicked: every kind is dropped.
334    (@clear $window:expr, [$($model:expr),*]) => {{
335        $window.on_selection_cleared({
336            let clearers: Vec<Box<dyn Fn()>> = vec![$({
337                let model = $model.clone();
338                Box::new(move || $crate::selection::clear_selection(&*model, |r| &mut r.selected))
339                    as Box<dyn Fn()>
340            }),*];
341            move || {
342                for clear in &clearers {
343                    clear();
344                }
345            }
346        });
347    }};
348
349    // A marquee was released: each kind selects its own hits, computed by the
350    // given closure over the cache and the link rows `(id, start, end)`.
351    (@box $window:expr, $setup:expr, $links:expr, [$(($model:expr, $hits:expr)),*]) => {{
352        $window.on_box_selection_committed({
353            let ctrl = $setup.controller().clone();
354            let links = $links.clone();
355            let kinds: Vec<($crate::BoxApply, $crate::BoxHits)> = vec![$({
356                let model = $model.clone();
357                (
358                    $crate::box_apply(move |hits, shift| {
359                        $crate::selection::apply_box(&*model, |r| r.id, |r| &mut r.selected, hits, shift)
360                    }),
361                    $crate::box_hits($hits),
362                )
363            }),*];
364            move |x, y, w, h, shift| {
365                let rows: Vec<(i32, i32, i32)> = (0..slint::Model::row_count(&*links))
366                    .filter_map(|i| slint::Model::row_data(&*links, i))
367                    .map(|l| (l.id, l.start_pin_id, l.end_pin_id))
368                    .collect();
369                let hits: Vec<Vec<i32>> = {
370                    let cache = ctrl.cache();
371                    let cache = cache.borrow();
372                    kinds.iter().map(|(_, find)| find(&cache, x, y, w, h, &rows)).collect()
373                };
374                for ((apply, _), hits) in kinds.iter().zip(hits) {
375                    apply(hits, shift);
376                }
377            }
378        });
379    }};
380
381    ($window:expr, $setup:expr, $nodes:expr) => {{
382        // `select-link` is deliberately not wired: the editor only emits it
383        // when the host opts into `has-link-selection`, and a host doing that
384        // wants the four-argument arm.
385        $crate::wire_selection!(@click $window, on_node_selected, $nodes, []);
386        $crate::wire_selection!(@clear $window, [$nodes]);
387        $window.on_box_selection_committed({
388            let nodes = $nodes.clone();
389            let ctrl = $setup.controller().clone();
390            move |x, y, w, h, shift| {
391                let hits = ctrl.cache().borrow().nodes_in_selection_box(x, y, w, h);
392                $crate::selection::apply_box(&nodes, |n| n.id, |n| &mut n.selected, hits, shift)
393            }
394        });
395    }};
396
397    // A plain click is exclusive across kinds — picking a node drops the
398    // links and vice versa. Shift means "add to what I have", so it leaves
399    // the other kind standing: the same mixed selection a shift-marquee
400    // builds, which is also what a delete then acts on.
401    ($window:expr, $setup:expr, $nodes:expr, $links:expr) => {{
402        $crate::wire_selection!(@click $window, on_node_selected, $nodes, [$links]);
403        $crate::wire_selection!(@click $window, on_select_link, $links, [$nodes]);
404        $crate::wire_selection!(@clear $window, [$nodes, $links]);
405        $crate::wire_selection!(@box $window, $setup, $links, [
406            ($nodes, |cache, x, y, w, h, _rows| cache.nodes_in_selection_box(x, y, w, h)),
407            ($links, |cache, x, y, w, h, rows| cache.links_in_selection_box(x, y, w, h, rows.iter().copied()))
408        ]);
409    }};
410
411    // Groups join the same contract; a marquee selects sheets by rectangle
412    // intersection like nodes, and members hidden by a collapsed group are
413    // never marquee hits (the cache excludes them).
414    ($window:expr, $setup:expr, $nodes:expr, $links:expr, $groups:expr) => {{
415        $crate::wire_selection!(@click $window, on_node_selected, $nodes, [$links, $groups]);
416        $crate::wire_selection!(@click $window, on_select_link, $links, [$nodes, $groups]);
417        $crate::wire_selection!(@click $window, on_group_selected, $groups, [$nodes, $links]);
418        $crate::wire_selection!(@clear $window, [$nodes, $links, $groups]);
419        $crate::wire_selection!(@box $window, $setup, $links, [
420            ($nodes, |cache, x, y, w, h, _rows| cache.nodes_in_selection_box(x, y, w, h)),
421            ($links, |cache, x, y, w, h, rows| cache.links_in_selection_box(x, y, w, h, rows.iter().copied())),
422            ($groups, |cache, x, y, w, h, _rows| cache.groups_in_selection_box(x, y, w, h))
423        ]);
424    }};
425}
426
427/// Boxed "apply these marquee hits" step used by `wire_selection!`.
428#[doc(hidden)]
429pub type BoxApply = Box<dyn Fn(Vec<i32>, bool)>;
430/// Boxed "find the marquee hits of one kind" step used by `wire_selection!`.
431/// Arguments: the geometry cache, the world-space box, and the link rows as
432/// `(id, start_pin, end_pin)`.
433#[doc(hidden)]
434pub type BoxHits = Box<dyn Fn(&GeometryCache, f32, f32, f32, f32, &[(i32, i32, i32)]) -> Vec<i32>>;
435
436#[doc(hidden)]
437pub fn box_apply(f: impl Fn(Vec<i32>, bool) + 'static) -> BoxApply {
438    Box::new(f)
439}
440
441#[doc(hidden)]
442pub fn box_hits(
443    f: impl Fn(&GeometryCache, f32, f32, f32, f32, &[(i32, i32, i32)]) -> Vec<i32> + 'static,
444) -> BoxHits {
445    Box::new(f)
446}
447
448/// Wire node groups for a host with one node model and one group model.
449///
450/// Installs the three host answers the editor needs for groups:
451///
452/// - `NodeEditorComputations.group-in-drag`: does a group move with the
453///   current drag? Answered by [`GroupLogic::group_moves`], the same rule the
454///   commit uses, so the live preview and the committed positions agree.
455/// - `NodeEditorComputations.group-collapsed`: is a group collapsed? Members
456///   hide themselves from the answer.
457/// - `NodeEditorEvents.group-collapse-requested`: the sheet's toggle asked
458///   for an explicit collapsed state; applied with [`GroupLogic::set_collapsed`].
459///
460/// The drag commit is not wired here: build the setup with
461/// [`NodeEditorSetup::with_drag_commit`] so a node drag and a sheet drag
462/// share one rule. Node rows implement [`GroupMember`], group rows
463/// [`GroupModel`], and the window imports `NodeEditorEvents` and
464/// `NodeEditorComputations` from `@nodeeditor`. Hosts with several node
465/// models install the same three answers by hand.
466///
467/// # Generated-UI integration
468///
469/// ```text
470/// let setup = NodeEditorSetup::with_drag_commit({
471///     let (nodes, groups) = (nodes.clone(), groups.clone());
472///     move |dragged, dx, dy| GroupLogic::commit_drag(&nodes, &groups, dragged, dx, dy)
473/// });
474/// wire_node_editor!(window, setup);
475/// wire_selection!(window, setup, nodes, links, groups);
476/// wire_groups!(window, groups, nodes);
477/// ```
478#[macro_export]
479macro_rules! wire_groups {
480    ($window:expr, $groups:expr, $nodes:expr) => {{
481        let computations = $window.global::<NodeEditorComputations>();
482
483        computations.on_group_in_drag({
484            let groups = $groups.clone();
485            move |group_id, dragged_node_id, dragged_group_id| {
486                $crate::groups::GroupLogic::group_moves(
487                    &*groups,
488                    group_id,
489                    $crate::groups::Dragged::from_ids(dragged_node_id, dragged_group_id),
490                )
491            }
492        });
493
494        computations.on_group_collapsed({
495            let groups = $groups.clone();
496            move |group_id, _version| $crate::groups::GroupLogic::is_collapsed(&*groups, group_id)
497        });
498
499        $window
500            .global::<NodeEditorEvents>()
501            .on_group_collapse_requested({
502                let groups = $groups.clone();
503                let nodes = $nodes.clone();
504                move |group_id, collapsed| {
505                    $crate::groups::GroupLogic::set_collapsed(
506                        &groups,
507                        &nodes,
508                        group_id,
509                        collapsed,
510                        |n| &mut n.selected,
511                    );
512                }
513            });
514    }};
515}