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//! - `Minimap` - Bird's-eye view component
42//!
43//! ## Accessibility
44//!
45//! Library components include accessibility roles for screen readers and MCP
46//! introspection. When creating custom node components, set `accessible-label`
47//! to the node's display title:
48//!
49//! ```slint
50//! component MyNode inherits BaseNode {
51//!     in property <string> title;
52//!     accessible-label: title;  // override default "Node <id>"
53//! }
54//! ```
55//!
56//! ## Rust Helpers
57//!
58//! This crate provides Rust helper functions for common operations:
59//!
60//! - [`generate_grid_commands`] - Generate SVG path for grid rendering
61//! - [`generate_bezier_path`] - Generate SVG path for bezier curves
62//! - [`find_pin_at`] - Hit-test pins in a shared coordinate space
63//! - [`find_link_route_at`] - Hit-test rendered link routes in a shared coordinate space
64//! - [`GeometryCache`] - Cache node and pin geometry for fast lookups
65//! - [`selection`] - Resolve selection gestures and project the result into rows
66//! - [`GraphLogic`] - Helper for managing node graph state
67//!
68//! ## Limitations
69//!
70//! **One NodeEditor per window.** The library uses Slint globals (`ViewportState`,
71//! `DragState`, `NodeEditorInternalCallbacks`, etc.) for internal communication between
72//! `BaseNode`/`Pin` components and the `NodeEditor`. Since Slint globals are
73//! window-level singletons, only one `NodeEditor` instance per `Window` is
74//! supported. Multiple editors in separate windows work fine. This limitation
75//! will be lifted once Slint introduces component-scoped globals.
76//!
77//! See the [README](https://github.com/tilladam/slint-node-editor)
78//! for detailed documentation and examples.
79
80/// The Slint components, compiled as a library module.
81///
82/// A Slint consumer reaches these through `import { … } from "@nodeeditor";`
83/// and never names this module directly — but the code the Slint compiler
84/// generates on their side resolves to `slint_node_editor::nodeeditor::…`,
85/// so the path has to exist and has to match `rust_module` in `build.rs`.
86pub mod nodeeditor {
87    include!(concat!(env!("OUT_DIR"), "/node-editor.rs"));
88}
89
90pub mod controller;
91pub mod graph;
92pub mod grid;
93pub mod hit_test;
94#[cfg(feature = "layout")]
95pub mod layout;
96pub mod links;
97pub mod path;
98pub mod selection;
99pub mod setup;
100pub mod state;
101pub mod tracking;
102
103// Re-export the data types declared in the Slint sources.
104//
105// A consumer's own generated code re-exports the *globals* it imports from
106// `@nodeeditor` but not the structs and enums (slint 1.18's `as_library`
107// forwards those only into its private inner module), so without this a
108// consumer building a `LinkData` has no name to reach for.
109pub use nodeeditor::{
110    BoxSelectionModifier, LinkCreationState, LinkData, LinkPath, MinimapNode, MinimapPosition,
111};
112
113// Re-export traits and functions
114pub use grid::generate_grid_commands;
115pub use hit_test::{
116    distance_to_polyline, find_link_at, find_link_route_at, find_pin_at, links_in_selection_box,
117    nodes_in_selection_box, BezierLinkRoute, LinkGeometry, LinkRoute, NodeGeometry, PinGeometry,
118    PolylineLinkRoute, SimpleLinkGeometry, SimpleNodeGeometry,
119};
120pub use path::{generate_bezier_path, generate_partial_bezier_path};
121pub use state::{GeometryCache, StoredPin};
122// `selection` is deliberately NOT re-exported at the crate root: it is the
123// host's half of selection, a family of its own, and a bare `resolve_click`
124// would say nothing about what it resolves.
125pub use controller::NodeEditorController;
126pub use graph::{
127    validate_and_normalize_link,
128    BasicLinkValidator,
129    CompositeValidator,
130    GraphLogic,
131    LinkModel,
132    // Link validation framework
133    LinkValidator,
134    MovableNode,
135    NoDuplicatesValidator,
136    NormalizedLink,
137    SimpleLink,
138    ValidationError,
139    ValidationResult,
140};
141#[cfg(feature = "layout")]
142pub use layout::{
143    sugiyama_layout, sugiyama_layout_from_cache, Direction, NodePosition, SugiyamaConfig,
144};
145pub use links::LinkManager;
146pub use setup::NodeEditorSetup;
147pub use tracking::GeometryTracker;
148
149/// Wire up all NodeEditor callbacks with a single macro call.
150///
151/// This macro sets up default behavior for geometry tracking, computations, grid updates,
152/// and keyboard focus on editor presses.
153/// You can override any callback after calling this macro - the last `.on_*()` call wins.
154///
155/// The window must expose `grid-commands`, `width_`, `height_`, and
156/// `public function focus-editor() { editor.focus(); }`.
157///
158/// # Generated-UI integration
159///
160/// This fragment assumes the generated globals and window members from the
161/// [compiled quick start](https://github.com/tilladam/slint-node-editor/tree/main/smoke/downstream).
162///
163/// ```text
164/// use slint_node_editor::{NodeEditorSetup, wire_node_editor};
165///
166/// let setup = NodeEditorSetup::new(|node_id, dx, dy| {
167///     // Update your model
168/// });
169///
170/// wire_node_editor!(window, setup);
171///
172/// // Override specific callbacks if needed:
173/// // window.global::<NodeEditorComputations>().on_compute_pin_at(|x, y, radius| { ... });
174/// ```
175#[macro_export]
176macro_rules! wire_node_editor {
177    ($window:expr, $setup:expr) => {{
178        // Geometry tracking
179        let gc = $window.global::<NodeEditorInternalCallbacks>();
180        gc.on_report_node_rect($setup.report_node_rect());
181        gc.on_report_pin_position($setup.report_pin_position());
182        gc.on_remove_node_from_cache($setup.remove_node());
183        gc.on_remove_pin_from_cache($setup.remove_pin());
184        gc.on_reset_graph_cache($setup.reset_graph());
185        gc.on_start_node_drag($setup.start_node_drag());
186        gc.on_cancel_node_drag($setup.cancel_node_drag());
187        gc.on_end_node_drag($setup.end_node_drag());
188
189        // Focus synchronously, before the press's consequences can focus another control.
190        let w = $window.as_weak();
191        gc.on_take_editor_focus(move || {
192            if let Some(w) = w.upgrade() {
193                w.invoke_focus_editor();
194            }
195        });
196
197        // Computations
198        let computations = $window.global::<NodeEditorComputations>();
199        computations.on_compute_link_path($setup.controller().compute_link_path_callback(
200            |commands, x, y, width, height| LinkPath {
201                commands: commands.into(),
202                x,
203                y,
204                width,
205                height,
206            },
207        ));
208
209        let ctrl = $setup.controller().clone();
210        computations
211            .on_compute_pin_at(move |x, y, radius| ctrl.cache().borrow().find_pin_at(x, y, radius));
212
213        computations.on_compute_link_preview_path(
214            |start_x, start_y, end_x, end_y, zoom, bezier_offset| {
215                $crate::generate_bezier_path(start_x, start_y, end_x, end_y, zoom, bezier_offset)
216                    .into()
217            },
218        );
219
220        // Keep the Rust controller aligned with the component's public settings.
221        $setup
222            .controller()
223            .set_grid_spacing(computations.get_grid_spacing());
224        $setup
225            .controller()
226            .set_bezier_offset(computations.get_bezier_min_offset());
227
228        let ctrl = $setup.controller().clone();
229        computations.on_configuration_changed(move |grid_spacing, bezier_offset| {
230            ctrl.set_grid_spacing(grid_spacing);
231            ctrl.set_bezier_offset(bezier_offset);
232        });
233
234        // Viewport state and grid generation are separate public contracts:
235        // viewport changes update coordinates, while request-grid-update also
236        // covers resize and spacing changes.
237        let ctrl = $setup.controller().clone();
238        computations.on_viewport_changed(move |zoom, pan_x, pan_y| {
239            ctrl.set_viewport(zoom, pan_x, pan_y);
240        });
241
242        let ctrl = $setup.controller().clone();
243        let w = $window.as_weak();
244        computations.on_request_grid_update(move || {
245            if let Some(w) = w.upgrade() {
246                w.set_grid_commands(ctrl.generate_current_grid(w.get_width_(), w.get_height_()));
247            }
248        });
249
250        // Initial grid
251        let ctrl = $setup.controller().clone();
252        let w = $window.as_weak();
253        if let Some(w) = w.upgrade() {
254            w.set_grid_commands(ctrl.generate_current_grid(w.get_width_(), w.get_height_()));
255        }
256    }};
257}
258
259/// Wire the editor's selection intents, using your model rows as the store.
260///
261/// The editor holds no selection state: it reports gestures (`node-selected`,
262/// `select-link`, `selection-cleared`, `box-selection-committed`) and renders
263/// whatever `selected` flag it finds on the rows. This macro closes that loop
264/// without introducing a second copy of the selection — each gesture reads the
265/// current set back out of the rows, resolves it through
266/// [`resolve_click`] / [`resolve_box`], and projects the result in. There is
267/// nothing to keep in sync, because there is only ever one record of what is
268/// selected.
269///
270/// Rows need an `id` and a `selected` field.
271///
272/// Two arms: node selection alone, or nodes and links together. Applications
273/// with several node models or their own gesture semantics wire the four
274/// callbacks by hand out of the [`selection`] module — see the `advanced`
275/// example.
276///
277/// [`resolve_click`]: crate::selection::resolve_click
278/// [`resolve_box`]: crate::selection::resolve_box
279/// [`selection`]: crate::selection
280///
281/// # Generated-UI integration
282///
283/// This fragment assumes the generated callbacks and models from the
284/// [compiled quick start](https://github.com/tilladam/slint-node-editor/tree/main/smoke/downstream).
285///
286/// ```text
287/// wire_node_editor!(window, setup);
288/// wire_selection!(window, setup, nodes);
289/// // …or, with selectable links:
290/// wire_selection!(window, setup, nodes, links);
291/// ```
292#[macro_export]
293macro_rules! wire_selection {
294    ($window:expr, $setup:expr, $nodes:expr) => {{
295        // `select-link` is deliberately not wired: the editor only emits it
296        // when the host opts into `has-link-selection`, and a host doing that
297        // wants the four-argument arm.
298
299        $window.on_node_selected({
300            let nodes = $nodes.clone();
301            move |node_id, shift| {
302                $crate::selection::apply_click(
303                    &nodes,
304                    |n| n.id,
305                    |n| &mut n.selected,
306                    node_id,
307                    shift,
308                )
309            }
310        });
311
312        $window.on_selection_cleared({
313            let nodes = $nodes.clone();
314            move || $crate::selection::clear_selection(&nodes, |n| &mut n.selected)
315        });
316
317        $window.on_box_selection_committed({
318            let nodes = $nodes.clone();
319            let ctrl = $setup.controller().clone();
320            move |x, y, w, h, shift| {
321                let hits = ctrl.cache().borrow().nodes_in_selection_box(x, y, w, h);
322                $crate::selection::apply_box(&nodes, |n| n.id, |n| &mut n.selected, hits, shift)
323            }
324        });
325    }};
326
327    ($window:expr, $setup:expr, $nodes:expr, $links:expr) => {{
328        // A plain click is exclusive across kinds — picking a node drops the
329        // links and vice versa. Shift means "add to what I have", so it leaves
330        // the other kind standing: the same mixed selection a shift-marquee
331        // builds, which is also what a delete then acts on.
332        $window.on_node_selected({
333            let nodes = $nodes.clone();
334            let links = $links.clone();
335            move |node_id, shift| {
336                if !shift {
337                    $crate::selection::clear_selection(&links, |l| &mut l.selected);
338                }
339                $crate::selection::apply_click(
340                    &nodes,
341                    |n| n.id,
342                    |n| &mut n.selected,
343                    node_id,
344                    shift,
345                )
346            }
347        });
348
349        $window.on_select_link({
350            let nodes = $nodes.clone();
351            let links = $links.clone();
352            move |link_id, shift| {
353                if !shift {
354                    $crate::selection::clear_selection(&nodes, |n| &mut n.selected);
355                }
356                $crate::selection::apply_click(
357                    &links,
358                    |l| l.id,
359                    |l| &mut l.selected,
360                    link_id,
361                    shift,
362                )
363            }
364        });
365
366        $window.on_selection_cleared({
367            let nodes = $nodes.clone();
368            let links = $links.clone();
369            move || {
370                $crate::selection::clear_selection(&nodes, |n| &mut n.selected);
371                $crate::selection::clear_selection(&links, |l| &mut l.selected);
372            }
373        });
374
375        $window.on_box_selection_committed({
376            let nodes = $nodes.clone();
377            let links = $links.clone();
378            let ctrl = $setup.controller().clone();
379            move |x, y, w, h, shift| {
380                let (node_hits, link_hits) = {
381                    let cache = ctrl.cache();
382                    let cache = cache.borrow();
383                    let rows = (0..slint::Model::row_count(&*links))
384                        .filter_map(|i| slint::Model::row_data(&*links, i))
385                        .map(|l| (l.id, l.start_pin_id, l.end_pin_id));
386                    (
387                        cache.nodes_in_selection_box(x, y, w, h),
388                        cache.links_in_selection_box(x, y, w, h, rows),
389                    )
390                };
391                $crate::selection::apply_box(
392                    &nodes,
393                    |n| n.id,
394                    |n| &mut n.selected,
395                    node_hits,
396                    shift,
397                );
398                $crate::selection::apply_box(
399                    &links,
400                    |l| l.id,
401                    |l| &mut l.selected,
402                    link_hits,
403                    shift,
404                )
405            }
406        });
407    }};
408}