Skip to main content

leptos_node_graph/
types.rs

1use std::collections::HashSet;
2use std::fmt::Debug;
3use std::hash::Hash;
4
5/// Consumer implements this to define port type compatibility.
6pub trait PortType: Clone + PartialEq + Debug + Send + Sync + 'static {
7    /// Returns true if a connection from `source` output to `target` input is valid.
8    fn compatible(source: &Self, target: &Self) -> bool;
9
10    /// Returns a string identifier for this port type, used for menu filtering.
11    /// Must round-trip with `from_type_id`.
12    fn type_id(&self) -> String;
13
14    /// Reconstruct a port type from its string identifier.
15    /// Must round-trip with `type_id`.
16    fn from_type_id(id: &str) -> Self;
17
18    /// Check compatibility using string type IDs.
19    /// Default uses `from_type_id` + `compatible`. Override if you need custom logic.
20    fn compatible_by_id(source_id: &str, target_id: &str) -> bool {
21        Self::compatible(
22            &Self::from_type_id(source_id),
23            &Self::from_type_id(target_id),
24        )
25    }
26}
27
28pub trait NodeId: Clone + Eq + Hash + Debug + Send + Sync + 'static {}
29pub trait PortId: Clone + Eq + Hash + Debug + Send + Sync + 'static {}
30pub trait ConnectionId: Clone + Eq + Hash + Debug + Send + Sync + 'static {}
31
32// Blanket implementations for common types
33impl NodeId for String {}
34impl PortId for String {}
35impl ConnectionId for String {}
36impl NodeId for u64 {}
37impl PortId for u64 {}
38impl ConnectionId for u64 {}
39impl NodeId for usize {}
40impl PortId for usize {}
41impl ConnectionId for usize {}
42
43#[derive(Clone, Copy, Debug, Default, PartialEq)]
44pub struct Position {
45    pub x: f64,
46    pub y: f64,
47}
48
49impl Position {
50    pub fn new(x: f64, y: f64) -> Self {
51        Self { x, y }
52    }
53}
54
55#[derive(Clone, Copy, Debug, Default, PartialEq)]
56pub struct Size {
57    pub width: f64,
58    pub height: f64,
59}
60
61impl Size {
62    pub fn new(width: f64, height: f64) -> Self {
63        Self { width, height }
64    }
65}
66
67#[derive(Clone, Copy, Debug, Default, PartialEq)]
68pub struct Rect {
69    pub position: Position,
70    pub size: Size,
71}
72
73impl Rect {
74    pub fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
75        Self {
76            position: Position::new(x, y),
77            size: Size::new(width, height),
78        }
79    }
80
81    pub fn contains(&self, point: Position) -> bool {
82        point.x >= self.position.x
83            && point.x <= self.position.x + self.size.width
84            && point.y >= self.position.y
85            && point.y <= self.position.y + self.size.height
86    }
87
88    pub fn intersects(&self, other: &Rect) -> bool {
89        self.position.x < other.position.x + other.size.width
90            && self.position.x + self.size.width > other.position.x
91            && self.position.y < other.position.y + other.size.height
92            && self.position.y + self.size.height > other.position.y
93    }
94}
95
96#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
97pub enum PortDirection {
98    Input,
99    Output,
100}
101
102#[derive(Clone, Debug)]
103pub enum GraphEvent<N, P, C>
104where
105    N: NodeId,
106    P: PortId,
107    C: ConnectionId,
108{
109    /// Final positions for every node moved by one drag gesture.
110    NodesMoved {
111        nodes: Vec<(N, Position)>,
112    },
113    NodeResized {
114        id: N,
115        size: Size,
116    },
117    ConnectionRequested {
118        source: P,
119        target: P,
120    },
121    ConnectionRemoved {
122        id: C,
123    },
124    SelectionChanged {
125        nodes: HashSet<N>,
126        connections: HashSet<C>,
127    },
128    NodesDeleted {
129        ids: Vec<N>,
130    },
131    NodesCopied {
132        ids: Vec<N>,
133    },
134    NodesPasted {
135        offset: Position,
136    },
137    Undo,
138    Redo,
139    GroupCreated {
140        node_ids: Vec<N>,
141    },
142    /// User selected a node type from the creation menu.
143    /// Consumer should create the node, and if `connect_from`/`connect_to` are set,
144    /// also create a connection between them.
145    CreateNode {
146        /// The menu item id (node type).
147        item_id: String,
148        /// Canvas position where the node should be created.
149        position: Position,
150        /// The port that initiated the draft connection (if menu was opened during a drag).
151        connect_from: Option<P>,
152        /// The port id on the new node to connect to (e.g. "a", "result").
153        /// Consumer prefixes this with the new node's id.
154        connect_to: Option<String>,
155        /// Direction of the draft origin, so consumer knows output→input order.
156        connect_direction: Option<PortDirection>,
157    },
158}
159
160#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
161pub enum LayoutMode {
162    #[default]
163    Classic,
164    Structured,
165}
166
167#[derive(Clone, Debug)]
168pub struct EditorConfig {
169    pub min_zoom: f64,
170    pub max_zoom: f64,
171    pub grid_size: Option<f64>,
172    pub layout_mode: LayoutMode,
173    /// Screen-pixel inset left around the graph when framing it (the `F` key).
174    pub fit_padding: f64,
175    /// Zoom ceiling when framing. Separate from `max_zoom` so that framing a
176    /// small graph fills the pane at a sane size instead of magnifying it —
177    /// framing may always zoom OUT as far as `min_zoom`.
178    pub fit_max_zoom: f64,
179    /// How close (in SCREEN pixels, so the pull feels the same at any zoom) the
180    /// cursor must come to a compatible port before a draft connection snaps to
181    /// it. `0.0` disables snapping.
182    pub snap_distance: f64,
183}
184
185impl Default for EditorConfig {
186    fn default() -> Self {
187        Self {
188            min_zoom: 0.1,
189            max_zoom: 5.0,
190            grid_size: None,
191            layout_mode: LayoutMode::Classic,
192            fit_padding: 48.0,
193            fit_max_zoom: 1.0,
194            snap_distance: 22.0,
195        }
196    }
197}
198
199#[derive(Clone, Copy, Debug)]
200pub struct ViewportTransform {
201    pub pan_x: f64,
202    pub pan_y: f64,
203    pub zoom: f64,
204}
205
206impl Default for ViewportTransform {
207    fn default() -> Self {
208        Self {
209            pan_x: 0.0,
210            pan_y: 0.0,
211            zoom: 1.0,
212        }
213    }
214}
215
216impl ViewportTransform {
217    pub fn screen_to_canvas(&self, screen: Position) -> Position {
218        Position {
219            x: (screen.x - self.pan_x) / self.zoom,
220            y: (screen.y - self.pan_y) / self.zoom,
221        }
222    }
223
224    pub fn canvas_to_screen(&self, canvas: Position) -> Position {
225        Position {
226            x: canvas.x * self.zoom + self.pan_x,
227            y: canvas.y * self.zoom + self.pan_y,
228        }
229    }
230}
231
232#[derive(Clone, Debug)]
233pub struct DraftConnection<P: PortId, T: PortType> {
234    pub source_port: P,
235    pub source_position: Position,
236    pub port_type: T,
237    pub current_end: Position,
238    /// The direction of the port where the drag started.
239    pub origin_direction: PortDirection,
240    /// Compatible port the draft is currently snapped to, if the cursor is
241    /// within `EditorConfig::snap_distance` of one. `current_end` sits exactly on
242    /// that port while this is set, and releasing completes the connection to it
243    /// — so the wire never appears attached to something it wouldn't connect to.
244    pub snap_target: Option<P>,
245}