hikari-extra-components 0.3.12

Advanced UI components (node graph, rich text editor, timeline) for the Hikari design system
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
// node_graph/canvas.rs
// Main canvas state for node graph rendering - Framework Agnostic

use std::collections::HashMap;

use crate::node_graph::{ connection::{Connection, ConnectionId}, history::{HistoryAction, HistoryState}, node::{Node, NodeId, NodeState, NodeType, PortPosition}, serialization::SerializedNodeGraph, };

/// Node graph state
///
/// Previously a component with complex rendering logic.
/// Now a pure state model that can be used with any framework.
#[derive(Clone, Debug, PartialEq)]
pub struct NodeGraphState {
    pub nodes: HashMap<String, NodeState>,
    pub connections: Vec<Connection>,
    pub selected_node: Option<String>,
    pub selected_connection: Option<ConnectionId>,
    pub zoom: f64,
    pub pan: (f64, f64),
}

impl Default for NodeGraphState {
    fn default() -> Self {
        Self::new()
    }
}

impl NodeGraphState {
    pub fn new() -> Self {
        Self {
            nodes: HashMap::new(),
            connections: Vec::new(),
            selected_node: None,
            selected_connection: None,
            zoom: 1.0,
            pan: (0.0, 0.0),
        }
    }

    /// Add a node to the graph
    pub fn add_node(&mut self, state: NodeState) {
        self.nodes.insert(state.id.clone(), state);
    }

    /// Remove a node from the graph
    pub fn remove_node(&mut self, id: &str) -> Option<NodeState> {
        self.nodes.remove(id)
    }

    /// Get a node by ID
    pub fn get_node(&self, id: &str) -> Option<&NodeState> {
        self.nodes.get(id)
    }

    /// Get a mutable node by ID
    pub fn get_node_mut(&mut self, id: &str) -> Option<&mut NodeState> {
        self.nodes.get_mut(id)
    }

    /// Update node position
    pub fn update_node_position(&mut self, id: &str, x: f64, y: f64) -> bool {
        if let Some(node) = self.nodes.get_mut(id) {
            node.position = (x, y);
            true
        } else {
            false
        }
    }

    /// Add a connection
    pub fn add_connection(&mut self, connection: Connection) {
        self.connections.push(connection);
    }

    /// Remove a connection by ID
    pub fn remove_connection(&mut self, id: &ConnectionId) -> Option<Connection> {
        let pos = self.connections.iter().position(|c| &c.id == id)?;
        Some(self.connections.remove(pos))
    }

    /// Select a node
    pub fn select_node(&mut self, id: Option<String>) {
        // Deselect current
        if let Some(current_id) = &self.selected_node {
            if let Some(node) = self.nodes.get_mut(current_id) {
                node.selected = false;
            }
        }

        self.selected_node = id.clone();

        // Select new
        if let Some(new_id) = id {
            if let Some(node) = self.nodes.get_mut(&new_id) {
                node.selected = true;
            }
        }
    }

    /// Select a connection
    pub fn select_connection(&mut self, id: Option<ConnectionId>) {
        self.selected_connection = id;
    }

    /// Set zoom level (clamped)
    pub fn set_zoom(&mut self, zoom: f64, min: f64, max: f64) {
        self.zoom = zoom.clamp(min, max);
    }

    /// Zoom in by a factor
    pub fn zoom_in(&mut self, factor: f64, min: f64, max: f64) {
        self.set_zoom(self.zoom * factor, min, max);
    }

    /// Zoom out by a factor
    pub fn zoom_out(&mut self, factor: f64, min: f64, max: f64) {
        self.set_zoom(self.zoom / factor, min, max);
    }

    /// Reset zoom and pan
    pub fn reset_view(&mut self) {
        self.zoom = 1.0;
        self.pan = (0.0, 0.0);
    }

    /// Pan the view
    pub fn pan(&mut self, dx: f64, dy: f64) {
        self.pan.0 += dx;
        self.pan.1 += dy;
    }

    /// Calculate port position based on node position and port placement
    pub fn calculate_port_position(
        &self,
        node_id: &str,
        _port_id: &str,
        port_position: PortPosition,
    ) -> Option<(f64, f64)> {
        let node_state = self.nodes.get(node_id)?;
        let (node_x, node_y) = node_state.position;
        let (node_width, node_height) = node_state.size;

        let (port_x, port_y) = match port_position {
            PortPosition::Top => (node_x + node_width / 2.0, node_y),
            PortPosition::Bottom => (node_x + node_width / 2.0, node_y + node_height),
            PortPosition::Left => (node_x, node_y + node_height / 2.0),
            PortPosition::Right => (node_x + node_width, node_y + node_height / 2.0),
        };

        Some((port_x, port_y))
    }

    /// Get the transform CSS string for the canvas
    pub fn transform_style(&self) -> String {
        format!(
            "transform: scale({}) translate({}px, {}px);",
            self.zoom, self.pan.0, self.pan.1
        )
    }

    /// Clear all nodes and connections
    pub fn clear(&mut self) {
        self.nodes.clear();
        self.connections.clear();
        self.selected_node = None;
        self.selected_connection = None;
    }
}

/// Node graph canvas configuration
///
/// Configuration for the canvas, separate from state.
#[derive(Clone, Debug, PartialEq)]
pub struct NodeGraphCanvasConfig {
    /// Canvas width in pixels
    pub width: f64,

    /// Canvas height in pixels
    pub height: f64,

    /// Minimum zoom level
    pub min_zoom: f64,

    /// Maximum zoom level
    pub max_zoom: f64,

    /// Whether to show minimap
    pub show_minimap: bool,

    /// Whether to show controls
    pub show_controls: bool,

    /// Grid size in pixels
    pub grid_size: f64,
}

impl Default for NodeGraphCanvasConfig {
    fn default() -> Self {
        Self {
            width: 1200.0,
            height: 800.0,
            min_zoom: 0.1,
            max_zoom: 3.0,
            show_minimap: true,
            show_controls: true,
            grid_size: 20.0,
        }
    }
}

impl NodeGraphCanvasConfig {
    pub fn with_size(mut self, width: f64, height: f64) -> Self {
        self.width = width;
        self.height = height;
        self
    }

    pub fn with_zoom_bounds(mut self, min: f64, max: f64) -> Self {
        self.min_zoom = min;
        self.max_zoom = max;
        self
    }

    pub fn with_minimap(mut self, show: bool) -> Self {
        self.show_minimap = show;
        self
    }

    pub fn with_controls(mut self, show: bool) -> Self {
        self.show_controls = show;
        self
    }

    /// Get the container style string
    pub fn container_style(&self) -> String {
        format!("width: {}px; height: {}px;", self.width, self.height)
    }
}

/// Events that can be emitted by the node graph canvas
#[derive(Clone, PartialEq, Debug)]
pub enum NodeGraphEvent {
    /// A node was added
    NodeAdded { id: String, node_type: NodeType, position: (f64, f64) },

    /// A node was selected
    NodeSelected(String),

    /// A node was moved
    NodeMoved { id: String, to: (f64, f64) },

    /// A node was deleted
    NodeDeleted(String),

    /// A connection was created
    ConnectionCreated { id: ConnectionId, from_node: String, from_port: String, to_node: String, to_port: String },

    /// A connection was deleted
    ConnectionDeleted(ConnectionId),

    /// Zoom changed
    ZoomChanged(f64),

    /// View was panned
    Panned { dx: f64, dy: f64 },

    /// Undo requested
    Undo,

    /// Redo requested
    Redo,

    /// Save requested
    Save,

    /// Load requested
    Load,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_node_graph_state_new() {
        let state = NodeGraphState::new();
        assert!(state.nodes.is_empty());
        assert!(state.connections.is_empty());
        assert_eq!(state.zoom, 1.0);
        assert_eq!(state.pan, (0.0, 0.0));
    }

    #[test]
    fn test_add_remove_node() {
        let mut state = NodeGraphState::new();
        let node = NodeState::new("node1".to_string());

        state.add_node(node.clone());
        assert_eq!(state.nodes.len(), 1);
        assert!(state.get_node("node1").is_some());

        let removed = state.remove_node("node1");
        assert!(removed.is_some());
        assert!(state.nodes.is_empty());
    }

    #[test]
    fn test_update_node_position() {
        let mut state = NodeGraphState::new();
        state.add_node(NodeState::new("node1".to_string()));

        assert!(state.update_node_position("node1", 100.0, 200.0));
        assert_eq!(state.get_node("node1").unwrap().position, (100.0, 200.0));
    }

    #[test]
    fn test_select_node() {
        let mut state = NodeGraphState::new();
        state.add_node(NodeState::new("node1".to_string()));
        state.add_node(NodeState::new("node2".to_string()));

        state.select_node(Some("node1".to_string()));
        assert_eq!(state.selected_node, Some("node1".to_string()));
        assert!(state.get_node("node1").unwrap().selected);

        state.select_node(Some("node2".to_string()));
        assert_eq!(state.selected_node, Some("node2".to_string()));
        assert!(!state.get_node("node1").unwrap().selected);
        assert!(state.get_node("node2").unwrap().selected);
    }

    #[test]
    fn test_zoom() {
        let mut state = NodeGraphState::new();

        state.set_zoom(2.0, 0.1, 3.0);
        assert_eq!(state.zoom, 2.0);

        state.set_zoom(5.0, 0.1, 3.0);
        assert_eq!(state.zoom, 3.0); // Clamped to max

        state.zoom_in(1.5, 0.1, 3.0);
        assert_eq!(state.zoom, 3.0); // 3.0 * 1.5 = 4.5, clamped to 3.0

        state.zoom_out(2.0, 0.1, 3.0);
        assert_eq!(state.zoom, 1.5); // 3.0 / 2.0 = 1.5
    }

    #[test]
    fn test_pan() {
        let mut state = NodeGraphState::new();

        state.pan(10.0, 20.0);
        assert_eq!(state.pan, (10.0, 20.0));

        state.pan(-5.0, -10.0);
        assert_eq!(state.pan, (5.0, 10.0));
    }

    #[test]
    fn test_reset_view() {
        let mut state = NodeGraphState::new();
        state.zoom = 2.0;
        state.pan = (100.0, 200.0);

        state.reset_view();
        assert_eq!(state.zoom, 1.0);
        assert_eq!(state.pan, (0.0, 0.0));
    }

    #[test]
    fn test_calculate_port_position() {
        let mut state = NodeGraphState::new();
        let node = NodeState::new("node1".to_string())
            .with_position(100.0, 100.0)
            .with_size(200.0, 150.0);
        state.add_node(node);

        let pos = state.calculate_port_position("node1", "port1", PortPosition::Top);
        assert_eq!(pos, Some((200.0, 100.0)));

        let pos = state.calculate_port_position("node1", "port1", PortPosition::Right);
        assert_eq!(pos, Some((300.0, 175.0)));

        let pos = state.calculate_port_position("node1", "port1", PortPosition::Bottom);
        assert_eq!(pos, Some((200.0, 250.0)));

        let pos = state.calculate_port_position("node1", "port1", PortPosition::Left);
        assert_eq!(pos, Some((100.0, 175.0)));
    }

    #[test]
    fn test_transform_style() {
        let state = NodeGraphState {
            zoom: 1.5,
            pan: (10.0, 20.0),
            ..Default::default()
        };

        let style = state.transform_style();
        assert!(style.contains("scale(1.5)"));
        assert!(style.contains("translate(10px"));
        assert!(style.contains("20px"));
    }

    #[test]
    fn test_config_default() {
        let config = NodeGraphCanvasConfig::default();
        assert_eq!(config.width, 1200.0);
        assert_eq!(config.height, 800.0);
        assert_eq!(config.min_zoom, 0.1);
        assert_eq!(config.max_zoom, 3.0);
    }

    #[test]
    fn test_config_builder() {
        let config = NodeGraphCanvasConfig::default()
            .with_size(800.0, 600.0)
            .with_zoom_bounds(0.5, 2.0)
            .with_minimap(false)
            .with_controls(false);

        assert_eq!(config.width, 800.0);
        assert_eq!(config.height, 600.0);
        assert_eq!(config.min_zoom, 0.5);
        assert_eq!(config.max_zoom, 2.0);
        assert!(!config.show_minimap);
        assert!(!config.show_controls);
    }
}