iced_nodegraph 0.4.0

High-performance node graph editor widget for Iced with SDF-based rendering
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! Pin widget for node graph connection points.
//!
//! This module provides the [`NodePin`] widget that wraps content and acts as
//! a connection point for edges. Pins are placed within nodes and can be
//! connected to other pins via dragging.
//!
//! ## Usage
//!
//! Pins are typically created using the [`pin!`] macro for convenience:
//!
//! ```ignore
//! use iced_nodegraph::pin;
//!
//! // Simple pin with just a label
//! pin!(Left, 0, text("Input"), Input)
//!
//! // Pin with a user-defined payload
//! pin!(Right, 1, text("Output"), Output, MyKind::Audio)
//! ```
//!
//! ## Pin Properties
//!
//! - [`PinSide`] - Which edge of the node the pin attaches to (Left, Right, Top, Bottom)
//! - [`PinDirection`] - Whether the pin is an input or output
//! - User info - Optional user-defined payload via [`NodePin::info`]
//!
//! ## Connection Behavior
//!
//! When users drag from a pin, the widget tracks valid drop targets based on:
//! - Pin direction (inputs connect to outputs)
//! - The graph's [`NodeGraph::can_connect`](crate::NodeGraph::can_connect) closure
//! - Visual feedback via pulsing animation on valid targets

use crate::ids::PinId;
use iced::{Element, Event, Length, Point, Rectangle, Size};
use iced_wgpu::core::{
    Clipboard, Layout, Shell, Widget, layout, mouse, renderer,
    widget::{Tree, tree},
};
/// Default pin size when no content widget is provided.
const DEFAULT_PIN_SIZE: Size = Size::new(50.0, 20.0);

/// Which side of a node this pin attaches to.
/// Determines the tangent direction for edge bezier curves.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u32)]
pub enum PinSide {
    /// Pin on the left edge, edges exit to the left.
    #[default]
    Left = 0,
    /// Pin on the right edge, edges exit to the right.
    Right = 1,
    /// Pin on the top edge, edges exit upward.
    Top = 2,
    /// Pin on the bottom edge, edges exit downward.
    Bottom = 3,
    /// Pin placed in a row layout. Edges exit to the right (same as `Right`).
    Row = 4,
}

impl From<PinSide> for u32 {
    fn from(side: PinSide) -> u32 {
        side as u32
    }
}

/// Direction of data flow for a pin.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PinDirection {
    Input,
    Output,
    #[default]
    Both,
}

/// Read-only view of a pin's semantic info, passed to a node's `pin_style`
/// closure so it can style each pin by direction, user info, or id. The pin
/// itself carries no style; the owning node decides how its pins look.
///
/// `UI` is the user-defined per-pin payload set via [`NodePin::info`]; it
/// defaults to `()` for pins that carry none.
pub struct PinInfo<'a, P, UI = ()> {
    direction: PinDirection,
    pin_id: &'a P,
    info: &'a UI,
}

impl<'a, P, UI> PinInfo<'a, P, UI> {
    pub(crate) fn new(direction: PinDirection, pin_id: &'a P, info: &'a UI) -> Self {
        Self {
            direction,
            pin_id,
            info,
        }
    }

    /// The pin's direction (input / output / both).
    pub fn direction(&self) -> PinDirection {
        self.direction
    }

    /// The pin's user id.
    pub fn pin_id(&self) -> &P {
        self.pin_id
    }

    /// The pin's user-defined payload set via [`NodePin::info`].
    pub fn info(&self) -> &UI {
        self.info
    }
}

/// Read-only view of one endpoint of a candidate connection, passed to
/// [`NodeGraph::can_connect`](crate::NodeGraph::can_connect). Bundles the pin's
/// node id, pin id, direction and user payload.
///
/// `UI` is the user-defined per-pin payload; it defaults to `()`.
pub struct PinEnd<'a, N, P, UI = ()> {
    node_id: &'a N,
    pin_id: &'a P,
    direction: PinDirection,
    info: &'a UI,
    is_occupied: bool,
}

// Hand-written so `PinEnd` stays `Copy` for any `N`/`P`/`UI` (it only holds shared
// references); a derive would add spurious `N: Copy`/`P: Copy`/`UI: Copy` bounds and
// stop `can_connect` helpers from passing it to several predicates by value.
impl<N, P, UI> Clone for PinEnd<'_, N, P, UI> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<N, P, UI> Copy for PinEnd<'_, N, P, UI> {}

impl<'a, N, P, UI> PinEnd<'a, N, P, UI> {
    pub(crate) fn new(
        node_id: &'a N,
        pin_id: &'a P,
        direction: PinDirection,
        info: &'a UI,
        is_occupied: bool,
    ) -> Self {
        Self {
            node_id,
            pin_id,
            direction,
            info,
            is_occupied,
        }
    }

    /// The id of the node this pin belongs to.
    pub fn node_id(&self) -> &N {
        self.node_id
    }

    /// The pin's user id.
    pub fn pin_id(&self) -> &P {
        self.pin_id
    }

    /// The pin's direction (input / output / both).
    pub fn direction(&self) -> PinDirection {
        self.direction
    }

    /// The pin's user-defined payload set via [`NodePin::info`].
    pub fn info(&self) -> &UI {
        self.info
    }

    /// Whether this pin already holds at least one edge.
    ///
    /// The edge currently being dragged is excluded, so a connection re-routed
    /// back onto its own input reports that input as free. See
    /// [`input_not_occupied`](crate::connection::input_not_occupied).
    pub fn is_occupied(&self) -> bool {
        self.is_occupied
    }
}

/// A transparent wrapper used as a marker within `NodeGraph`.
///
/// Generic over `P` (the pin identifier type, e.g. `String`, enum, UUID) and
/// `UI` (the user-defined per-pin payload surfaced to `pin_style`/`can_connect`,
/// defaults to `()`).
pub struct NodePin<'a, P, UI, Message, Theme, Renderer>
where
    P: PinId,
    Renderer: renderer::Renderer,
{
    /// Which side of the node the pin sits on.
    pub side: PinSide,
    /// Whether the pin is an input, an output, or both.
    pub direction: PinDirection,
    /// The pin's user id, unique within its node.
    pub pin_id: P,
    /// User-defined per-pin payload, surfaced to `pin_style` / `can_connect`.
    pub user_info: UI,
    /// The widget drawn as the pin's label/content.
    pub content: Element<'a, Message, Theme, Renderer>,
    interactions_disabled: bool,
}

impl<'a, P, Message, Theme, Renderer> NodePin<'a, P, (), Message, Theme, Renderer>
where
    P: PinId,
    Renderer: renderer::Renderer,
{
    pub fn new(
        side: PinSide,
        pin_id: P,
        content: impl Into<Element<'a, Message, Theme, Renderer>>,
    ) -> Self {
        Self {
            side,
            direction: PinDirection::Both,
            pin_id,
            user_info: (),
            content: content.into(),
            interactions_disabled: false,
        }
    }
}

impl<'a, P, UI, Message, Theme, Renderer> NodePin<'a, P, UI, Message, Theme, Renderer>
where
    P: PinId,
    Renderer: renderer::Renderer,
{
    pub fn direction(mut self, direction: PinDirection) -> Self {
        self.direction = direction;
        self
    }

    /// Attaches a user-defined payload to this pin, surfaced to the node's
    /// `pin_style` closure and the graph's `can_connect` closure as `UI`.
    ///
    /// Changing the payload type also changes the pin's `UI` type parameter.
    ///
    /// # Example
    /// ```rust,ignore
    /// pin!(Left, "value", text("x"), Input).info(MyKind::Scalar)
    /// ```
    pub fn info<UI2>(self, info: UI2) -> NodePin<'a, P, UI2, Message, Theme, Renderer> {
        NodePin {
            side: self.side,
            direction: self.direction,
            pin_id: self.pin_id,
            user_info: info,
            content: self.content,
            interactions_disabled: self.interactions_disabled,
        }
    }

    /// Disables all interactions (drag, drop) for this pin.
    ///
    /// The pin remains visible and edges stay connected, but the user
    /// cannot start new connections or unplug existing ones.
    /// Useful for collapsed sections where pins should be visible but inactive.
    pub fn disable_interactions(mut self) -> Self {
        self.interactions_disabled = true;
        self
    }
}

/// Internal state for a NodePin widget.
///
/// Generic over `P` (the pin id) and `UI` (the user payload). Within one graph
/// all pins share the same `P` and `UI`, so `find_pins` matches a single
/// `tree::Tag`. The pin id is stored directly: matching an edge endpoint is exact
/// equality, and recovering the user's id is just a borrow (no type erasure).
#[derive(Debug, Clone)]
pub(super) struct NodePinState<P, UI> {
    /// The user's pin id.
    pub pin_id: P,
    pub side: PinSide,
    pub direction: PinDirection,
    pub position: Point,
    /// When true, pin cannot be dragged from or dropped onto
    pub interactions_disabled: bool,
    /// User-defined per-pin payload, surfaced to pin_style / can_connect.
    pub user_info: UI,
}

impl<'a, P, UI, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
    for NodePin<'a, P, UI, Message, Theme, Renderer>
where
    P: PinId + 'static,
    UI: Clone + 'static,
    Renderer: renderer::Renderer + 'a,
    Theme: 'a,
    Message: 'a,
{
    fn tag(&self) -> tree::Tag {
        // Same tag for all pins sharing P and UI - enables consistent pin finding
        tree::Tag::of::<NodePinState<P, UI>>()
    }

    fn state(&self) -> tree::State {
        tree::State::new(NodePinState {
            pin_id: self.pin_id.clone(),
            side: self.side,
            direction: self.direction,
            position: Point::new(0.0, 0.0),
            interactions_disabled: self.interactions_disabled,
            user_info: self.user_info.clone(),
        })
    }

    fn size(&self) -> Size<Length> {
        self.content.as_widget().size()
    }

    fn children(&self) -> Vec<Tree> {
        vec![Tree::new(&self.content)]
    }

    fn layout(
        &mut self,
        tree: &mut Tree,
        renderer: &Renderer,
        limits: &layout::Limits,
    ) -> layout::Node {
        if let Some(content_tree) = tree.children.first_mut() {
            let content_layout =
                self.content
                    .as_widget_mut()
                    .layout(content_tree, renderer, limits);
            let size = content_layout.size();
            layout::Node::with_children(size, vec![content_layout])
        } else {
            layout::Node::new(DEFAULT_PIN_SIZE)
        }
    }

    fn update(
        &mut self,
        tree: &mut Tree,
        event: &Event,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        renderer: &Renderer,
        clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
        viewport: &Rectangle,
    ) {
        {
            let state = tree.state.downcast_mut::<NodePinState<P, UI>>();
            state.pin_id = self.pin_id.clone();
            state.side = self.side;
            state.direction = self.direction;
            state.position = layout.bounds().center();
            state.interactions_disabled = self.interactions_disabled;
            state.user_info = self.user_info.clone();
        }
        if let Some((child_layout, child_tree)) = layout.children().zip(&mut tree.children).next() {
            self.content.as_widget_mut().update(
                child_tree,
                event,
                child_layout,
                cursor,
                renderer,
                clipboard,
                shell,
                viewport,
            );
        }
    }

    fn draw(
        &self,
        tree: &Tree,
        renderer: &mut Renderer,
        theme: &Theme,
        style: &renderer::Style,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        viewport: &Rectangle,
    ) {
        if let Some((child_layout, child_tree)) = layout.children().zip(&tree.children).next() {
            self.content.as_widget().draw(
                child_tree,
                renderer,
                theme,
                style,
                child_layout,
                cursor,
                viewport,
            );
        }
    }

    fn mouse_interaction(
        &self,
        tree: &Tree,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        viewport: &Rectangle,
        renderer: &Renderer,
    ) -> mouse::Interaction {
        if let Some((content_tree, content_layout)) =
            tree.children.first().zip(layout.children().next())
        {
            self.content.as_widget().mouse_interaction(
                content_tree,
                content_layout,
                cursor,
                viewport,
                renderer,
            )
        } else {
            mouse::Interaction::default()
        }
    }

    fn size_hint(&self) -> Size<Length> {
        self.content.as_widget().size_hint()
    }

    fn diff(&self, tree: &mut Tree) {
        if let Some(content_tree) = tree.children.first_mut() {
            self.content.as_widget().diff(content_tree);
        } else {
            tree.children.push(Tree::new(&self.content));
        }
    }
}

impl<'a, P, UI, Message, Theme, Renderer> From<NodePin<'a, P, UI, Message, Theme, Renderer>>
    for Element<'a, Message, Theme, Renderer>
where
    P: PinId + 'static,
    UI: Clone + 'static,
    Renderer: renderer::Renderer + 'a,
    Message: 'a,
    Theme: 'a,
{
    fn from(widget: NodePin<'a, P, UI, Message, Theme, Renderer>) -> Self {
        Element::new(widget)
    }
}

pub fn node_pin<'a, P, Message, Theme, Renderer>(
    side: PinSide,
    pin_id: P,
    content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> NodePin<'a, P, (), Message, Theme, Renderer>
where
    P: PinId,
    Renderer: iced_wgpu::core::renderer::Renderer,
{
    NodePin::new(side, pin_id, content)
}

/// Macro for creating pins with concise syntax.
///
/// The pin widget is an invisible wrapper that marks where a connection point
/// should be placed. The content element (typically a text label) is passed through.
///
/// # Examples
///
/// Pins carry no style of their own; the owning node colors and shapes them via
/// [`Node::pin_style`](crate::Node::pin_style), keyed on the pin's direction,
/// user info or id.
///
/// ```rust,ignore
/// use iced_nodegraph::pin;
/// use iced::widget::text;
///
/// // Full syntax: side, pin_id, content, direction, user info
/// pin!(Right, "output", text("output"), Output, MyKind::Email)
///
/// // With direction only (connects to anything)
/// pin!(Right, "data", text("data"), Output)
///
/// // Minimal (side, pin_id, content only, defaults: Both direction, no info)
/// pin!(Right, "data", text("data"))
/// ```
#[macro_export]
macro_rules! pin {
    // With user info: side, pin_id, content, direction, info
    ($side:ident, $pin_id:expr, $content:expr, $dir:ident, $info:expr) => {
        $crate::node_pin($crate::PinSide::$side, $pin_id, $content)
            .direction($crate::PinDirection::$dir)
            .info($info)
    };

    // Direction only: side, pin_id, content, direction
    ($side:ident, $pin_id:expr, $content:expr, $dir:ident) => {
        $crate::node_pin($crate::PinSide::$side, $pin_id, $content)
            .direction($crate::PinDirection::$dir)
    };

    // Minimal: side, pin_id, content only
    ($side:ident, $pin_id:expr, $content:expr) => {
        $crate::node_pin($crate::PinSide::$side, $pin_id, $content)
    };
}