slint-node-editor 1.0.0

A flexible, generic Slint component library for building visual graph editors
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! # Slint Node Editor Library
//!
//! A flexible, generic Slint component library for building visual graph editors.
//! Supports data flow diagrams, state machines, shader graphs, and any visual
//! node-based interface.
//!
//! ## Features
//!
//! - **Generic Design** - Works with any node and link data structures
//! - **Trait-Based Architecture** - Zero coupling via `NodeGeometry` and `LinkModel` traits
//! - **Callback-Based Computation** - Delegates expensive operations to Rust for performance
//! - **Opaque Pin IDs** - Library never prescribes pin encoding; applications choose
//! - **Extensible** - Easy to customize pins, styling, node types, and behaviors
//!
//! ## Quick Start
//!
//! This is a composition fragment. The
//! [compiled downstream quick start](https://github.com/tilladam/slint-node-editor/tree/main/smoke/downstream)
//! contains the Cargo manifest, build script, Slint UI and Rust host.
//!
//! ```slint
//! import { NodeEditor, BaseNode, Pin, PinTypes } from "@nodeeditor";
//!
//! export component MainWindow inherits Window {
//!     NodeEditor {
//!         // Your nodes and links here
//!     }
//! }
//! ```
//!
//! ## Core Components
//!
//! These are Slint components, imported from `@nodeeditor`. Only the top-level
//! editor has a generated Rust counterpart ([`nodeeditor::NodeEditor`]); the
//! rest exist solely in `.slint`.
//!
//! - `NodeEditor` - Main graph editor component
//! - `BaseNode` - Base component for creating custom nodes
//! - `Pin` - Connection point component
//! - `Link` - Bezier curve link component
//! - `Minimap` - Bird's-eye view component
//!
//! ## Accessibility
//!
//! Library components include accessibility roles for screen readers and MCP
//! introspection. When creating custom node components, set `accessible-label`
//! to the node's display title:
//!
//! ```slint
//! component MyNode inherits BaseNode {
//!     in property <string> title;
//!     accessible-label: title;  // override default "Node <id>"
//! }
//! ```
//!
//! ## Rust Helpers
//!
//! This crate provides Rust helper functions for common operations:
//!
//! - [`generate_grid_commands`] - Generate SVG path for grid rendering
//! - [`generate_bezier_path`] - Generate SVG path for bezier curves
//! - [`find_pin_at`] - Hit-test pins in a shared coordinate space
//! - [`find_link_route_at`] - Hit-test rendered link routes in a shared coordinate space
//! - [`GeometryCache`] - Cache node and pin geometry for fast lookups
//! - [`selection`] - Resolve selection gestures and project the result into rows
//! - [`GraphLogic`] - Helper for managing node graph state
//!
//! ## Limitations
//!
//! **One NodeEditor per window.** The library uses Slint globals (`ViewportState`,
//! `DragState`, `NodeEditorInternalCallbacks`, etc.) for internal communication between
//! `BaseNode`/`Pin` components and the `NodeEditor`. Since Slint globals are
//! window-level singletons, only one `NodeEditor` instance per `Window` is
//! supported. Multiple editors in separate windows work fine. This limitation
//! will be lifted once Slint introduces component-scoped globals.
//!
//! See the [README](https://github.com/tilladam/slint-node-editor)
//! for detailed documentation and examples.

/// The Slint components, compiled as a library module.
///
/// A Slint consumer reaches these through `import { … } from "@nodeeditor";`
/// and never names this module directly — but the code the Slint compiler
/// generates on their side resolves to `slint_node_editor::nodeeditor::…`,
/// so the path has to exist and has to match `rust_module` in `build.rs`.
pub mod nodeeditor {
    include!(concat!(env!("OUT_DIR"), "/node-editor.rs"));
}

pub mod controller;
pub mod graph;
pub mod grid;
pub mod hit_test;
#[cfg(feature = "layout")]
pub mod layout;
pub mod links;
pub mod path;
pub mod selection;
pub mod setup;
pub mod state;
pub mod tracking;

// Re-export the data types declared in the Slint sources.
//
// A consumer's own generated code re-exports the *globals* it imports from
// `@nodeeditor` but not the structs and enums (slint 1.18's `as_library`
// forwards those only into its private inner module), so without this a
// consumer building a `LinkData` has no name to reach for.
pub use nodeeditor::{
    BoxSelectionModifier, LinkCreationState, LinkData, LinkPath, MinimapNode, MinimapPosition,
};

// Re-export traits and functions
pub use grid::generate_grid_commands;
pub use hit_test::{
    distance_to_polyline, find_link_at, find_link_route_at, find_pin_at, links_in_selection_box,
    nodes_in_selection_box, BezierLinkRoute, LinkGeometry, LinkRoute, NodeGeometry, PinGeometry,
    PolylineLinkRoute, SimpleLinkGeometry, SimpleNodeGeometry,
};
pub use path::{generate_bezier_path, generate_partial_bezier_path};
pub use state::{GeometryCache, StoredPin};
// `selection` is deliberately NOT re-exported at the crate root: it is the
// host's half of selection, a family of its own, and a bare `resolve_click`
// would say nothing about what it resolves.
pub use controller::NodeEditorController;
pub use graph::{
    validate_and_normalize_link,
    BasicLinkValidator,
    CompositeValidator,
    GraphLogic,
    LinkModel,
    // Link validation framework
    LinkValidator,
    MovableNode,
    NoDuplicatesValidator,
    NormalizedLink,
    SimpleLink,
    ValidationError,
    ValidationResult,
};
#[cfg(feature = "layout")]
pub use layout::{
    sugiyama_layout, sugiyama_layout_from_cache, Direction, NodePosition, SugiyamaConfig,
};
pub use links::LinkManager;
pub use setup::NodeEditorSetup;
pub use tracking::GeometryTracker;

/// Wire up all NodeEditor callbacks with a single macro call.
///
/// This macro sets up default behavior for geometry tracking, computations, grid updates,
/// and keyboard focus on editor presses.
/// You can override any callback after calling this macro - the last `.on_*()` call wins.
///
/// The window must expose `grid-commands`, `width_`, `height_`, and
/// `public function focus-editor() { editor.focus(); }`.
///
/// # Generated-UI integration
///
/// This fragment assumes the generated globals and window members from the
/// [compiled quick start](https://github.com/tilladam/slint-node-editor/tree/main/smoke/downstream).
///
/// ```text
/// use slint_node_editor::{NodeEditorSetup, wire_node_editor};
///
/// let setup = NodeEditorSetup::new(|node_id, dx, dy| {
///     // Update your model
/// });
///
/// wire_node_editor!(window, setup);
///
/// // Override specific callbacks if needed:
/// // window.global::<NodeEditorComputations>().on_compute_pin_at(|x, y, radius| { ... });
/// ```
#[macro_export]
macro_rules! wire_node_editor {
    ($window:expr, $setup:expr) => {{
        // Geometry tracking
        let gc = $window.global::<NodeEditorInternalCallbacks>();
        gc.on_report_node_rect($setup.report_node_rect());
        gc.on_report_pin_position($setup.report_pin_position());
        gc.on_remove_node_from_cache($setup.remove_node());
        gc.on_remove_pin_from_cache($setup.remove_pin());
        gc.on_reset_graph_cache($setup.reset_graph());
        gc.on_start_node_drag($setup.start_node_drag());
        gc.on_cancel_node_drag($setup.cancel_node_drag());
        gc.on_end_node_drag($setup.end_node_drag());

        // Focus synchronously, before the press's consequences can focus another control.
        let w = $window.as_weak();
        gc.on_take_editor_focus(move || {
            if let Some(w) = w.upgrade() {
                w.invoke_focus_editor();
            }
        });

        // Computations
        let computations = $window.global::<NodeEditorComputations>();
        computations.on_compute_link_path($setup.controller().compute_link_path_callback(
            |commands, x, y, width, height| LinkPath {
                commands: commands.into(),
                x,
                y,
                width,
                height,
            },
        ));

        let ctrl = $setup.controller().clone();
        computations
            .on_compute_pin_at(move |x, y, radius| ctrl.cache().borrow().find_pin_at(x, y, radius));

        computations.on_compute_link_preview_path(
            |start_x, start_y, end_x, end_y, zoom, bezier_offset| {
                $crate::generate_bezier_path(start_x, start_y, end_x, end_y, zoom, bezier_offset)
                    .into()
            },
        );

        // Keep the Rust controller aligned with the component's public settings.
        $setup
            .controller()
            .set_grid_spacing(computations.get_grid_spacing());
        $setup
            .controller()
            .set_bezier_offset(computations.get_bezier_min_offset());

        let ctrl = $setup.controller().clone();
        computations.on_configuration_changed(move |grid_spacing, bezier_offset| {
            ctrl.set_grid_spacing(grid_spacing);
            ctrl.set_bezier_offset(bezier_offset);
        });

        // Viewport state and grid generation are separate public contracts:
        // viewport changes update coordinates, while request-grid-update also
        // covers resize and spacing changes.
        let ctrl = $setup.controller().clone();
        computations.on_viewport_changed(move |zoom, pan_x, pan_y| {
            ctrl.set_viewport(zoom, pan_x, pan_y);
        });

        let ctrl = $setup.controller().clone();
        let w = $window.as_weak();
        computations.on_request_grid_update(move || {
            if let Some(w) = w.upgrade() {
                w.set_grid_commands(ctrl.generate_current_grid(w.get_width_(), w.get_height_()));
            }
        });

        // Initial grid
        let ctrl = $setup.controller().clone();
        let w = $window.as_weak();
        if let Some(w) = w.upgrade() {
            w.set_grid_commands(ctrl.generate_current_grid(w.get_width_(), w.get_height_()));
        }
    }};
}

/// Wire the editor's selection intents, using your model rows as the store.
///
/// The editor holds no selection state: it reports gestures (`node-selected`,
/// `select-link`, `selection-cleared`, `box-selection-committed`) and renders
/// whatever `selected` flag it finds on the rows. This macro closes that loop
/// without introducing a second copy of the selection — each gesture reads the
/// current set back out of the rows, resolves it through
/// [`resolve_click`] / [`resolve_box`], and projects the result in. There is
/// nothing to keep in sync, because there is only ever one record of what is
/// selected.
///
/// Rows need an `id` and a `selected` field.
///
/// Two arms: node selection alone, or nodes and links together. 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.
///
/// [`resolve_click`]: crate::selection::resolve_click
/// [`resolve_box`]: crate::selection::resolve_box
/// [`selection`]: crate::selection
///
/// # Generated-UI integration
///
/// This fragment assumes the generated callbacks and models from the
/// [compiled quick start](https://github.com/tilladam/slint-node-editor/tree/main/smoke/downstream).
///
/// ```text
/// wire_node_editor!(window, setup);
/// wire_selection!(window, setup, nodes);
/// // …or, with selectable links:
/// wire_selection!(window, setup, nodes, links);
/// ```
#[macro_export]
macro_rules! wire_selection {
    ($window:expr, $setup:expr, $nodes:expr) => {{
        // `select-link` is deliberately not wired: the editor only emits it
        // when the host opts into `has-link-selection`, and a host doing that
        // wants the four-argument arm.

        $window.on_node_selected({
            let nodes = $nodes.clone();
            move |node_id, shift| {
                $crate::selection::apply_click(
                    &nodes,
                    |n| n.id,
                    |n| &mut n.selected,
                    node_id,
                    shift,
                )
            }
        });

        $window.on_selection_cleared({
            let nodes = $nodes.clone();
            move || $crate::selection::clear_selection(&nodes, |n| &mut n.selected)
        });

        $window.on_box_selection_committed({
            let nodes = $nodes.clone();
            let ctrl = $setup.controller().clone();
            move |x, y, w, h, shift| {
                let hits = ctrl.cache().borrow().nodes_in_selection_box(x, y, w, h);
                $crate::selection::apply_box(&nodes, |n| n.id, |n| &mut n.selected, hits, shift)
            }
        });
    }};

    ($window:expr, $setup:expr, $nodes:expr, $links:expr) => {{
        // A plain click is exclusive across kinds — picking a node drops the
        // links and vice versa. Shift means "add to what I have", so it leaves
        // the other kind standing: the same mixed selection a shift-marquee
        // builds, which is also what a delete then acts on.
        $window.on_node_selected({
            let nodes = $nodes.clone();
            let links = $links.clone();
            move |node_id, shift| {
                if !shift {
                    $crate::selection::clear_selection(&links, |l| &mut l.selected);
                }
                $crate::selection::apply_click(
                    &nodes,
                    |n| n.id,
                    |n| &mut n.selected,
                    node_id,
                    shift,
                )
            }
        });

        $window.on_select_link({
            let nodes = $nodes.clone();
            let links = $links.clone();
            move |link_id, shift| {
                if !shift {
                    $crate::selection::clear_selection(&nodes, |n| &mut n.selected);
                }
                $crate::selection::apply_click(
                    &links,
                    |l| l.id,
                    |l| &mut l.selected,
                    link_id,
                    shift,
                )
            }
        });

        $window.on_selection_cleared({
            let nodes = $nodes.clone();
            let links = $links.clone();
            move || {
                $crate::selection::clear_selection(&nodes, |n| &mut n.selected);
                $crate::selection::clear_selection(&links, |l| &mut l.selected);
            }
        });

        $window.on_box_selection_committed({
            let nodes = $nodes.clone();
            let links = $links.clone();
            let ctrl = $setup.controller().clone();
            move |x, y, w, h, shift| {
                let (node_hits, link_hits) = {
                    let cache = ctrl.cache();
                    let cache = cache.borrow();
                    let rows = (0..slint::Model::row_count(&*links))
                        .filter_map(|i| slint::Model::row_data(&*links, i))
                        .map(|l| (l.id, l.start_pin_id, l.end_pin_id));
                    (
                        cache.nodes_in_selection_box(x, y, w, h),
                        cache.links_in_selection_box(x, y, w, h, rows),
                    )
                };
                $crate::selection::apply_box(
                    &nodes,
                    |n| n.id,
                    |n| &mut n.selected,
                    node_hits,
                    shift,
                );
                $crate::selection::apply_box(
                    &links,
                    |l| l.id,
                    |l| &mut l.selected,
                    link_hits,
                    shift,
                )
            }
        });
    }};
}