1
//! Interactive node graph editor widget.
2
//!
3
//! Provides the [`NodeGraph`] widget for building visual node-based editors
4
//! (e.g. shader graphs, data-flow pipelines). Key types:
5
//!
6
//! - [`NodeGraph`] — top-level widget holding nodes, types, and callbacks
7
//! - [`Node`] — a single node with typed input/output connections and editable fields
8
//! - [`NodeTypeInfo`] / [`InputOutputInfo`] — metadata describing node types and their I/O ports
9
//! - [`NodeGraphCallbacks`] — user-provided callbacks for add, remove, drag, connect, etc.
10
//!
11
//! **Known limitation:** Connection curves between nodes are currently not rendered
12
//! (`draw_connection` returns a null image pending `RenderImageCallbackInfo` support).
13

            
14
use alloc::vec::Vec;
15
use core::fmt;
16

            
17
use azul_core::{
18
    callbacks::{CoreCallback, CoreCallbackData, Update},
19
    dom::{Dom, EventFilter, HoverEventFilter, IdOrClass, IdOrClass::Class, IdOrClassVec},
20
    geom::{LogicalPosition, LogicalRect, LogicalSize, PhysicalSizeU32},
21
    gl::Texture,
22
    menu::{Menu, MenuItem, StringMenuItem},
23
    refany::{OptionRefAny, RefAny},
24
    resources::{ImageRef, RawImageFormat},
25
    svg::{SvgPath, SvgPathElement, SvgStrokeStyle, TessellatedGPUSvgNode},
26
    window::CursorPosition::InWindow,
27
};
28
use azul_css::css::BoxOrStatic;
29
#[allow(clippy::wildcard_imports)]
30
// widget/render module pulls in the css property/value types it builds with
31
use azul_css::{
32
    dynamic_selector::{CssPropertyWithConditions, CssPropertyWithConditionsVec},
33
    props::{
34
        basic::*,
35
        layout::*,
36
        property::{CssProperty, *},
37
        style::*,
38
    },
39
    *,
40
};
41

            
42
use crate::{
43
    callbacks::{Callback, CallbackInfo},
44
    widgets::{
45
        check_box::{CheckBox, CheckBoxOnToggleCallbackType, CheckBoxState},
46
        color_input::{ColorInput, ColorInputOnValueChangeCallbackType, ColorInputState},
47
        file_input::{FileInput, FileInputOnPathChangeCallbackType, FileInputState},
48
        number_input::{NumberInput, NumberInputOnFocusLostCallbackType, NumberInputState},
49
        text_input::{TextInput, TextInputOnFocusLostCallbackType, TextInputState},
50
    },
51
};
52

            
53
/// Interactive node graph editor widget with typed input/output connections.
54
#[derive(Debug, Clone)]
55
#[repr(C)]
56
pub struct NodeGraph {
57
    pub node_types: NodeTypeIdInfoMapVec,
58
    pub input_output_types: InputOutputTypeIdInfoMapVec,
59
    pub nodes: NodeIdNodeMapVec,
60
    pub allow_multiple_root_nodes: bool,
61
    pub offset: LogicalPosition,
62
    pub style: NodeGraphStyle,
63
    pub callbacks: NodeGraphCallbacks,
64
    pub add_node_str: AzString,
65
    pub scale_factor: f32,
66
}
67

            
68
impl Default for NodeGraph {
69
143
    fn default() -> Self {
70
143
        Self {
71
143
            node_types: NodeTypeIdInfoMapVec::from_const_slice(&[]),
72
143
            input_output_types: InputOutputTypeIdInfoMapVec::from_const_slice(&[]),
73
143
            nodes: NodeIdNodeMapVec::from_const_slice(&[]),
74
143
            allow_multiple_root_nodes: false,
75
143
            offset: LogicalPosition::zero(),
76
143
            style: NodeGraphStyle::Default,
77
143
            callbacks: NodeGraphCallbacks::default(),
78
143
            add_node_str: AzString::from_const_str(""),
79
143
            scale_factor: 1.0,
80
143
        }
81
143
    }
82
}
83

            
84
impl NodeGraph {
85
    /// Generates a new `NodeId` that is unique in the graph
86
    #[must_use]
87
9
    pub fn generate_unique_node_id(&self) -> NodeGraphNodeId {
88
        NodeGraphNodeId {
89
9
            inner: self
90
9
                .nodes
91
9
                .iter()
92
9
                .map(|i| i.node_id.inner)
93
9
                .max()
94
9
                .unwrap_or(0)
95
9
                .saturating_add(1),
96
        }
97
9
    }
98
}
99

            
100
/// Maps a [`NodeTypeId`] to its [`NodeTypeInfo`] metadata.
101
#[derive(Debug, Clone)]
102
#[repr(C)]
103
pub struct NodeTypeIdInfoMap {
104
    pub node_type_id: NodeTypeId,
105
    pub node_type_info: NodeTypeInfo,
106
}
107

            
108
impl_option!(
109
    NodeTypeIdInfoMap,
110
    OptionNodeTypeIdInfoMap,
111
    copy = false,
112
    [Debug, Clone]
113
);
114
impl_vec!(
115
    NodeTypeIdInfoMap,
116
    NodeTypeIdInfoMapVec,
117
    NodeTypeIdInfoMapVecDestructor,
118
    NodeTypeIdInfoMapVecDestructorType,
119
    NodeTypeIdInfoMapVecSlice,
120
    OptionNodeTypeIdInfoMap
121
);
122
impl_vec_clone!(
123
    NodeTypeIdInfoMap,
124
    NodeTypeIdInfoMapVec,
125
    NodeTypeIdInfoMapVecDestructor
126
);
127
impl_vec_mut!(NodeTypeIdInfoMap, NodeTypeIdInfoMapVec);
128
impl_vec_debug!(NodeTypeIdInfoMap, NodeTypeIdInfoMapVec);
129

            
130
/// Maps an [`InputOutputTypeId`] to its [`InputOutputInfo`] metadata.
131
#[derive(Debug, Clone)]
132
#[repr(C)]
133
pub struct InputOutputTypeIdInfoMap {
134
    pub io_type_id: InputOutputTypeId,
135
    pub io_info: InputOutputInfo,
136
}
137

            
138
impl_option!(
139
    InputOutputTypeIdInfoMap,
140
    OptionInputOutputTypeIdInfoMap,
141
    copy = false,
142
    [Debug, Clone]
143
);
144
impl_vec!(
145
    InputOutputTypeIdInfoMap,
146
    InputOutputTypeIdInfoMapVec,
147
    InputOutputTypeIdInfoMapVecDestructor,
148
    InputOutputTypeIdInfoMapVecDestructorType,
149
    InputOutputTypeIdInfoMapVecSlice,
150
    OptionInputOutputTypeIdInfoMap
151
);
152
impl_vec_clone!(
153
    InputOutputTypeIdInfoMap,
154
    InputOutputTypeIdInfoMapVec,
155
    InputOutputTypeIdInfoMapVecDestructor
156
);
157
impl_vec_mut!(InputOutputTypeIdInfoMap, InputOutputTypeIdInfoMapVec);
158
impl_vec_debug!(InputOutputTypeIdInfoMap, InputOutputTypeIdInfoMapVec);
159

            
160
/// Maps a [`NodeGraphNodeId`] to its [`Node`] data.
161
#[derive(Debug, Clone)]
162
#[repr(C)]
163
pub struct NodeIdNodeMap {
164
    pub node_id: NodeGraphNodeId,
165
    pub node: Node,
166
}
167

            
168
impl_option!(
169
    NodeIdNodeMap,
170
    OptionNodeIdNodeMap,
171
    copy = false,
172
    [Debug, Clone]
173
);
174
impl_vec!(
175
    NodeIdNodeMap,
176
    NodeIdNodeMapVec,
177
    NodeIdNodeMapVecDestructor,
178
    NodeIdNodeMapVecDestructorType,
179
    NodeIdNodeMapVecSlice,
180
    OptionNodeIdNodeMap
181
);
182
impl_vec_clone!(NodeIdNodeMap, NodeIdNodeMapVec, NodeIdNodeMapVecDestructor);
183
impl_vec_mut!(NodeIdNodeMap, NodeIdNodeMapVec);
184
impl_vec_debug!(NodeIdNodeMap, NodeIdNodeMapVec);
185

            
186
#[derive(Debug, Copy, Clone)]
187
#[repr(C)]
188
pub enum NodeGraphStyle {
189
    Default,
190
    // to be extended
191
}
192

            
193
/// User-provided callbacks for node graph interaction events.
194
#[derive(Default, Debug, Clone)]
195
#[repr(C)]
196
pub struct NodeGraphCallbacks {
197
    pub on_node_added: OptionOnNodeAdded,
198
    pub on_node_removed: OptionOnNodeRemoved,
199
    pub on_node_dragged: OptionOnNodeDragged,
200
    pub on_node_graph_dragged: OptionOnNodeGraphDragged,
201
    pub on_node_connected: OptionOnNodeConnected,
202
    pub on_node_input_disconnected: OptionOnNodeInputDisconnected,
203
    pub on_node_output_disconnected: OptionOnNodeOutputDisconnected,
204
    pub on_node_field_edited: OptionOnNodeFieldEdited,
205
}
206

            
207
pub type OnNodeAddedCallbackType = extern "C" fn(
208
    refany: RefAny,
209
    info: CallbackInfo,
210
    new_node_type: NodeTypeId,
211
    new_node_id: NodeGraphNodeId,
212
    new_node_position: NodeGraphNodePosition,
213
) -> Update;
214
impl_widget_callback!(
215
    OnNodeAdded,
216
    OptionOnNodeAdded,
217
    OnNodeAddedCallback,
218
    OnNodeAddedCallbackType
219
);
220

            
221
pub type OnNodeRemovedCallbackType =
222
    extern "C" fn(refany: RefAny, info: CallbackInfo, node_id_to_remove: NodeGraphNodeId) -> Update;
223
impl_widget_callback!(
224
    OnNodeRemoved,
225
    OptionOnNodeRemoved,
226
    OnNodeRemovedCallback,
227
    OnNodeRemovedCallbackType
228
);
229

            
230
pub type OnNodeGraphDraggedCallbackType =
231
    extern "C" fn(refany: RefAny, info: CallbackInfo, drag_amount: GraphDragAmount) -> Update;
232
impl_widget_callback!(
233
    OnNodeGraphDragged,
234
    OptionOnNodeGraphDragged,
235
    OnNodeGraphDraggedCallback,
236
    OnNodeGraphDraggedCallbackType
237
);
238

            
239
pub type OnNodeDraggedCallbackType = extern "C" fn(
240
    refany: RefAny,
241
    info: CallbackInfo,
242
    node_dragged: NodeGraphNodeId,
243
    drag_amount: NodeDragAmount,
244
) -> Update;
245
impl_widget_callback!(
246
    OnNodeDragged,
247
    OptionOnNodeDragged,
248
    OnNodeDraggedCallback,
249
    OnNodeDraggedCallbackType
250
);
251

            
252
pub type OnNodeConnectedCallbackType = extern "C" fn(
253
    refany: RefAny,
254
    info: CallbackInfo,
255
    input: NodeGraphNodeId,
256
    input_index: usize,
257
    output: NodeGraphNodeId,
258
    output_index: usize,
259
) -> Update;
260
impl_widget_callback!(
261
    OnNodeConnected,
262
    OptionOnNodeConnected,
263
    OnNodeConnectedCallback,
264
    OnNodeConnectedCallbackType
265
);
266

            
267
pub type OnNodeInputDisconnectedCallbackType = extern "C" fn(
268
    refany: RefAny,
269
    info: CallbackInfo,
270
    input: NodeGraphNodeId,
271
    input_index: usize,
272
) -> Update;
273
impl_widget_callback!(
274
    OnNodeInputDisconnected,
275
    OptionOnNodeInputDisconnected,
276
    OnNodeInputDisconnectedCallback,
277
    OnNodeInputDisconnectedCallbackType
278
);
279

            
280
pub type OnNodeOutputDisconnectedCallbackType = extern "C" fn(
281
    refany: RefAny,
282
    info: CallbackInfo,
283
    output: NodeGraphNodeId,
284
    output_index: usize,
285
) -> Update;
286
impl_widget_callback!(
287
    OnNodeOutputDisconnected,
288
    OptionOnNodeOutputDisconnected,
289
    OnNodeOutputDisconnectedCallback,
290
    OnNodeOutputDisconnectedCallbackType
291
);
292

            
293
pub type OnNodeFieldEditedCallbackType = extern "C" fn(
294
    refany: RefAny,
295
    info: CallbackInfo,
296
    node_id: NodeGraphNodeId,
297
    field_id: usize,
298
    node_type: NodeTypeId,
299
    new_value: NodeTypeFieldValue,
300
) -> Update;
301
impl_widget_callback!(
302
    OnNodeFieldEdited,
303
    OptionOnNodeFieldEdited,
304
    OnNodeFieldEditedCallback,
305
    OnNodeFieldEditedCallbackType
306
);
307

            
308
/// Unique identifier for an input/output port type.
309
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
310
#[repr(C)]
311
pub struct InputOutputTypeId {
312
    pub inner: u64,
313
}
314

            
315
impl_option!(
316
    InputOutputTypeId,
317
    OptionInputOutputTypeId,
318
    copy = false,
319
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
320
);
321
impl_vec!(
322
    InputOutputTypeId,
323
    InputOutputTypeIdVec,
324
    InputOutputTypeIdVecDestructor,
325
    InputOutputTypeIdVecDestructorType,
326
    InputOutputTypeIdVecSlice,
327
    OptionInputOutputTypeId
328
);
329
impl_vec_clone!(
330
    InputOutputTypeId,
331
    InputOutputTypeIdVec,
332
    InputOutputTypeIdVecDestructor
333
);
334
impl_vec_mut!(InputOutputTypeId, InputOutputTypeIdVec);
335
impl_vec_debug!(InputOutputTypeId, InputOutputTypeIdVec);
336

            
337
/// Unique identifier for a node type (e.g. "Add", "Multiply").
338
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
339
#[repr(C)]
340
pub struct NodeTypeId {
341
    pub inner: u64,
342
}
343

            
344
/// Unique identifier for a node instance within the graph.
345
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
346
#[repr(C)]
347
pub struct NodeGraphNodeId {
348
    pub inner: u64,
349
}
350

            
351
/// A single node with typed input/output connections and editable fields.
352
#[derive(Debug, Clone)]
353
#[repr(C)]
354
pub struct Node {
355
    pub node_type: NodeTypeId,
356
    pub position: NodeGraphNodePosition,
357
    pub fields: NodeTypeFieldVec,
358
    pub connect_in: InputConnectionVec,
359
    pub connect_out: OutputConnectionVec,
360
}
361

            
362
/// A key-value field on a node (e.g. a text input labelled "Name").
363
#[derive(Debug, Clone)]
364
#[repr(C)]
365
pub struct NodeTypeField {
366
    pub key: AzString,
367
    pub value: NodeTypeFieldValue,
368
}
369

            
370
impl_option!(
371
    NodeTypeField,
372
    OptionNodeTypeField,
373
    copy = false,
374
    [Debug, Clone]
375
);
376
impl_vec!(
377
    NodeTypeField,
378
    NodeTypeFieldVec,
379
    NodeTypeFieldVecDestructor,
380
    NodeTypeFieldVecDestructorType,
381
    NodeTypeFieldVecSlice,
382
    OptionNodeTypeField
383
);
384
impl_vec_clone!(NodeTypeField, NodeTypeFieldVec, NodeTypeFieldVecDestructor);
385
impl_vec_debug!(NodeTypeField, NodeTypeFieldVec);
386
impl_vec_mut!(NodeTypeField, NodeTypeFieldVec);
387

            
388
/// The value of a node field, determining which widget is rendered.
389
#[derive(Debug, Clone)]
390
#[repr(C, u8)]
391
pub enum NodeTypeFieldValue {
392
    TextInput(AzString),
393
    NumberInput(f32),
394
    CheckBox(bool),
395
    ColorInput(ColorU),
396
    FileInput(OptionString),
397
}
398

            
399
/// An input port's connections to one or more output ports on other nodes.
400
#[derive(Debug, Clone)]
401
#[repr(C)]
402
pub struct InputConnection {
403
    pub input_index: usize,
404
    pub connects_to: OutputNodeAndIndexVec,
405
}
406

            
407
impl_option!(
408
    InputConnection,
409
    OptionInputConnection,
410
    copy = false,
411
    [Debug, Clone]
412
);
413
impl_vec!(
414
    InputConnection,
415
    InputConnectionVec,
416
    InputConnectionVecDestructor,
417
    InputConnectionVecDestructorType,
418
    InputConnectionVecSlice,
419
    OptionInputConnection
420
);
421
impl_vec_clone!(
422
    InputConnection,
423
    InputConnectionVec,
424
    InputConnectionVecDestructor
425
);
426
impl_vec_debug!(InputConnection, InputConnectionVec);
427
impl_vec_mut!(InputConnection, InputConnectionVec);
428

            
429
/// Reference to a specific output port on a node.
430
#[derive(Copy, Debug, Clone)]
431
#[repr(C)]
432
pub struct OutputNodeAndIndex {
433
    pub node_id: NodeGraphNodeId,
434
    pub output_index: usize,
435
}
436

            
437
impl_option!(
438
    OutputNodeAndIndex,
439
    OptionOutputNodeAndIndex,
440
    copy = false,
441
    [Debug, Clone]
442
);
443
impl_vec!(
444
    OutputNodeAndIndex,
445
    OutputNodeAndIndexVec,
446
    OutputNodeAndIndexVecDestructor,
447
    OutputNodeAndIndexVecDestructorType,
448
    OutputNodeAndIndexVecSlice,
449
    OptionOutputNodeAndIndex
450
);
451
impl_vec_clone!(
452
    OutputNodeAndIndex,
453
    OutputNodeAndIndexVec,
454
    OutputNodeAndIndexVecDestructor
455
);
456
impl_vec_debug!(OutputNodeAndIndex, OutputNodeAndIndexVec);
457
impl_vec_mut!(OutputNodeAndIndex, OutputNodeAndIndexVec);
458

            
459
/// An output port's connections to one or more input ports on other nodes.
460
#[derive(Debug, Clone)]
461
#[repr(C)]
462
pub struct OutputConnection {
463
    pub output_index: usize,
464
    pub connects_to: InputNodeAndIndexVec,
465
}
466

            
467
impl_option!(
468
    OutputConnection,
469
    OptionOutputConnection,
470
    copy = false,
471
    [Debug, Clone]
472
);
473
impl_vec!(
474
    OutputConnection,
475
    OutputConnectionVec,
476
    OutputConnectionVecDestructor,
477
    OutputConnectionVecDestructorType,
478
    OutputConnectionVecSlice,
479
    OptionOutputConnection
480
);
481
impl_vec_clone!(
482
    OutputConnection,
483
    OutputConnectionVec,
484
    OutputConnectionVecDestructor
485
);
486
impl_vec_debug!(OutputConnection, OutputConnectionVec);
487
impl_vec_mut!(OutputConnection, OutputConnectionVec);
488

            
489
/// Reference to a specific input port on a node.
490
#[derive(Copy, Debug, Clone, PartialEq, Eq)]
491
#[repr(C)]
492
pub struct InputNodeAndIndex {
493
    pub node_id: NodeGraphNodeId,
494
    pub input_index: usize,
495
}
496

            
497
impl_option!(
498
    InputNodeAndIndex,
499
    OptionInputNodeAndIndex,
500
    copy = false,
501
    [Debug, Clone]
502
);
503
impl_vec!(
504
    InputNodeAndIndex,
505
    InputNodeAndIndexVec,
506
    InputNodeAndIndexVecDestructor,
507
    InputNodeAndIndexVecDestructorType,
508
    InputNodeAndIndexVecSlice,
509
    OptionInputNodeAndIndex
510
);
511
impl_vec_clone!(
512
    InputNodeAndIndex,
513
    InputNodeAndIndexVec,
514
    InputNodeAndIndexVecDestructor
515
);
516
impl_vec_debug!(InputNodeAndIndex, InputNodeAndIndexVec);
517
impl_vec_mut!(InputNodeAndIndex, InputNodeAndIndexVec);
518

            
519
/// Metadata describing a node type and its I/O port configuration.
520
#[derive(Debug, Clone)]
521
#[repr(C)]
522
pub struct NodeTypeInfo {
523
    /// Whether this node type is a "root" type
524
    pub is_root: bool,
525
    /// Name of the node type
526
    pub node_type_name: AzString,
527
    /// List of inputs for this node
528
    pub inputs: InputOutputTypeIdVec,
529
    /// List of outputs for this node
530
    pub outputs: InputOutputTypeIdVec,
531
}
532

            
533
/// Display metadata for an input/output port type (name and color).
534
#[derive(Debug, Clone)]
535
#[repr(C)]
536
pub struct InputOutputInfo {
537
    /// Data type of this input / output
538
    pub data_type: AzString,
539
    /// Which color to use for the input / output
540
    pub color: ColorU,
541
}
542

            
543
/// Things only relevant to the display of the node in an interactive editor
544
/// - such as x and y position in the node graph, name, etc.
545
#[derive(Debug, Copy, Clone)]
546
#[repr(C)]
547
pub struct NodeGraphNodePosition {
548
    /// X Position of the node
549
    pub x: f32,
550
    /// Y Position of the node
551
    pub y: f32,
552
}
553

            
554
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
555
#[repr(C)]
556
pub enum NodeGraphError {
557
    /// MIME type is not the same (for example: connection "spatialdata/point"
558
    /// with a node that expects "spatialdata/line")
559
    NodeMimeTypeMismatch,
560
    /// Invalid index when accessing a node in / output
561
    NodeInvalidIndex,
562
    /// The in-/ output matching encountered a non-existing hash to a node that doesn't exist
563
    NodeInvalidNode,
564
    /// Root node is missing from the graph tree
565
    NoRootNode,
566
}
567

            
568
impl fmt::Display for NodeGraphError {
569
24
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
570
        use self::NodeGraphError::{
571
            NoRootNode, NodeInvalidIndex, NodeInvalidNode, NodeMimeTypeMismatch,
572
        };
573
24
        match self {
574
6
            NodeMimeTypeMismatch => write!(f, "MIME type mismatch"),
575
6
            NodeInvalidIndex => write!(f, "Invalid node index"),
576
6
            NodeInvalidNode => write!(f, "Invalid node"),
577
6
            NoRootNode => write!(f, "No root node found"),
578
        }
579
24
    }
580
}
581

            
582
/// Amount (in logical pixels) the entire graph was dragged.
583
#[derive(Debug, Copy, Clone, PartialEq)]
584
#[repr(C)]
585
pub struct GraphDragAmount {
586
    pub x: f32,
587
    pub y: f32,
588
}
589

            
590
/// Amount (in logical pixels) a single node was dragged.
591
#[derive(Debug, Copy, Clone, PartialEq)]
592
#[repr(C)]
593
pub struct NodeDragAmount {
594
    pub x: f32,
595
    pub y: f32,
596
}
597

            
598
impl NodeGraph {
599
    #[must_use]
600
6
    pub fn swap_with_default(&mut self) -> Self {
601
6
        let mut default = Self::default();
602
6
        ::core::mem::swap(&mut default, self);
603
6
        default
604
6
    }
605

            
606
    /// Connects the current nodes input with another nodes output
607
    ///
608
    /// ## Inputs
609
    ///
610
    /// - `output_node_id`: The ID of the output node (index in the `NodeGraphs` internal `BTree`)
611
    /// - `output_index`: The index of the output *on the output node*
612
    /// - `input_node_id`: Same as `output_node_id`, but for the input node
613
    /// - `input_index`: Same as `output_index`, but for the input node
614
    ///
615
    /// ## Returns
616
    ///
617
    /// One of:
618
    ///
619
    /// - `NodeGraphError::NodeInvalidNode`: One of the input nodes does not exist
620
    /// - `NodeGraphError::NodeInvalidIndex`: One node has an invalid `output` or `input` index
621
    /// - `NodeGraphError::NodeMimeTypeMismatch`: The types of two connected `outputs` and `inputs`
622
    ///   aren't the same
623
    /// - `Ok(())`: The connection was established successfully.
624
45
    fn connect_input_output(
625
45
        &mut self,
626
45
        input_node_id: NodeGraphNodeId,
627
45
        input_index: usize,
628
45
        output_node_id: NodeGraphNodeId,
629
45
        output_index: usize,
630
45
    ) -> Result<(), NodeGraphError> {
631
        // Verify that the node type of the connection matches
632
45
        self.verify_nodetype_match(output_node_id, output_index, input_node_id, input_index)?;
633

            
634
        // connect input -> output
635
34
        if let Some(input_node) = self
636
34
            .nodes
637
34
            .as_mut()
638
34
            .iter_mut()
639
105
            .find(|i| i.node_id == input_node_id)
640
        {
641
34
            if let Some(position) = input_node
642
34
                .node
643
34
                .connect_in
644
34
                .as_ref()
645
34
                .iter()
646
34
                .position(|i| i.input_index == input_index)
647
4
            {
648
4
                input_node.node.connect_in.as_mut()[position]
649
4
                    .connects_to
650
4
                    .push(OutputNodeAndIndex {
651
4
                        node_id: output_node_id,
652
4
                        output_index,
653
4
                    });
654
30
            } else {
655
30
                input_node.node.connect_in.push(InputConnection {
656
30
                    input_index,
657
30
                    connects_to: vec![OutputNodeAndIndex {
658
30
                        node_id: output_node_id,
659
30
                        output_index,
660
30
                    }]
661
30
                    .into(),
662
30
                });
663
30
            }
664
        } else {
665
            return Err(NodeGraphError::NodeInvalidNode);
666
        }
667

            
668
        // connect output -> input
669
34
        if let Some(output_node) = self
670
34
            .nodes
671
34
            .as_mut()
672
34
            .iter_mut()
673
40
            .find(|i| i.node_id == output_node_id)
674
        {
675
34
            if let Some(position) = output_node
676
34
                .node
677
34
                .connect_out
678
34
                .as_ref()
679
34
                .iter()
680
34
                .position(|i| i.output_index == output_index)
681
5
            {
682
5
                output_node.node.connect_out.as_mut()[position]
683
5
                    .connects_to
684
5
                    .push(InputNodeAndIndex {
685
5
                        node_id: input_node_id,
686
5
                        input_index,
687
5
                    });
688
29
            } else {
689
29
                output_node.node.connect_out.push(OutputConnection {
690
29
                    output_index,
691
29
                    connects_to: vec![InputNodeAndIndex {
692
29
                        node_id: input_node_id,
693
29
                        input_index,
694
29
                    }]
695
29
                    .into(),
696
29
                });
697
29
            }
698
        } else {
699
            return Err(NodeGraphError::NodeInvalidNode);
700
        }
701

            
702
34
        Ok(())
703
45
    }
704

            
705
    /// Disconnect an input if it is connected to an output
706
    ///
707
    /// # Inputs
708
    ///
709
    /// - `input_node_id`: The ID of the input node (index in the `NodeGraphs` internal `BTree`)
710
    /// - `input_index`: The index of the input *on the input node*
711
    ///
712
    /// # Returns
713
    ///
714
    /// - `Err(NodeGraphError::NodeInvalidNode)`: The node at index `input_node_id` does not exist
715
    /// - `Err(NodeGraphError::NodeInvalidIndex)`: One node has an invalid `input` or `output` index
716
    /// - `Err(NodeGraphError::NodeMimeTypeMismatch)`: The types of two connected `input` and
717
    ///   `output` do not match
718
    /// - `Ok(())`: The disconnection completed successfully.
719
6
    fn disconnect_input(
720
6
        &mut self,
721
6
        input_node_id: NodeGraphNodeId,
722
6
        input_index: usize,
723
6
    ) -> Result<(), NodeGraphError> {
724
3
        let output_connections = {
725
6
            let input_node = self
726
6
                .nodes
727
6
                .as_ref()
728
6
                .iter()
729
20
                .find(|i| i.node_id == input_node_id)
730
6
                .ok_or(NodeGraphError::NodeInvalidNode)?;
731

            
732
5
            match input_node
733
5
                .node
734
5
                .connect_in
735
5
                .iter()
736
5
                .find(|i| i.input_index == input_index)
737
            {
738
2
                None => return Ok(()),
739
3
                Some(s) => s.connects_to.clone(),
740
            }
741
        };
742

            
743
        // for every output that this input was connected to...
744
        for OutputNodeAndIndex {
745
4
            node_id,
746
4
            output_index,
747
3
        } in output_connections.as_ref()
748
        {
749
4
            let output_node_id = *node_id;
750
4
            let output_index = *output_index;
751

            
752
            // verify that the node type of the connection matches
753
4
            self.verify_nodetype_match(output_node_id, output_index, input_node_id, input_index)?;
754

            
755
            // disconnect input -> output
756

            
757
4
            if let Some(input_node) = self
758
4
                .nodes
759
4
                .as_mut()
760
4
                .iter_mut()
761
14
                .find(|i| i.node_id == input_node_id)
762
            {
763
4
                if let Some(position) = input_node
764
4
                    .node
765
4
                    .connect_in
766
4
                    .iter()
767
4
                    .position(|i| i.input_index == input_index)
768
3
                {
769
3
                    input_node.node.connect_in.remove(position);
770
3
                }
771
            } else {
772
                return Err(NodeGraphError::NodeInvalidNode);
773
            }
774

            
775
4
            if let Some(output_node) = self
776
4
                .nodes
777
4
                .as_mut()
778
4
                .iter_mut()
779
6
                .find(|i| i.node_id == output_node_id)
780
            {
781
4
                if let Some(position) = output_node
782
4
                    .node
783
4
                    .connect_out
784
4
                    .iter()
785
4
                    .position(|i| i.output_index == output_index)
786
4
                {
787
4
                    output_node.node.connect_out.remove(position);
788
4
                }
789
            } else {
790
                return Err(NodeGraphError::NodeInvalidNode);
791
            }
792
        }
793

            
794
3
        Ok(())
795
6
    }
796

            
797
    /// Disconnect an output if it is connected to an input
798
    ///
799
    /// # Inputs
800
    ///
801
    /// - `output_node_id`: The ID of the output node (index in the `NodeGraphs` internal `BTree`)
802
    /// - `output_index`: The index of the output *on the output node*
803
    ///
804
    /// # Returns
805
    ///
806
    /// - `Err(NodeGraphError::NodeInvalidNode)`: The node at index `output_node_id` does not exist
807
    /// - `Err(NodeGraphError::NodeInvalidIndex)`: One node has an invalid `input` or `output` index
808
    /// - `Err(NodeGraphError::NodeMimeTypeMismatch)`: The types of two connected `input` and
809
    ///   `output` do not match
810
    /// - `Ok(())`: The disconnection completed successfully.
811
6
    fn disconnect_output(
812
6
        &mut self,
813
6
        output_node_id: NodeGraphNodeId,
814
6
        output_index: usize,
815
6
    ) -> Result<(), NodeGraphError> {
816
3
        let input_connections = {
817
6
            let output_node = self
818
6
                .nodes
819
6
                .as_ref()
820
6
                .iter()
821
9
                .find(|i| i.node_id == output_node_id)
822
6
                .ok_or(NodeGraphError::NodeInvalidNode)?;
823

            
824
5
            match output_node
825
5
                .node
826
5
                .connect_out
827
5
                .iter()
828
5
                .find(|i| i.output_index == output_index)
829
            {
830
2
                None => return Ok(()),
831
3
                Some(s) => s.connects_to.clone(),
832
            }
833
        };
834

            
835
        for InputNodeAndIndex {
836
4
            node_id,
837
4
            input_index,
838
7
        } in &input_connections
839
        {
840
4
            let input_node_id = *node_id;
841
4
            let input_index = *input_index;
842

            
843
            // verify that the node type of the connection matches
844
4
            self.verify_nodetype_match(output_node_id, output_index, input_node_id, input_index)?;
845

            
846
4
            if let Some(output_node) = self
847
4
                .nodes
848
4
                .as_mut()
849
4
                .iter_mut()
850
4
                .find(|i| i.node_id == output_node_id)
851
            {
852
4
                if let Some(position) = output_node
853
4
                    .node
854
4
                    .connect_out
855
4
                    .iter()
856
4
                    .position(|i| i.output_index == output_index)
857
3
                {
858
3
                    output_node.node.connect_out.remove(position);
859
3
                }
860
            } else {
861
                return Err(NodeGraphError::NodeInvalidNode);
862
            }
863

            
864
4
            if let Some(input_node) = self
865
4
                .nodes
866
4
                .as_mut()
867
4
                .iter_mut()
868
11
                .find(|i| i.node_id == input_node_id)
869
            {
870
4
                if let Some(position) = input_node
871
4
                    .node
872
4
                    .connect_in
873
4
                    .iter()
874
4
                    .position(|i| i.input_index == input_index)
875
4
                {
876
4
                    input_node.node.connect_in.remove(position);
877
4
                }
878
            } else {
879
                return Err(NodeGraphError::NodeInvalidNode);
880
            }
881
        }
882

            
883
3
        Ok(())
884
6
    }
885

            
886
    /// Verifies that the node types of two connections match
887
68
    fn verify_nodetype_match(
888
68
        &self,
889
68
        output_node_id: NodeGraphNodeId,
890
68
        output_index: usize,
891
68
        input_node_id: NodeGraphNodeId,
892
68
        input_index: usize,
893
68
    ) -> Result<(), NodeGraphError> {
894
68
        let output_node = self
895
68
            .nodes
896
68
            .iter()
897
95
            .find(|i| i.node_id == output_node_id)
898
68
            .ok_or(NodeGraphError::NodeInvalidNode)?;
899

            
900
63
        let output_node_type = self
901
63
            .node_types
902
63
            .iter()
903
64
            .find(|i| i.node_type_id == output_node.node.node_type)
904
63
            .ok_or(NodeGraphError::NodeInvalidNode)?;
905

            
906
62
        let output_type = output_node_type
907
62
            .node_type_info
908
62
            .outputs
909
62
            .as_ref()
910
62
            .get(output_index)
911
62
            .copied()
912
62
            .ok_or(NodeGraphError::NodeInvalidIndex)?;
913

            
914
55
        let input_node = self
915
55
            .nodes
916
55
            .iter()
917
168
            .find(|i| i.node_id == input_node_id)
918
55
            .ok_or(NodeGraphError::NodeInvalidNode)?;
919

            
920
53
        let input_node_type = self
921
53
            .node_types
922
53
            .iter()
923
57
            .find(|i| i.node_type_id == input_node.node.node_type)
924
53
            .ok_or(NodeGraphError::NodeInvalidNode)?;
925

            
926
52
        let input_type = input_node_type
927
52
            .node_type_info
928
52
            .inputs
929
52
            .as_ref()
930
52
            .get(input_index)
931
52
            .copied()
932
52
            .ok_or(NodeGraphError::NodeInvalidIndex)?;
933

            
934
        // Input / Output do not have the same TypeId
935
48
        if input_type != output_type {
936
3
            return Err(NodeGraphError::NodeMimeTypeMismatch);
937
45
        }
938

            
939
45
        Ok(())
940
68
    }
941

            
942
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
943
    #[must_use]
944
19
    pub fn dom(self) -> Dom {
945
        static NODEGRAPH_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str("nodegraph"))];
946

            
947
        static NODEGRAPH_BACKGROUND: &[StyleBackgroundContent] = &[StyleBackgroundContent::Image(
948
            AzString::from_const_str("nodegraph-background"),
949
        )];
950

            
951
        static NODEGRAPH_NODES_CONTAINER_CLASS: &[IdOrClass] =
952
            &[Class(AzString::from_const_str("nodegraph-nodes-container"))];
953

            
954
        static NODEGRAPH_NODES_CONTAINER_PROPS: &[CssPropertyWithConditions] = &[
955
            CssPropertyWithConditions::simple(CssProperty::flex_grow(LayoutFlexGrow::const_new(1))),
956
            CssPropertyWithConditions::simple(CssProperty::position(LayoutPosition::Absolute)),
957
        ];
958

            
959
19
        let nodegraph_wrapper_props = vec![
960
19
            CssPropertyWithConditions::simple(CssProperty::overflow_x(LayoutOverflow::Hidden)),
961
19
            CssPropertyWithConditions::simple(CssProperty::overflow_y(LayoutOverflow::Hidden)),
962
19
            CssPropertyWithConditions::simple(CssProperty::flex_grow(LayoutFlexGrow::const_new(1))),
963
19
            CssPropertyWithConditions::simple(CssProperty::background_content(
964
19
                StyleBackgroundContentVec::from_const_slice(NODEGRAPH_BACKGROUND),
965
            )),
966
19
            CssPropertyWithConditions::simple(CssProperty::background_repeat(
967
19
                vec![StyleBackgroundRepeat::PatternRepeat].into(),
968
            )),
969
19
            CssPropertyWithConditions::simple(CssProperty::background_position(
970
19
                vec![StyleBackgroundPosition {
971
19
                    horizontal: BackgroundPositionHorizontal::Exact(PixelValue::const_px(0)),
972
19
                    vertical: BackgroundPositionVertical::Exact(PixelValue::const_px(0)),
973
19
                }]
974
19
                .into(),
975
            )),
976
        ];
977

            
978
19
        let nodegraph_props = vec![
979
19
            CssPropertyWithConditions::simple(CssProperty::overflow_x(LayoutOverflow::Hidden)),
980
19
            CssPropertyWithConditions::simple(CssProperty::overflow_y(LayoutOverflow::Hidden)),
981
19
            CssPropertyWithConditions::simple(CssProperty::flex_grow(LayoutFlexGrow::const_new(1))),
982
19
            CssPropertyWithConditions::simple(CssProperty::position(LayoutPosition::Relative)),
983
        ];
984

            
985
19
        let marker_prefix = next_marker_prefix();
986
19
        let connections_marker: AzString = format!("{}-connections", marker_prefix.as_str()).into();
987

            
988
19
        let node_graph_local_dataset = RefAny::new(NodeGraphLocalDataset {
989
19
            node_graph: self.clone(), // TODO: expensive
990
19
            last_input_or_output_clicked: None,
991
19
            active_node_being_dragged: None,
992
19
            marker_prefix: marker_prefix.clone(),
993
19
            callbacks: self.callbacks.clone(),
994
19
        });
995

            
996
19
        let context_menu = Menu::create(
997
19
            vec![MenuItem::String(
998
19
                StringMenuItem::create(self.add_node_str.clone()).with_children(
999
19
                    self.node_types
19
                        .iter()
19
                        .map(
                            |NodeTypeIdInfoMap {
                                 node_type_id,
                                 node_type_info,
29
                             }| {
29
                                let context_menu_local_dataset =
29
                                    RefAny::new(ContextMenuEntryLocalDataset {
29
                                        node_type: *node_type_id,
29
                                        // RefAny<NodeGraphLocalDataset>
29
                                        backref: node_graph_local_dataset.clone(),
29
                                    });
29
                                MenuItem::String(
29
                                    StringMenuItem::create(node_type_info.node_type_name.clone())
29
                                        .with_callback(
29
                                            context_menu_local_dataset,
29
                                            nodegraph_context_menu_click as usize,
29
                                        ),
29
                                )
29
                            },
                        )
19
                        .collect::<Vec<_>>()
19
                        .into(),
                ),
            )]
19
            .into(),
        );
19
        Dom::create_div()
19
            .with_css_props(nodegraph_wrapper_props.into())
19
            .with_context_menu(context_menu)
19
            .with_children(
19
                vec![Dom::create_div()
19
                    .with_ids_and_classes(IdOrClassVec::from_const_slice(NODEGRAPH_CLASS))
19
                    .with_css_props(nodegraph_props.into())
19
                    .with_callbacks(
19
                        vec![
19
                            CoreCallbackData {
19
                                event: EventFilter::Hover(HoverEventFilter::MouseMove),
19
                                refany: node_graph_local_dataset.clone(),
19
                                callback: CoreCallback {
19
                                    cb: nodegraph_drag_graph_or_nodes as usize,
19
                                    ctx: OptionRefAny::None,
19
                                },
19
                            },
19
                            CoreCallbackData {
19
                                event: EventFilter::Hover(HoverEventFilter::LeftMouseUp),
19
                                refany: node_graph_local_dataset.clone(),
19
                                callback: CoreCallback {
19
                                    cb: nodegraph_unset_active_node as usize,
19
                                    ctx: OptionRefAny::None,
19
                                },
19
                            },
                        ]
19
                        .into(),
                    )
19
                    .with_children({
19
                        vec![
                            // connections
19
                            render_connections(&self, connections_marker),
                            // nodes
19
                            self.nodes
19
                                .iter()
58
                                .filter_map(|NodeIdNodeMap { node_id, node }| {
58
                                    let node_type_info = self
58
                                        .node_types
58
                                        .iter()
67
                                        .find(|i| i.node_type_id == node.node_type)?;
53
                                    let node_local_dataset = NodeLocalDataset {
53
                                        node_id: *node_id,
53
                                        backref: node_graph_local_dataset.clone(),
53
                                    };
53
                                    Some(render_node(
53
                                        node,
53
                                        (self.offset.x, self.offset.y),
53
                                        &node_type_info.node_type_info,
53
                                        node_local_dataset,
53
                                        self.scale_factor,
53
                                        node_marker(&marker_prefix, *node_id),
53
                                    ))
58
                                })
19
                                .collect::<Dom>()
19
                                .with_ids_and_classes(IdOrClassVec::from_const_slice(
19
                                    NODEGRAPH_NODES_CONTAINER_CLASS,
                                ))
19
                                .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
19
                                    NODEGRAPH_NODES_CONTAINER_PROPS,
                                )),
                        ]
19
                        .into()
                    })]
19
                .into(),
            )
19
            .with_dataset(Some(node_graph_local_dataset).into())
            // The wrapper's marker: what the context-menu callback resolves
            // to place a new node relative to this graph's on-screen box.
19
            .with_marker(Some(marker_prefix).into())
19
    }
}
/// Process-unique prefix for one `NodeGraph::dom()` render's marker strings.
/// The prefix (and every marker derived from it) is rebuilt together with the
/// dataset that stores it on each `layout()` pass, so lookups made through
/// the live dataset always match the live DOM.
19
fn next_marker_prefix() -> AzString {
    use core::sync::atomic::{AtomicU64, Ordering};
    static NEXT: AtomicU64 = AtomicU64::new(1);
19
    format!("azul-nodegraph-{:x}", NEXT.fetch_add(1, Ordering::Relaxed)).into()
19
}
/// Marker string of one visual node: `{prefix}-node-{id}`.
83
fn node_marker(prefix: &AzString, node_id: NodeGraphNodeId) -> AzString {
83
    format!("{}-node-{:x}", prefix.as_str(), node_id.inner).into()
83
}
// dataset set on the top-level nodegraph node,
// containing all the state of the node graph
struct NodeGraphLocalDataset {
    node_graph: NodeGraph,
    last_input_or_output_clicked: Option<(NodeGraphNodeId, InputOrOutput)>,
    /// The graph node currently being dragged. Its VISUAL node is resolved
    /// via `node_marker(&marker_prefix, id)` — no dataset handle needed.
    active_node_being_dragged: Option<NodeGraphNodeId>,
    /// Prefix of this render's marker strings (see `next_marker_prefix`):
    /// the wrapper carries `{prefix}`, the connections container
    /// `{prefix}-connections`, each visual node `{prefix}-node-{id}`.
    /// Replaces the old empty-marker-dataset type searches
    /// (`get_node_id_of_root_dataset`), which were ambiguous the moment two
    /// datasets of one type existed.
    marker_prefix: AzString,
    callbacks: NodeGraphCallbacks,
}
struct ContextMenuEntryLocalDataset {
    node_type: NodeTypeId,
    backref: RefAny, // RefAny<NodeGraphLocalDataset>
}
struct NodeLocalDataset {
    node_id: NodeGraphNodeId,
    backref: RefAny, // RefAny<NodeGraphLocalDataset>
}
#[derive(Debug, Copy, Clone)]
enum InputOrOutput {
    Input(usize),
    Output(usize),
}
struct NodeInputOutputLocalDataset {
    io_id: InputOrOutput,
    backref: RefAny, // RefAny<NodeLocalDataset>
}
struct NodeFieldLocalDataset {
    field_idx: usize,
    backref: RefAny, // RefAny<NodeLocalDataset>
}
#[derive(Copy, Clone)]
struct ConnectionLocalDataset {
    out_node_id: NodeGraphNodeId,
    out_idx: usize,
    in_node_id: NodeGraphNodeId,
    in_idx: usize,
    swap_vert: bool,
    swap_horz: bool,
    color: ColorU,
}
#[allow(clippy::float_cmp)] // intentional exact compare: change-detection / identity fast-path / cache-key match
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine
                                 // (one branch per case)
83
fn render_node(
83
    node: &Node,
83
    graph_offset: (f32, f32),
83
    node_info: &NodeTypeInfo,
83
    mut node_local_dataset: NodeLocalDataset,
83
    scale_factor: f32,
83
    visual_marker: AzString,
83
) -> Dom {
    use azul_core::dom::{
        CssPropertyWithConditions, CssPropertyWithConditionsVec, Dom, DomVec, IdOrClass,
        IdOrClass::Class, IdOrClassVec,
    };
    #[allow(clippy::wildcard_imports)]
    // widget/render module pulls in the css property/value types it builds with
    use azul_css::*;
    const STRING_9416190750059025162: AzString = AzString::from_const_str("Material Icons");
    const STRING_16146701490593874959: AzString = AzString::from_const_str("system:ui");
    const STYLE_BACKGROUND_CONTENT_524016094839686509_ITEMS: &[StyleBackgroundContent] =
        &[StyleBackgroundContent::Color(ColorU {
            r: 34,
            g: 34,
            b: 34,
            a: 255,
        })];
    const STYLE_BACKGROUND_CONTENT_10430246856047584562_ITEMS: &[StyleBackgroundContent] =
        &[StyleBackgroundContent::LinearGradient(LinearGradient {
            direction: Direction::FromTo(DirectionCorners {
                dir_from: DirectionCorner::Left,
                dir_to: DirectionCorner::Right,
            }),
            extend_mode: ExtendMode::Clamp,
            stops: NormalizedLinearColorStopVec::from_const_slice(
                LINEAR_COLOR_STOP_4373556077110009258_ITEMS,
            ),
        })];
    const STYLE_BACKGROUND_CONTENT_11535310356736632656_ITEMS: &[StyleBackgroundContent] =
        &[StyleBackgroundContent::RadialGradient(RadialGradient {
            shape: Shape::Ellipse,
            extend_mode: ExtendMode::Clamp,
            position: StyleBackgroundPosition {
                horizontal: BackgroundPositionHorizontal::Left,
                vertical: BackgroundPositionVertical::Top,
            },
            size: RadialGradientSize::FarthestCorner,
            stops: NormalizedLinearColorStopVec::from_const_slice(
                LINEAR_COLOR_STOP_15596411095679453272_ITEMS,
            ),
        })];
    const STYLE_BACKGROUND_CONTENT_11936041127084538304_ITEMS: &[StyleBackgroundContent] =
        &[StyleBackgroundContent::LinearGradient(LinearGradient {
            direction: Direction::FromTo(DirectionCorners {
                dir_from: DirectionCorner::Right,
                dir_to: DirectionCorner::Left,
            }),
            extend_mode: ExtendMode::Clamp,
            stops: NormalizedLinearColorStopVec::from_const_slice(
                LINEAR_COLOR_STOP_4373556077110009258_ITEMS,
            ),
        })];
    const STYLE_BACKGROUND_CONTENT_15813232491335471489_ITEMS: &[StyleBackgroundContent] =
        &[StyleBackgroundContent::Color(ColorU {
            r: 0,
            g: 0,
            b: 0,
            a: 85,
        })];
    const STYLE_BACKGROUND_CONTENT_17648039690071193942_ITEMS: &[StyleBackgroundContent] =
        &[StyleBackgroundContent::LinearGradient(LinearGradient {
            direction: Direction::FromTo(DirectionCorners {
                dir_from: DirectionCorner::Top,
                dir_to: DirectionCorner::Bottom,
            }),
            extend_mode: ExtendMode::Clamp,
            stops: NormalizedLinearColorStopVec::from_const_slice(
                LINEAR_COLOR_STOP_7397113864565941600_ITEMS,
            ),
        })];
    const STYLE_TRANSFORM_347117342922946953_ITEMS: &[StyleTransform] =
        &[StyleTransform::Translate(StyleTransformTranslate2D {
            x: PixelValue::const_px(200),
            y: PixelValue::const_px(100),
        })];
    const STYLE_TRANSFORM_14683950870521466298_ITEMS: &[StyleTransform] =
        &[StyleTransform::Translate(StyleTransformTranslate2D {
            x: PixelValue::const_px(240),
            y: PixelValue::const_px(-10),
        })];
    const STYLE_FONT_FAMILY_8122988506401935406_ITEMS: &[StyleFontFamily] =
        &[StyleFontFamily::System(STRING_16146701490593874959)];
    const STYLE_FONT_FAMILY_11383897783350685780_ITEMS: &[StyleFontFamily] =
        &[StyleFontFamily::System(STRING_9416190750059025162)];
    const LINEAR_COLOR_STOP_4373556077110009258_ITEMS: &[NormalizedLinearColorStop] = &[
        NormalizedLinearColorStop {
            offset: PercentageValue::const_new(20),
            color: ColorOrSystem::color(ColorU {
                r: 0,
                g: 0,
                b: 0,
                a: 204,
            }),
        },
        NormalizedLinearColorStop {
            offset: PercentageValue::const_new(100),
            color: ColorOrSystem::color(ColorU {
                r: 0,
                g: 0,
                b: 0,
                a: 0,
            }),
        },
    ];
    const LINEAR_COLOR_STOP_7397113864565941600_ITEMS: &[NormalizedLinearColorStop] = &[
        NormalizedLinearColorStop {
            offset: PercentageValue::const_new(0),
            color: ColorOrSystem::color(ColorU {
                r: 229,
                g: 57,
                b: 53,
                a: 255,
            }),
        },
        NormalizedLinearColorStop {
            offset: PercentageValue::const_new(100),
            color: ColorOrSystem::color(ColorU {
                r: 227,
                g: 93,
                b: 91,
                a: 255,
            }),
        },
    ];
    const LINEAR_COLOR_STOP_15596411095679453272_ITEMS: &[NormalizedLinearColorStop] = &[
        NormalizedLinearColorStop {
            offset: PercentageValue::const_new(0),
            color: ColorOrSystem::color(ColorU {
                r: 47,
                g: 49,
                b: 54,
                a: 255,
            }),
        },
        NormalizedLinearColorStop {
            offset: PercentageValue::const_new(50),
            color: ColorOrSystem::color(ColorU {
                r: 47,
                g: 49,
                b: 54,
                a: 255,
            }),
        },
        NormalizedLinearColorStop {
            offset: PercentageValue::const_new(100),
            color: ColorOrSystem::color(ColorU {
                r: 32,
                g: 34,
                b: 37,
                a: 255,
            }),
        },
    ];
    const CSS_MATCH_10339190304804100510_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .node_output_wrapper
        CssPropertyWithConditions::simple(CssProperty::Display(LayoutDisplayValue::Exact(
            LayoutDisplay::Flex,
        ))),
        CssPropertyWithConditions::simple(CssProperty::FlexDirection(
            LayoutFlexDirectionValue::Exact(LayoutFlexDirection::Column),
        )),
        CssPropertyWithConditions::simple(CssProperty::Left(LayoutLeftValue::Exact(LayoutLeft {
            inner: PixelValue::const_px(0),
        }))),
        CssPropertyWithConditions::simple(CssProperty::OverflowX(LayoutOverflowValue::Exact(
            LayoutOverflow::Visible,
        ))),
        CssPropertyWithConditions::simple(CssProperty::OverflowY(LayoutOverflowValue::Exact(
            LayoutOverflow::Visible,
        ))),
        CssPropertyWithConditions::simple(CssProperty::Position(LayoutPositionValue::Exact(
            LayoutPosition::Absolute,
        ))),
    ];
    const CSS_MATCH_10339190304804100510: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_10339190304804100510_PROPERTIES);
    const CSS_MATCH_11452431279102104133_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .node_input_connection_label
        CssPropertyWithConditions::simple(CssProperty::FontFamily(StyleFontFamilyVecValue::Exact(
            StyleFontFamilyVec::from_const_slice(STYLE_FONT_FAMILY_8122988506401935406_ITEMS),
        ))),
        CssPropertyWithConditions::simple(CssProperty::FontSize(StyleFontSizeValue::Exact(
            StyleFontSize {
                inner: PixelValue::const_px(12),
            },
        ))),
        CssPropertyWithConditions::simple(CssProperty::Height(LayoutHeightValue::Exact(
            LayoutHeight::Px(PixelValue::const_px(15)),
        ))),
        CssPropertyWithConditions::simple(CssProperty::TextAlign(StyleTextAlignValue::Exact(
            StyleTextAlign::Right,
        ))),
        CssPropertyWithConditions::simple(CssProperty::Width(LayoutWidthValue::Exact(
            LayoutWidth::Px(PixelValue::const_px(100)),
        ))),
    ];
    const CSS_MATCH_11452431279102104133: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_11452431279102104133_PROPERTIES);
    const CSS_MATCH_1173826950760010563_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .node_configuration_field_value:focus
        CssPropertyWithConditions::simple(CssProperty::BorderTopColor(
            StyleBorderTopColorValue::Exact(StyleBorderTopColor {
                inner: ColorU {
                    r: 0,
                    g: 131,
                    b: 176,
                    a: 119,
                },
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderRightColor(
            StyleBorderRightColorValue::Exact(StyleBorderRightColor {
                inner: ColorU {
                    r: 0,
                    g: 131,
                    b: 176,
                    a: 119,
                },
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderLeftColor(
            StyleBorderLeftColorValue::Exact(StyleBorderLeftColor {
                inner: ColorU {
                    r: 0,
                    g: 131,
                    b: 176,
                    a: 119,
                },
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderBottomColor(
            StyleBorderBottomColorValue::Exact(StyleBorderBottomColor {
                inner: ColorU {
                    r: 0,
                    g: 131,
                    b: 176,
                    a: 119,
                },
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderTopStyle(
            StyleBorderTopStyleValue::Exact(StyleBorderTopStyle {
                inner: BorderStyle::Solid,
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderRightStyle(
            StyleBorderRightStyleValue::Exact(StyleBorderRightStyle {
                inner: BorderStyle::Solid,
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderLeftStyle(
            StyleBorderLeftStyleValue::Exact(StyleBorderLeftStyle {
                inner: BorderStyle::Solid,
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderBottomStyle(
            StyleBorderBottomStyleValue::Exact(StyleBorderBottomStyle {
                inner: BorderStyle::Solid,
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderTopWidth(
            LayoutBorderTopWidthValue::Exact(LayoutBorderTopWidth {
                inner: PixelValue::const_px(1),
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderRightWidth(
            LayoutBorderRightWidthValue::Exact(LayoutBorderRightWidth {
                inner: PixelValue::const_px(1),
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderLeftWidth(
            LayoutBorderLeftWidthValue::Exact(LayoutBorderLeftWidth {
                inner: PixelValue::const_px(1),
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderBottomWidth(
            LayoutBorderBottomWidthValue::Exact(LayoutBorderBottomWidth {
                inner: PixelValue::const_px(1),
            }),
        )),
        // .node_configuration_field_value
        CssPropertyWithConditions::simple(CssProperty::AlignItems(LayoutAlignItemsValue::Exact(
            LayoutAlignItems::Center,
        ))),
        CssPropertyWithConditions::simple(CssProperty::BackgroundContent(
            StyleBackgroundContentVecValue::Exact(StyleBackgroundContentVec::from_const_slice(
                STYLE_BACKGROUND_CONTENT_524016094839686509_ITEMS,
            )),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderTopColor(
            StyleBorderTopColorValue::Exact(StyleBorderTopColor {
                inner: ColorU {
                    r: 54,
                    g: 57,
                    b: 63,
                    a: 255,
                },
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderRightColor(
            StyleBorderRightColorValue::Exact(StyleBorderRightColor {
                inner: ColorU {
                    r: 54,
                    g: 57,
                    b: 63,
                    a: 255,
                },
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderLeftColor(
            StyleBorderLeftColorValue::Exact(StyleBorderLeftColor {
                inner: ColorU {
                    r: 54,
                    g: 57,
                    b: 63,
                    a: 255,
                },
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderBottomColor(
            StyleBorderBottomColorValue::Exact(StyleBorderBottomColor {
                inner: ColorU {
                    r: 54,
                    g: 57,
                    b: 63,
                    a: 255,
                },
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderTopStyle(
            StyleBorderTopStyleValue::Exact(StyleBorderTopStyle {
                inner: BorderStyle::Solid,
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderRightStyle(
            StyleBorderRightStyleValue::Exact(StyleBorderRightStyle {
                inner: BorderStyle::Solid,
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderLeftStyle(
            StyleBorderLeftStyleValue::Exact(StyleBorderLeftStyle {
                inner: BorderStyle::Solid,
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderBottomStyle(
            StyleBorderBottomStyleValue::Exact(StyleBorderBottomStyle {
                inner: BorderStyle::Solid,
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderTopWidth(
            LayoutBorderTopWidthValue::Exact(LayoutBorderTopWidth {
                inner: PixelValue::const_px(1),
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderRightWidth(
            LayoutBorderRightWidthValue::Exact(LayoutBorderRightWidth {
                inner: PixelValue::const_px(1),
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderLeftWidth(
            LayoutBorderLeftWidthValue::Exact(LayoutBorderLeftWidth {
                inner: PixelValue::const_px(1),
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderBottomWidth(
            LayoutBorderBottomWidthValue::Exact(LayoutBorderBottomWidth {
                inner: PixelValue::const_px(1),
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::FlexGrow(LayoutFlexGrowValue::Exact(
            LayoutFlexGrow {
                inner: FloatValue::const_new(1),
            },
        ))),
        CssPropertyWithConditions::simple(CssProperty::TextAlign(StyleTextAlignValue::Exact(
            StyleTextAlign::Left,
        ))),
    ];
    const CSS_MATCH_1173826950760010563: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_1173826950760010563_PROPERTIES);
    const CSS_MATCH_1198521124955124418_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .node_configuration_field_label
        CssPropertyWithConditions::simple(CssProperty::AlignItems(LayoutAlignItemsValue::Exact(
            LayoutAlignItems::Center,
        ))),
        CssPropertyWithConditions::simple(CssProperty::FlexGrow(LayoutFlexGrowValue::Exact(
            LayoutFlexGrow {
                inner: FloatValue::const_new(1),
            },
        ))),
        CssPropertyWithConditions::simple(CssProperty::MaxWidth(LayoutMaxWidthValue::Exact(
            LayoutMaxWidth {
                inner: PixelValue::const_px(120),
            },
        ))),
        CssPropertyWithConditions::simple(CssProperty::PaddingLeft(LayoutPaddingLeftValue::Exact(
            LayoutPaddingLeft {
                inner: PixelValue::const_px(10),
            },
        ))),
        CssPropertyWithConditions::simple(CssProperty::TextAlign(StyleTextAlignValue::Exact(
            StyleTextAlign::Left,
        ))),
    ];
    const CSS_MATCH_1198521124955124418: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_1198521124955124418_PROPERTIES);
    const CSS_MATCH_12038890904436132038_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .node_output_connection_label_wrapper
        CssPropertyWithConditions::simple(CssProperty::BackgroundContent(
            StyleBackgroundContentVecValue::Exact(StyleBackgroundContentVec::from_const_slice(
                STYLE_BACKGROUND_CONTENT_10430246856047584562_ITEMS,
            )),
        )),
        CssPropertyWithConditions::simple(CssProperty::PaddingLeft(LayoutPaddingLeftValue::Exact(
            LayoutPaddingLeft {
                inner: PixelValue::const_px(5),
            },
        ))),
    ];
    const CSS_MATCH_12038890904436132038: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_12038890904436132038_PROPERTIES);
    const CSS_MATCH_12400244273289328300_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .node_output_container
        CssPropertyWithConditions::simple(CssProperty::Display(LayoutDisplayValue::Exact(
            LayoutDisplay::Flex,
        ))),
        CssPropertyWithConditions::simple(CssProperty::FlexDirection(
            LayoutFlexDirectionValue::Exact(LayoutFlexDirection::Row),
        )),
        CssPropertyWithConditions::simple(CssProperty::MarginTop(LayoutMarginTopValue::Exact(
            LayoutMarginTop {
                inner: PixelValue::const_px(10),
            },
        ))),
    ];
    const CSS_MATCH_12400244273289328300: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_12400244273289328300_PROPERTIES);
    const CSS_MATCH_14906563417280941890_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .outputs
        CssPropertyWithConditions::simple(CssProperty::FlexGrow(LayoutFlexGrowValue::Exact(
            LayoutFlexGrow {
                inner: FloatValue::const_new(0),
            },
        ))),
        CssPropertyWithConditions::simple(CssProperty::OverflowX(LayoutOverflowValue::Exact(
            LayoutOverflow::Visible,
        ))),
        CssPropertyWithConditions::simple(CssProperty::OverflowY(LayoutOverflowValue::Exact(
            LayoutOverflow::Visible,
        ))),
        CssPropertyWithConditions::simple(CssProperty::Position(LayoutPositionValue::Exact(
            LayoutPosition::Relative,
        ))),
        CssPropertyWithConditions::simple(CssProperty::Width(LayoutWidthValue::Exact(
            LayoutWidth::Px(PixelValue::const_px(0)),
        ))),
    ];
    const CSS_MATCH_14906563417280941890: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_14906563417280941890_PROPERTIES);
    const CSS_MATCH_16946967739775705757_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .inputs
        CssPropertyWithConditions::simple(CssProperty::FlexGrow(LayoutFlexGrowValue::Exact(
            LayoutFlexGrow {
                inner: FloatValue::const_new(0),
            },
        ))),
        CssPropertyWithConditions::simple(CssProperty::OverflowX(LayoutOverflowValue::Exact(
            LayoutOverflow::Visible,
        ))),
        CssPropertyWithConditions::simple(CssProperty::OverflowY(LayoutOverflowValue::Exact(
            LayoutOverflow::Visible,
        ))),
        CssPropertyWithConditions::simple(CssProperty::Position(LayoutPositionValue::Exact(
            LayoutPosition::Relative,
        ))),
        CssPropertyWithConditions::simple(CssProperty::Width(LayoutWidthValue::Exact(
            LayoutWidth::Px(PixelValue::const_px(0)),
        ))),
    ];
    const CSS_MATCH_16946967739775705757: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_16946967739775705757_PROPERTIES);
    const CSS_MATCH_1739273067404038547_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .node_label
        CssPropertyWithConditions::simple(CssProperty::FontSize(StyleFontSizeValue::Exact(
            StyleFontSize {
                inner: PixelValue::const_px(18),
            },
        ))),
        CssPropertyWithConditions::simple(CssProperty::Height(LayoutHeightValue::Exact(
            LayoutHeight::Px(PixelValue::const_px(50)),
        ))),
        CssPropertyWithConditions::simple(CssProperty::PaddingLeft(LayoutPaddingLeftValue::Exact(
            LayoutPaddingLeft {
                inner: PixelValue::const_px(5),
            },
        ))),
        CssPropertyWithConditions::simple(CssProperty::PaddingTop(LayoutPaddingTopValue::Exact(
            LayoutPaddingTop {
                inner: PixelValue::const_px(10),
            },
        ))),
    ];
    const CSS_MATCH_1739273067404038547: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_1739273067404038547_PROPERTIES);
    const CSS_MATCH_2008162367868363199_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .node_output_connection_label
        CssPropertyWithConditions::simple(CssProperty::FontFamily(StyleFontFamilyVecValue::Exact(
            StyleFontFamilyVec::from_const_slice(STYLE_FONT_FAMILY_8122988506401935406_ITEMS),
        ))),
        CssPropertyWithConditions::simple(CssProperty::FontSize(StyleFontSizeValue::Exact(
            StyleFontSize {
                inner: PixelValue::const_px(12),
            },
        ))),
        CssPropertyWithConditions::simple(CssProperty::Height(LayoutHeightValue::Exact(
            LayoutHeight::Px(PixelValue::const_px(15)),
        ))),
        CssPropertyWithConditions::simple(CssProperty::TextAlign(StyleTextAlignValue::Exact(
            StyleTextAlign::Left,
        ))),
        CssPropertyWithConditions::simple(CssProperty::Width(LayoutWidthValue::Exact(
            LayoutWidth::Px(PixelValue::const_px(100)),
        ))),
    ];
    const CSS_MATCH_2008162367868363199: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_2008162367868363199_PROPERTIES);
    const CSS_MATCH_2639191696846875011_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .node_configuration_field_container
        CssPropertyWithConditions::simple(CssProperty::FlexDirection(
            LayoutFlexDirectionValue::Exact(LayoutFlexDirection::Column),
        )),
        CssPropertyWithConditions::simple(CssProperty::PaddingTop(LayoutPaddingTopValue::Exact(
            LayoutPaddingTop {
                inner: PixelValue::const_px(3),
            },
        ))),
        CssPropertyWithConditions::simple(CssProperty::PaddingBottom(
            LayoutPaddingBottomValue::Exact(LayoutPaddingBottom {
                inner: PixelValue::const_px(3),
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::PaddingLeft(LayoutPaddingLeftValue::Exact(
            LayoutPaddingLeft {
                inner: PixelValue::const_px(5),
            },
        ))),
        CssPropertyWithConditions::simple(CssProperty::PaddingRight(
            LayoutPaddingRightValue::Exact(LayoutPaddingRight {
                inner: PixelValue::const_px(5),
            }),
        )),
    ];
    const CSS_MATCH_2639191696846875011: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_2639191696846875011_PROPERTIES);
    const CSS_MATCH_3354247437065914166_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .node_body
        CssPropertyWithConditions::simple(CssProperty::FlexDirection(
            LayoutFlexDirectionValue::Exact(LayoutFlexDirection::Row),
        )),
        CssPropertyWithConditions::simple(CssProperty::Position(LayoutPositionValue::Exact(
            LayoutPosition::Relative,
        ))),
    ];
    const CSS_MATCH_3354247437065914166: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_3354247437065914166_PROPERTIES);
    const CSS_MATCH_4700400755767504372_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .node_input_connection_label_wrapper
        CssPropertyWithConditions::simple(CssProperty::BackgroundContent(
            StyleBackgroundContentVecValue::Exact(StyleBackgroundContentVec::from_const_slice(
                STYLE_BACKGROUND_CONTENT_11936041127084538304_ITEMS,
            )),
        )),
        CssPropertyWithConditions::simple(CssProperty::PaddingRight(
            LayoutPaddingRightValue::Exact(LayoutPaddingRight {
                inner: PixelValue::const_px(5),
            }),
        )),
    ];
    const CSS_MATCH_4700400755767504372: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_4700400755767504372_PROPERTIES);
    const CSS_MATCH_705881630351954657_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .node_input_wrapper
        CssPropertyWithConditions::simple(CssProperty::Display(LayoutDisplayValue::Exact(
            LayoutDisplay::Flex,
        ))),
        CssPropertyWithConditions::simple(CssProperty::FlexDirection(
            LayoutFlexDirectionValue::Exact(LayoutFlexDirection::Column),
        )),
        CssPropertyWithConditions::simple(CssProperty::OverflowX(LayoutOverflowValue::Exact(
            LayoutOverflow::Visible,
        ))),
        CssPropertyWithConditions::simple(CssProperty::OverflowY(LayoutOverflowValue::Exact(
            LayoutOverflow::Visible,
        ))),
        CssPropertyWithConditions::simple(CssProperty::Position(LayoutPositionValue::Exact(
            LayoutPosition::Absolute,
        ))),
        CssPropertyWithConditions::simple(CssProperty::Right(LayoutRightValue::Exact(
            LayoutRight {
                inner: PixelValue::const_px(0),
            },
        ))),
    ];
    const CSS_MATCH_705881630351954657: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_705881630351954657_PROPERTIES);
    const CSS_MATCH_7395766480280098891_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .node_close_button
        CssPropertyWithConditions::simple(CssProperty::AlignItems(LayoutAlignItemsValue::Exact(
            LayoutAlignItems::Center,
        ))),
        CssPropertyWithConditions::simple(CssProperty::BackgroundContent(
            StyleBackgroundContentVecValue::Exact(StyleBackgroundContentVec::from_const_slice(
                STYLE_BACKGROUND_CONTENT_17648039690071193942_ITEMS,
            )),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderTopColor(
            StyleBorderTopColorValue::Exact(StyleBorderTopColor {
                inner: ColorU {
                    r: 255,
                    g: 255,
                    b: 255,
                    a: 153,
                },
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderRightColor(
            StyleBorderRightColorValue::Exact(StyleBorderRightColor {
                inner: ColorU {
                    r: 255,
                    g: 255,
                    b: 255,
                    a: 153,
                },
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderLeftColor(
            StyleBorderLeftColorValue::Exact(StyleBorderLeftColor {
                inner: ColorU {
                    r: 255,
                    g: 255,
                    b: 255,
                    a: 153,
                },
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderBottomColor(
            StyleBorderBottomColorValue::Exact(StyleBorderBottomColor {
                inner: ColorU {
                    r: 255,
                    g: 255,
                    b: 255,
                    a: 153,
                },
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderTopStyle(
            StyleBorderTopStyleValue::Exact(StyleBorderTopStyle {
                inner: BorderStyle::Solid,
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderRightStyle(
            StyleBorderRightStyleValue::Exact(StyleBorderRightStyle {
                inner: BorderStyle::Solid,
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderLeftStyle(
            StyleBorderLeftStyleValue::Exact(StyleBorderLeftStyle {
                inner: BorderStyle::Solid,
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderBottomStyle(
            StyleBorderBottomStyleValue::Exact(StyleBorderBottomStyle {
                inner: BorderStyle::Solid,
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderTopWidth(
            LayoutBorderTopWidthValue::Exact(LayoutBorderTopWidth {
                inner: PixelValue::const_px(1),
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderRightWidth(
            LayoutBorderRightWidthValue::Exact(LayoutBorderRightWidth {
                inner: PixelValue::const_px(1),
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderLeftWidth(
            LayoutBorderLeftWidthValue::Exact(LayoutBorderLeftWidth {
                inner: PixelValue::const_px(1),
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BorderBottomWidth(
            LayoutBorderBottomWidthValue::Exact(LayoutBorderBottomWidth {
                inner: PixelValue::const_px(1),
            }),
        )),
        CssPropertyWithConditions::simple(CssProperty::BoxShadowLeft(StyleBoxShadowValue::Exact(
            BoxOrStatic::Static(&StyleBoxShadow {
                offset_x: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                offset_y: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                color: ColorU {
                    r: 229,
                    g: 57,
                    b: 53,
                    a: 255,
                },
                blur_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(2),
                },
                spread_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                clip_mode: BoxShadowClipMode::Outset,
            }),
        ))),
        CssPropertyWithConditions::simple(CssProperty::BoxShadowRight(StyleBoxShadowValue::Exact(
            BoxOrStatic::Static(&StyleBoxShadow {
                offset_x: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                offset_y: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                color: ColorU {
                    r: 229,
                    g: 57,
                    b: 53,
                    a: 255,
                },
                blur_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(2),
                },
                spread_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                clip_mode: BoxShadowClipMode::Outset,
            }),
        ))),
        CssPropertyWithConditions::simple(CssProperty::BoxShadowTop(StyleBoxShadowValue::Exact(
            BoxOrStatic::Static(&StyleBoxShadow {
                offset_x: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                offset_y: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                color: ColorU {
                    r: 229,
                    g: 57,
                    b: 53,
                    a: 255,
                },
                blur_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(2),
                },
                spread_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                clip_mode: BoxShadowClipMode::Outset,
            }),
        ))),
        CssPropertyWithConditions::simple(CssProperty::BoxShadowBottom(
            StyleBoxShadowValue::Exact(BoxOrStatic::Static(&StyleBoxShadow {
                offset_x: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                offset_y: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                color: ColorU {
                    r: 229,
                    g: 57,
                    b: 53,
                    a: 255,
                },
                blur_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(2),
                },
                spread_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                clip_mode: BoxShadowClipMode::Outset,
            })),
        )),
        CssPropertyWithConditions::simple(CssProperty::Cursor(StyleCursorValue::Exact(
            StyleCursor::Pointer,
        ))),
        CssPropertyWithConditions::simple(CssProperty::FontFamily(StyleFontFamilyVecValue::Exact(
            StyleFontFamilyVec::from_const_slice(STYLE_FONT_FAMILY_11383897783350685780_ITEMS),
        ))),
        CssPropertyWithConditions::simple(CssProperty::Height(LayoutHeightValue::Exact(
            LayoutHeight::Px(PixelValue::const_px(20)),
        ))),
        CssPropertyWithConditions::simple(CssProperty::Position(LayoutPositionValue::Exact(
            LayoutPosition::Absolute,
        ))),
        CssPropertyWithConditions::simple(CssProperty::TextAlign(StyleTextAlignValue::Exact(
            StyleTextAlign::Center,
        ))),
        CssPropertyWithConditions::simple(CssProperty::Transform(StyleTransformVecValue::Exact(
            StyleTransformVec::from_const_slice(STYLE_TRANSFORM_14683950870521466298_ITEMS),
        ))),
        CssPropertyWithConditions::simple(CssProperty::Width(LayoutWidthValue::Exact(
            LayoutWidth::Px(PixelValue::const_px(20)),
        ))),
    ];
    const CSS_MATCH_7395766480280098891: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_7395766480280098891_PROPERTIES);
    const CSS_MATCH_7432473243011547380_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .node_content_wrapper
        CssPropertyWithConditions::simple(CssProperty::BackgroundContent(
            StyleBackgroundContentVecValue::Exact(StyleBackgroundContentVec::from_const_slice(
                STYLE_BACKGROUND_CONTENT_15813232491335471489_ITEMS,
            )),
        )),
        CssPropertyWithConditions::simple(CssProperty::BoxShadowLeft(StyleBoxShadowValue::Exact(
            BoxOrStatic::Static(&StyleBoxShadow {
                offset_x: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                offset_y: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                color: ColorU {
                    r: 0,
                    g: 0,
                    b: 0,
                    a: 255,
                },
                blur_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(4),
                },
                spread_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                clip_mode: BoxShadowClipMode::Inset,
            }),
        ))),
        CssPropertyWithConditions::simple(CssProperty::BoxShadowRight(StyleBoxShadowValue::Exact(
            BoxOrStatic::Static(&StyleBoxShadow {
                offset_x: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                offset_y: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                color: ColorU {
                    r: 0,
                    g: 0,
                    b: 0,
                    a: 255,
                },
                blur_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(4),
                },
                spread_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                clip_mode: BoxShadowClipMode::Inset,
            }),
        ))),
        CssPropertyWithConditions::simple(CssProperty::BoxShadowTop(StyleBoxShadowValue::Exact(
            BoxOrStatic::Static(&StyleBoxShadow {
                offset_x: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                offset_y: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                color: ColorU {
                    r: 0,
                    g: 0,
                    b: 0,
                    a: 255,
                },
                blur_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(4),
                },
                spread_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                clip_mode: BoxShadowClipMode::Inset,
            }),
        ))),
        CssPropertyWithConditions::simple(CssProperty::BoxShadowBottom(
            StyleBoxShadowValue::Exact(BoxOrStatic::Static(&StyleBoxShadow {
                offset_x: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                offset_y: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                color: ColorU {
                    r: 0,
                    g: 0,
                    b: 0,
                    a: 255,
                },
                blur_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(4),
                },
                spread_radius: PixelValueNoPercent {
                    inner: PixelValue::const_px(0),
                },
                clip_mode: BoxShadowClipMode::Inset,
            })),
        )),
        CssPropertyWithConditions::simple(CssProperty::FlexGrow(LayoutFlexGrowValue::Exact(
            LayoutFlexGrow {
                inner: FloatValue::const_new(1),
            },
        ))),
    ];
    const CSS_MATCH_7432473243011547380: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_7432473243011547380_PROPERTIES);
    const CSS_MATCH_9863994880298313101_PROPERTIES: &[CssPropertyWithConditions] = &[
        // .node_input_container
        CssPropertyWithConditions::simple(CssProperty::Display(LayoutDisplayValue::Exact(
            LayoutDisplay::Flex,
        ))),
        CssPropertyWithConditions::simple(CssProperty::FlexDirection(
            LayoutFlexDirectionValue::Exact(LayoutFlexDirection::Row),
        )),
        CssPropertyWithConditions::simple(CssProperty::MarginTop(LayoutMarginTopValue::Exact(
            LayoutMarginTop {
                inner: PixelValue::const_px(10),
            },
        ))),
    ];
    const CSS_MATCH_9863994880298313101: CssPropertyWithConditionsVec =
        CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_9863994880298313101_PROPERTIES);
    // NODE RENDER FUNCTION BEGIN
83
    let node_transform = StyleTransformTranslate2D {
83
        x: PixelValue::px(graph_offset.0 + node.position.x),
83
        y: PixelValue::px(graph_offset.1 + node.position.y),
83
    };
    // get names and colors for inputs / outputs
83
    let inputs = node_info
83
        .inputs
83
        .iter()
83
        .filter_map(|io_id| {
83
            let node_graph_ref = node_local_dataset
83
                .backref
83
                .downcast_ref::<NodeGraphLocalDataset>()?;
82
            let io_info = node_graph_ref
82
                .node_graph
82
                .input_output_types
82
                .iter()
95
                .find(|i| i.io_type_id == *io_id)?;
81
            Some((io_info.io_info.data_type.clone(), io_info.io_info.color))
83
        })
83
        .collect::<Vec<_>>();
83
    let outputs = node_info
83
        .outputs
83
        .iter()
83
        .filter_map(|io_id| {
83
            let node_graph_ref = node_local_dataset
83
                .backref
83
                .downcast_ref::<NodeGraphLocalDataset>()?;
82
            let io_info = node_graph_ref
82
                .node_graph
82
                .input_output_types
82
                .iter()
94
                .find(|i| i.io_type_id == *io_id)?;
82
            Some((io_info.io_info.data_type.clone(), io_info.io_info.color))
83
        })
83
        .collect::<Vec<_>>();
83
    let node_local_dataset = RefAny::new(node_local_dataset);
83
    Dom::create_div()
83
    .with_css_props(vec![
83
        CssPropertyWithConditions::simple(CssProperty::Position(LayoutPositionValue::Exact(
83
            LayoutPosition::Absolute,
83
        ))),
83
    ].into())
83
    .with_children(vec![
83
        Dom::create_div()
83
        .with_callbacks(vec![
83
           CoreCallbackData {
83
               event: EventFilter::Hover(HoverEventFilter::LeftMouseDown),
83
               refany: node_local_dataset.clone(),
83
               callback: CoreCallback { cb: nodegraph_set_active_node as usize, ctx: OptionRefAny::None },
83
           },
83
        ].into())
83
        .with_css_props(vec![
           // .node_graph_node
83
           CssPropertyWithConditions::simple(CssProperty::OverflowX(
83
               LayoutOverflowValue::Exact(LayoutOverflow::Visible)
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::Position(LayoutPositionValue::Exact(
83
               LayoutPosition::Relative,
83
           ))),
83
           CssPropertyWithConditions::simple(CssProperty::OverflowY(
83
               LayoutOverflowValue::Exact(LayoutOverflow::Visible)
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::BackgroundContent(
83
               StyleBackgroundContentVecValue::Exact(StyleBackgroundContentVec::from_const_slice(
83
                   STYLE_BACKGROUND_CONTENT_11535310356736632656_ITEMS,
83
               )),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::BorderTopColor(
83
               StyleBorderTopColorValue::Exact(StyleBorderTopColor {
83
                   inner: ColorU {
83
                       r: 0,
83
                       g: 180,
83
                       b: 219,
83
                       a: 255,
83
                   },
83
               }),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::BorderRightColor(
83
               StyleBorderRightColorValue::Exact(StyleBorderRightColor {
83
                   inner: ColorU {
83
                       r: 0,
83
                       g: 180,
83
                       b: 219,
83
                       a: 255,
83
                   },
83
               }),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::BorderLeftColor(
83
               StyleBorderLeftColorValue::Exact(StyleBorderLeftColor {
83
                   inner: ColorU {
83
                       r: 0,
83
                       g: 180,
83
                       b: 219,
83
                       a: 255,
83
                   },
83
               }),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::BorderBottomColor(
83
               StyleBorderBottomColorValue::Exact(StyleBorderBottomColor {
83
                   inner: ColorU {
83
                       r: 0,
83
                       g: 180,
83
                       b: 219,
83
                       a: 255,
83
                   },
83
               }),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::BorderTopStyle(
83
               StyleBorderTopStyleValue::Exact(StyleBorderTopStyle {
83
                   inner: BorderStyle::Solid,
83
               }),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::BorderRightStyle(
83
               StyleBorderRightStyleValue::Exact(StyleBorderRightStyle {
83
                   inner: BorderStyle::Solid,
83
               }),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::BorderLeftStyle(
83
               StyleBorderLeftStyleValue::Exact(StyleBorderLeftStyle {
83
                   inner: BorderStyle::Solid,
83
               }),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::BorderBottomStyle(
83
               StyleBorderBottomStyleValue::Exact(StyleBorderBottomStyle {
83
                   inner: BorderStyle::Solid,
83
               }),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::BorderTopWidth(
83
               LayoutBorderTopWidthValue::Exact(LayoutBorderTopWidth {
83
                   inner: PixelValue::const_px(1),
83
               }),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::BorderRightWidth(
83
               LayoutBorderRightWidthValue::Exact(LayoutBorderRightWidth {
83
                   inner: PixelValue::const_px(1),
83
               }),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::BorderLeftWidth(
83
               LayoutBorderLeftWidthValue::Exact(LayoutBorderLeftWidth {
83
                   inner: PixelValue::const_px(1),
83
               }),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::BorderBottomWidth(
83
               LayoutBorderBottomWidthValue::Exact(LayoutBorderBottomWidth {
83
                   inner: PixelValue::const_px(1),
83
               }),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::BoxShadowLeft(StyleBoxShadowValue::Exact(BoxOrStatic::heap(
83
               StyleBoxShadow {
83
                   offset_x: PixelValueNoPercent { inner: PixelValue::const_px(0) }, offset_y: PixelValueNoPercent { inner: PixelValue::const_px(0) },
83
                   color: ColorU {
83
                       r: 0,
83
                       g: 131,
83
                       b: 176,
83
                       a: 119,
83
                   },
83
                   blur_radius: PixelValueNoPercent {
83
                       inner: PixelValue::const_px(3),
83
                   },
83
                   spread_radius: PixelValueNoPercent {
83
                       inner: PixelValue::const_px(0),
83
                   },
83
                   clip_mode: BoxShadowClipMode::Outset,
83
               },
83
           )))),
83
           CssPropertyWithConditions::simple(CssProperty::BoxShadowRight(StyleBoxShadowValue::Exact(BoxOrStatic::heap(
83
               StyleBoxShadow {
83
                   offset_x: PixelValueNoPercent { inner: PixelValue::const_px(0) }, offset_y: PixelValueNoPercent { inner: PixelValue::const_px(0) },
83
                   color: ColorU {
83
                       r: 0,
83
                       g: 131,
83
                       b: 176,
83
                       a: 119,
83
                   },
83
                   blur_radius: PixelValueNoPercent {
83
                       inner: PixelValue::const_px(3),
83
                   },
83
                   spread_radius: PixelValueNoPercent {
83
                       inner: PixelValue::const_px(0),
83
                   },
83
                   clip_mode: BoxShadowClipMode::Outset,
83
               },
83
           )))),
83
           CssPropertyWithConditions::simple(CssProperty::BoxShadowTop(StyleBoxShadowValue::Exact(BoxOrStatic::heap(
83
               StyleBoxShadow {
83
                   offset_x: PixelValueNoPercent { inner: PixelValue::const_px(0) }, offset_y: PixelValueNoPercent { inner: PixelValue::const_px(0) },
83
                   color: ColorU {
83
                       r: 0,
83
                       g: 131,
83
                       b: 176,
83
                       a: 119,
83
                   },
83
                   blur_radius: PixelValueNoPercent {
83
                       inner: PixelValue::const_px(3),
83
                   },
83
                   spread_radius: PixelValueNoPercent {
83
                       inner: PixelValue::const_px(0),
83
                   },
83
                   clip_mode: BoxShadowClipMode::Outset,
83
               },
83
           )))),
83
           CssPropertyWithConditions::simple(CssProperty::BoxShadowBottom(
83
               StyleBoxShadowValue::Exact(BoxOrStatic::heap(StyleBoxShadow {
83
                   offset_x: PixelValueNoPercent { inner: PixelValue::const_px(0) }, offset_y: PixelValueNoPercent { inner: PixelValue::const_px(0) },
83
                   color: ColorU {
83
                       r: 0,
83
                       g: 131,
83
                       b: 176,
83
                       a: 119,
83
                   },
83
                   blur_radius: PixelValueNoPercent {
83
                       inner: PixelValue::const_px(3),
83
                   },
83
                   spread_radius: PixelValueNoPercent {
83
                       inner: PixelValue::const_px(0),
83
                   },
83
                   clip_mode: BoxShadowClipMode::Outset,
83
               })),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::TextColor(StyleTextColorValue::Exact(
83
               StyleTextColor {
83
                   inner: ColorU {
83
                       r: 255,
83
                       g: 255,
83
                       b: 255,
83
                       a: 255,
83
                   },
83
               },
83
           ))),
83
           CssPropertyWithConditions::simple(CssProperty::Display(LayoutDisplayValue::Exact(
83
               LayoutDisplay::Block
83
           ))),
83
           CssPropertyWithConditions::simple(CssProperty::FontFamily(StyleFontFamilyVecValue::Exact(
83
               StyleFontFamilyVec::from_const_slice(STYLE_FONT_FAMILY_8122988506401935406_ITEMS),
83
           ))),
83
           CssPropertyWithConditions::simple(CssProperty::PaddingTop(LayoutPaddingTopValue::Exact(
83
               LayoutPaddingTop {
83
                   inner: PixelValue::const_px(10),
83
               },
83
           ))),
83
           CssPropertyWithConditions::simple(CssProperty::PaddingBottom(
83
               LayoutPaddingBottomValue::Exact(LayoutPaddingBottom {
83
                   inner: PixelValue::const_px(10),
83
               }),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::PaddingLeft(LayoutPaddingLeftValue::Exact(
83
               LayoutPaddingLeft {
83
                   inner: PixelValue::const_px(10),
83
               },
83
           ))),
83
           CssPropertyWithConditions::simple(CssProperty::PaddingRight(
83
               LayoutPaddingRightValue::Exact(LayoutPaddingRight {
83
                   inner: PixelValue::const_px(10),
83
               }),
83
           )),
83
           CssPropertyWithConditions::simple(CssProperty::Transform(StyleTransformVecValue::Exact(
83
               if scale_factor == 1.0 {
48
                    vec![
48
                         StyleTransform::Translate(node_transform)
                    ]
               } else {
35
                    vec![
35
                         StyleTransform::Translate(node_transform),
35
                         StyleTransform::ScaleX(PercentageValue::new(scale_factor * 100.0)),
35
                         StyleTransform::ScaleY(PercentageValue::new(scale_factor * 100.0)),
                    ]
83
               }.into()
           ))),
83
           CssPropertyWithConditions::simple(CssProperty::Width(LayoutWidthValue::Exact(
83
               LayoutWidth::Px(PixelValue::const_px(250),),
83
           ))),
83
        ].into())
83
        .with_ids_and_classes({
           const IDS_AND_CLASSES_4480169002427296613: &[IdOrClass] =
               &[Class(AzString::from_const_str("node_graph_node"))];
83
           IdOrClassVec::from_const_slice(IDS_AND_CLASSES_4480169002427296613)
        })
83
        .with_children(DomVec::from_vec(vec![
83
           crate::widgets::widget_p_with_text(AzString::from_const_str("X"))
83
               .with_css_props(CSS_MATCH_7395766480280098891)
83
               .with_callbacks(vec![
83
                   CoreCallbackData {
83
                       event: EventFilter::Hover(HoverEventFilter::Click),
83
                       refany: node_local_dataset.clone(),
83
                       callback: CoreCallback { cb: nodegraph_delete_node as usize, ctx: OptionRefAny::None },
83
                   },
83
               ].into())
83
               .with_ids_and_classes({
                   const IDS_AND_CLASSES_7122017923389407516: &[IdOrClass] =
                       &[Class(AzString::from_const_str("node_close_button"))];
83
                   IdOrClassVec::from_const_slice(IDS_AND_CLASSES_7122017923389407516)
               }),
83
           crate::widgets::widget_p_with_text(node_info.node_type_name.clone())
83
               .with_css_props(CSS_MATCH_1739273067404038547)
83
               .with_ids_and_classes({
                   const IDS_AND_CLASSES_15777790571346582635: &[IdOrClass] =
                       &[Class(AzString::from_const_str("node_label"))];
83
                   IdOrClassVec::from_const_slice(IDS_AND_CLASSES_15777790571346582635)
               }),
83
           Dom::create_div()
83
               .with_css_props(CSS_MATCH_3354247437065914166)
83
               .with_ids_and_classes({
                   const IDS_AND_CLASSES_5590500152394859708: &[IdOrClass] =
                       &[Class(AzString::from_const_str("node_body"))];
83
                   IdOrClassVec::from_const_slice(IDS_AND_CLASSES_5590500152394859708)
               })
83
               .with_children(DomVec::from_vec(vec![
83
                   Dom::create_div()
83
                       .with_css_props(CSS_MATCH_16946967739775705757)
83
                       .with_ids_and_classes({
                           const IDS_AND_CLASSES_3626404106673061698: &[IdOrClass] =
                               &[Class(AzString::from_const_str("inputs"))];
83
                           IdOrClassVec::from_const_slice(IDS_AND_CLASSES_3626404106673061698)
                       })
83
                       .with_children(DomVec::from_vec(vec![Dom::create_div()
83
                           .with_css_props(CSS_MATCH_705881630351954657)
83
                           .with_ids_and_classes({
                               const IDS_AND_CLASSES_12825690349660780627: &[IdOrClass] =
                                   &[Class(AzString::from_const_str("node_input_wrapper"))];
83
                               IdOrClassVec::from_const_slice(
                                   IDS_AND_CLASSES_12825690349660780627,
                               )
                           })
83
                           .with_children(DomVec::from_vec(
83
                               inputs
83
                               .into_iter()
83
                               .enumerate()
83
                               .map(|(io_id, (input_label, input_color))| {
                                   use self::InputOrOutput::Input;
81
                                   Dom::create_div()
81
                                       .with_css_props(CSS_MATCH_9863994880298313101)
81
                                       .with_ids_and_classes({
                                           const IDS_AND_CLASSES_5020681879750641508:
                                               &[IdOrClass] = &[Class(AzString::from_const_str(
                                               "node_input_container",
                                           ))];
81
                                           IdOrClassVec::from_const_slice(
                                               IDS_AND_CLASSES_5020681879750641508,
                                           )
                                       })
81
                                       .with_children(DomVec::from_vec(vec![
81
                                           Dom::create_div()
81
                                               .with_css_props(
81
                                                   CSS_MATCH_4700400755767504372,
                                               )
81
                                               .with_ids_and_classes({
                                                   const IDS_AND_CLASSES_9154857442066749879:
                                                       &[IdOrClass] =
                                                       &[Class(AzString::from_const_str(
                                                           "node_input_connection_label_wrapper",
                                                       ))];
81
                                                   IdOrClassVec::from_const_slice(
                                                       IDS_AND_CLASSES_9154857442066749879,
                                                   )
                                               })
81
                                               .with_children(DomVec::from_vec(vec![crate::widgets::widget_p_with_text(
81
                                                   input_label,
                                               )
81
                                               .with_css_props(
81
                                                   CSS_MATCH_11452431279102104133,
                                               )
81
                                               .with_ids_and_classes({
                                                   const IDS_AND_CLASSES_16291496011772407931:
                                                       &[IdOrClass] =
                                                       &[Class(AzString::from_const_str(
                                                           "node_input_connection_label",
                                                       ))];
81
                                                   IdOrClassVec::from_const_slice(
                                                       IDS_AND_CLASSES_16291496011772407931,
                                                   )
                                               })])),
81
                                           Dom::create_div()
81
                                               .with_callbacks(vec![
81
                                                   CoreCallbackData {
81
                                                       event: EventFilter::Hover(HoverEventFilter::LeftMouseUp),
81
                                                       refany: RefAny::new(NodeInputOutputLocalDataset {
81
                                                           io_id: Input(io_id),
81
                                                           backref: node_local_dataset.clone(),
81
                                                       }),
81
                                                       callback: CoreCallback { cb: nodegraph_input_output_connect as usize, ctx: OptionRefAny::None },
81
                                                   },
81
                                                   CoreCallbackData {
81
                                                       event: EventFilter::Hover(HoverEventFilter::MiddleMouseUp),
81
                                                       refany: RefAny::new(NodeInputOutputLocalDataset {
81
                                                           io_id: Input(io_id),
81
                                                           backref: node_local_dataset.clone(),
81
                                                       }),
81
                                                       callback: CoreCallback { cb: nodegraph_input_output_disconnect as usize, ctx: OptionRefAny::None },
81
                                                   },
81
                                               ].into())
81
                                               .with_css_props(CssPropertyWithConditionsVec::from_vec(vec![
                                                       // .node_input
81
                                                       CssPropertyWithConditions::simple(CssProperty::BackgroundContent(
81
                                                           StyleBackgroundContentVecValue::Exact(vec![StyleBackgroundContent::Color(input_color)].into()),
81
                                                       )),
81
                                                       CssPropertyWithConditions::simple(CssProperty::Cursor(StyleCursorValue::Exact(
81
                                                           StyleCursor::Pointer,
81
                                                       ))),
81
                                                       CssPropertyWithConditions::simple(CssProperty::Height(LayoutHeightValue::Exact(
81
                                                           LayoutHeight::Px(PixelValue::const_px(15),),
81
                                                       ))),
81
                                                       CssPropertyWithConditions::simple(CssProperty::Width(LayoutWidthValue::Exact(
81
                                                           LayoutWidth::Px(PixelValue::const_px(15),),
81
                                                       ))),
                                                   ])
                                               )
81
                                               .with_ids_and_classes({
                                                   const IDS_AND_CLASSES_2128818677168244823:
                                                       &[IdOrClass] = &[Class(
                                                       AzString::from_const_str("node_input"),
                                                   )];
81
                                                   IdOrClassVec::from_const_slice(
                                                       IDS_AND_CLASSES_2128818677168244823,
                                                   )
                                               }),
                                       ]))
83
                               }).collect()
                           ))
                       ])),
83
                   Dom::create_div()
83
                       .with_css_props(CSS_MATCH_7432473243011547380)
83
                       .with_ids_and_classes({
                           const IDS_AND_CLASSES_746059979773622802: &[IdOrClass] =
                               &[Class(AzString::from_const_str("node_content_wrapper"))];
83
                           IdOrClassVec::from_const_slice(IDS_AND_CLASSES_746059979773622802)
                       })
83
                       .with_children({
83
                           let mut fields = Vec::new();
83
                           for (field_idx, field) in node.fields.iter().enumerate() {
28
                               let field_local_dataset = RefAny::new(NodeFieldLocalDataset {
28
                                   field_idx,
28
                                   backref: node_local_dataset.clone(),
28
                               });
28
                               let div = Dom::create_div()
28
                               .with_css_props(CSS_MATCH_2639191696846875011)
28
                               .with_ids_and_classes({
                                   const IDS_AND_CLASSES_4413230059125905311: &[IdOrClass] =
                                       &[Class(AzString::from_const_str(
                                           "node_configuration_field_container",
                                       ))];
28
                                   IdOrClassVec::from_const_slice(
                                       IDS_AND_CLASSES_4413230059125905311,
                                   )
                               })
28
                               .with_children(DomVec::from_vec(vec![
28
                                   crate::widgets::widget_p_with_text(field.key.clone())
28
                                   .with_css_props(CSS_MATCH_1198521124955124418)
28
                                   .with_ids_and_classes({
                                       const IDS_AND_CLASSES_12334207996395559585:
                                           &[IdOrClass] =
                                           &[Class(AzString::from_const_str(
                                               "node_configuration_field_label",
                                           ))];
28
                                       IdOrClassVec::from_const_slice(
                                           IDS_AND_CLASSES_12334207996395559585,
                                       )
                                   }),
28
                                   match &field.value {
3
                                       NodeTypeFieldValue::TextInput(initial_text) => {
3
                                           let cb: TextInputOnFocusLostCallbackType = nodegraph_on_textinput_focus_lost;
3
                                           TextInput::create()
3
                                           .with_text(initial_text.clone())
3
                                           .with_on_focus_lost(field_local_dataset, cb)
3
                                           .dom()
                                       },
5
                                       NodeTypeFieldValue::NumberInput(initial_value) => {
5
                                           let cb: NumberInputOnFocusLostCallbackType = nodegraph_on_numberinput_focus_lost;
5
                                           NumberInput::create(*initial_value)
5
                                           .with_on_focus_lost(field_local_dataset, cb)
5
                                           .dom()
                                       },
16
                                       NodeTypeFieldValue::CheckBox(initial_checked) => {
16
                                           let cb: CheckBoxOnToggleCallbackType = nodegraph_on_checkbox_value_changed;
16
                                           CheckBox::create(*initial_checked)
16
                                           .with_on_toggle(field_local_dataset, cb)
16
                                           .dom()
                                       },
2
                                       NodeTypeFieldValue::ColorInput(initial_color) => {
2
                                           let cb: ColorInputOnValueChangeCallbackType = nodegraph_on_colorinput_value_changed;
2
                                           ColorInput::create(*initial_color)
2
                                           .with_on_value_change(field_local_dataset, cb)
2
                                           .dom()
                                       },
2
                                       NodeTypeFieldValue::FileInput(file_path) => {
2
                                           let cb: FileInputOnPathChangeCallbackType = nodegraph_on_fileinput_button_clicked;
2
                                           FileInput::create(file_path.clone())
2
                                           .with_on_path_change(field_local_dataset, cb)
2
                                           .dom()
                                       },
                                   }
                               ]));
28
                               fields.push(div);
                           }
83
                           DomVec::from_vec(fields)
                       }),
83
                   Dom::create_div()
83
                       .with_css_props(CSS_MATCH_14906563417280941890)
83
                       .with_ids_and_classes({
                           const IDS_AND_CLASSES_4737474624251936466: &[IdOrClass] =
                               &[Class(AzString::from_const_str("outputs"))];
83
                           IdOrClassVec::from_const_slice(IDS_AND_CLASSES_4737474624251936466)
                       })
83
                       .with_children(DomVec::from_vec(vec![Dom::create_div()
83
                           .with_css_props(CSS_MATCH_10339190304804100510)
83
                           .with_ids_and_classes({
                               const IDS_AND_CLASSES_12883576328110161157: &[IdOrClass] =
                                   &[Class(AzString::from_const_str("node_output_wrapper"))];
83
                               IdOrClassVec::from_const_slice(
                                   IDS_AND_CLASSES_12883576328110161157,
                               )
                           })
83
                           .with_children(DomVec::from_vec(
83
                               outputs
83
                               .into_iter()
83
                               .enumerate()
83
                               .map(|(io_id, (output_label, output_color))| {
                                   use self::InputOrOutput::Output;
82
                                   Dom::create_div()
82
                                       .with_css_props(CSS_MATCH_12400244273289328300)
82
                                       .with_ids_and_classes({
                                           const IDS_AND_CLASSES_10917819668096233812:
                                               &[IdOrClass] = &[Class(AzString::from_const_str(
                                               "node_output_container",
                                           ))];
82
                                           IdOrClassVec::from_const_slice(
                                               IDS_AND_CLASSES_10917819668096233812,
                                           )
                                       })
82
                                       .with_children(DomVec::from_vec(vec![
82
                                           Dom::create_div()
82
                                               .with_callbacks(vec![
82
                                                   CoreCallbackData {
82
                                                       event: EventFilter::Hover(HoverEventFilter::LeftMouseUp),
82
                                                       refany: RefAny::new(NodeInputOutputLocalDataset {
82
                                                           io_id: Output(io_id),
82
                                                           backref: node_local_dataset.clone(),
82
                                                       }),
82
                                                       callback: CoreCallback { cb: nodegraph_input_output_connect as usize, ctx: OptionRefAny::None },
82
                                                   },
82
                                                   CoreCallbackData {
82
                                                       event: EventFilter::Hover(HoverEventFilter::MiddleMouseUp),
82
                                                       refany: RefAny::new(NodeInputOutputLocalDataset {
82
                                                           io_id: Output(io_id),
82
                                                           backref: node_local_dataset.clone(),
82
                                                       }),
82
                                                       callback: CoreCallback { cb: nodegraph_input_output_disconnect as usize, ctx: OptionRefAny::None },
82
                                                   },
82
                                               ].into())
82
                                               .with_css_props(
82
                                                   CssPropertyWithConditionsVec::from_vec(vec![
                                                       // .node_output
82
                                                       CssPropertyWithConditions::simple(CssProperty::BackgroundContent(
82
                                                           StyleBackgroundContentVecValue::Exact(vec![
82
                                                               StyleBackgroundContent::Color(output_color)
82
                                                           ].into()),
82
                                                       )),
82
                                                       CssPropertyWithConditions::simple(CssProperty::Cursor(StyleCursorValue::Exact(
82
                                                           StyleCursor::Pointer,
82
                                                       ))),
82
                                                       CssPropertyWithConditions::simple(CssProperty::Height(LayoutHeightValue::Exact(
82
                                                           LayoutHeight::Px(PixelValue::const_px(15),),
82
                                                       ))),
82
                                                       CssPropertyWithConditions::simple(CssProperty::Width(LayoutWidthValue::Exact(
82
                                                           LayoutWidth::Px(PixelValue::const_px(15),),
82
                                                       ))),
                                                   ])
                                               )
82
                                               .with_ids_and_classes({
                                                   const IDS_AND_CLASSES_17632471664405317563:
                                                       &[IdOrClass] = &[Class(
                                                       AzString::from_const_str("node_output"),
                                                   )];
82
                                                   IdOrClassVec::from_const_slice(
                                                       IDS_AND_CLASSES_17632471664405317563,
                                                   )
                                               }),
82
                                           Dom::create_div()
82
                                               .with_css_props(
82
                                                   CSS_MATCH_12038890904436132038,
                                               )
82
                                               .with_ids_and_classes({
                                                   const IDS_AND_CLASSES_1667960214206134147:
                                                       &[IdOrClass] =
                                                       &[Class(AzString::from_const_str(
                                                           "node_output_connection_label_wrapper",
                                                       ))];
82
                                                   IdOrClassVec::from_const_slice(
                                                       IDS_AND_CLASSES_1667960214206134147,
                                                   )
                                               })
82
                                               .with_children(DomVec::from_vec(vec![crate::widgets::widget_p_with_text(
82
                                                   output_label,
                                               )
82
                                               .with_css_props(
82
                                                   CSS_MATCH_2008162367868363199,
                                               )
82
                                               .with_ids_and_classes({
                                                   const IDS_AND_CLASSES_2974914452796301884:
                                                       &[IdOrClass] =
                                                       &[Class(AzString::from_const_str(
                                                           "node_output_connection_label",
                                                       ))];
82
                                                   IdOrClassVec::from_const_slice(
                                                       IDS_AND_CLASSES_2974914452796301884,
                                                   )
                                               })])),
                                       ]))
83
                               }).collect()
                           ))])),
               ])),
        ]))
83
        .with_dataset(Some(node_local_dataset).into())
        // Resolvable from the drag callback via `node_marker(prefix, id)` —
        // the fast-path jump that positions this node without a relayout.
83
        .with_marker(Some(visual_marker).into())
83
    ].into())
83
}
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine
                                 // (one branch per case)
31
fn render_connections(node_graph: &NodeGraph, connections_marker: AzString) -> Dom {
    static NODEGRAPH_CONNECTIONS_CONTAINER_CLASS: &[IdOrClass] = &[Class(
        AzString::from_const_str("nodegraph-connections-container"),
    )];
    static NODEGRAPH_CONNECTIONS_CONTAINER_PROPS: &[CssPropertyWithConditions] = &[
        CssPropertyWithConditions::simple(CssProperty::position(LayoutPosition::Absolute)),
        CssPropertyWithConditions::simple(CssProperty::flex_grow(LayoutFlexGrow::const_new(1))),
    ];
31
    Dom::create_div()
31
        .with_ids_and_classes(IdOrClassVec::from_const_slice(
31
            NODEGRAPH_CONNECTIONS_CONTAINER_CLASS,
        ))
31
        .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
31
            NODEGRAPH_CONNECTIONS_CONTAINER_PROPS,
        ))
31
        .with_marker(Some(connections_marker).into())
31
        .with_children({
31
            let mut children = Vec::new();
107
            for NodeIdNodeMap { node_id, node } in node_graph.nodes.as_ref() {
107
                let out_node_id = node_id;
107
                let node_type_info = match node_graph
107
                    .node_types
107
                    .iter()
129
                    .find(|i| i.node_type_id == node.node_type)
                {
101
                    Some(s) => &s.node_type_info,
6
                    None => continue,
                };
                for OutputConnection {
18
                    output_index,
18
                    connects_to,
101
                } in node.connect_out.as_ref()
                {
18
                    let Some(output_type_id) = node_type_info.outputs.get(*output_index) else {
3
                        continue;
                    };
15
                    let output_color = match node_graph
15
                        .input_output_types
15
                        .iter()
16
                        .find(|o| o.io_type_id == *output_type_id)
                    {
14
                        Some(s) => s.io_info.color,
1
                        None => continue,
                    };
                    for InputNodeAndIndex {
16
                        node_id,
16
                        input_index,
14
                    } in connects_to.as_ref()
                    {
16
                        let in_node_id = node_id;
16
                        let mut cld = ConnectionLocalDataset {
16
                            out_node_id: *out_node_id,
16
                            out_idx: *output_index,
16
                            in_node_id: *in_node_id,
16
                            in_idx: *input_index,
16
                            swap_vert: false,
16
                            swap_horz: false,
16
                            color: output_color,
16
                        };
16
                        let Some((rect, swap_vert, swap_horz)) = get_rect(node_graph, cld) else {
1
                            continue;
                        };
15
                        cld.swap_vert = swap_vert;
15
                        cld.swap_horz = swap_horz;
15
                        let cld_refany = RefAny::new(cld);
15
                        let connection_div = Dom::create_image(ImageRef::callback(
15
                            draw_connection as usize,
15
                            cld_refany.clone(),
                        ))
15
                        .with_dataset(Some(cld_refany).into())
15
                        .with_css_props(
15
                            vec![
15
                                CssPropertyWithConditions::simple(CssProperty::Transform(
15
                                    StyleTransformVecValue::Exact(
15
                                        vec![
15
                                            StyleTransform::Translate(StyleTransformTranslate2D {
15
                                                x: PixelValue::px(
15
                                                    node_graph.offset.x + rect.origin.x,
15
                                                ),
15
                                                y: PixelValue::px(
15
                                                    node_graph.offset.y + rect.origin.y,
15
                                                ),
15
                                            }),
15
                                            StyleTransform::ScaleX(PercentageValue::new(
15
                                                node_graph.scale_factor * 100.0,
15
                                            )),
15
                                            StyleTransform::ScaleY(PercentageValue::new(
15
                                                node_graph.scale_factor * 100.0,
15
                                            )),
15
                                        ]
15
                                        .into(),
15
                                    ),
15
                                )),
15
                                CssPropertyWithConditions::simple(CssProperty::Width(
15
                                    LayoutWidthValue::Exact(LayoutWidth::Px(PixelValue::px(
15
                                        rect.size.width,
15
                                    ))),
15
                                )),
15
                                CssPropertyWithConditions::simple(CssProperty::Height(
15
                                    LayoutHeightValue::Exact(LayoutHeight::Px(PixelValue::px(
15
                                        rect.size.height,
15
                                    ))),
15
                                )),
                            ]
15
                            .into(),
                        );
15
                        children.push(
15
                            Dom::create_div()
15
                                .with_css("flex-grow: 1; position: absolute; overflow: hidden;")
15
                                .with_children(vec![connection_div].into()),
                        );
                    }
                }
            }
31
            children.into()
        })
31
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // bounded layout/render numeric
                                                                   // cast
8
extern "C" fn draw_connection(mut refany: RefAny, _info: ()) -> ImageRef {
    // RenderImageCallbackInfo not available in memtest
    // let size = info.get_bounds().get_physical_size();
8
    let size = LogicalSize {
8
        width: 100.0,
8
        height: 100.0,
8
    };
    // Cannot call draw_connection_inner without RenderImageCallbackInfo
8
    ImageRef::null_image(
8
        size.width as usize,
8
        size.height as usize,
8
        RawImageFormat::R8,
8
        Vec::new(),
    )
8
}
const NODE_WIDTH: f32 = 250.0;
const V_OFFSET: f32 = 71.0;
const DIST_BETWEEN_NODES: f32 = 10.0;
const CONNECTION_DOT_HEIGHT: f32 = 15.0;
// calculates the rect on which the connection is drawn in the UI
#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
#[allow(clippy::cast_precision_loss)] // bounded layout/render numeric cast
29
fn get_rect(
29
    node_graph: &NodeGraph,
29
    connection: ConnectionLocalDataset,
29
) -> Option<(LogicalRect, bool, bool)> {
    let ConnectionLocalDataset {
29
        out_node_id,
29
        out_idx,
29
        in_node_id,
29
        in_idx,
        ..
29
    } = connection;
39
    let out_node = node_graph.nodes.iter().find(|i| i.node_id == out_node_id)?;
82
    let in_node = node_graph.nodes.iter().find(|i| i.node_id == in_node_id)?;
25
    let x_out = out_node.node.position.x + NODE_WIDTH;
25
    let y_out = out_node.node.position.y
25
        + V_OFFSET
25
        + (out_idx as f32 * (DIST_BETWEEN_NODES + CONNECTION_DOT_HEIGHT));
25
    let x_in = in_node.node.position.x;
25
    let y_in = in_node.node.position.y
25
        + V_OFFSET
25
        + (in_idx as f32 * (DIST_BETWEEN_NODES + CONNECTION_DOT_HEIGHT));
25
    let should_swap_vertical = y_in > y_out;
25
    let should_swap_horizontal = x_in < x_out;
25
    let width = (x_in - x_out).abs();
25
    let height = (y_in - y_out).abs() + CONNECTION_DOT_HEIGHT;
25
    let x = x_in.min(x_out);
25
    let y = y_in.min(y_out);
25
    Some((
25
        LogicalRect {
25
            size: LogicalSize { width, height },
25
            origin: LogicalPosition { x, y },
25
        },
25
        should_swap_vertical,
25
        should_swap_horizontal,
25
    ))
29
}
3
extern "C" fn nodegraph_set_active_node(mut refany: RefAny, _info: CallbackInfo) -> Update {
3
    if let Some(mut refany) = refany.downcast_mut::<NodeLocalDataset>() {
2
        let node_id = refany.node_id;
2
        if let Some(mut backref) = refany.backref.downcast_mut::<NodeGraphLocalDataset>() {
1
            backref.active_node_being_dragged = Some(node_id);
1
        }
1
    }
3
    Update::DoNothing
3
}
5
extern "C" fn nodegraph_unset_active_node(mut refany: RefAny, _info: CallbackInfo) -> Update {
5
    if let Some(mut refany) = refany.downcast_mut::<NodeGraphLocalDataset>() {
4
        refany.active_node_being_dragged = None;
4
    }
5
    Update::DoNothing
5
}
// drag either the graph or the currently active nodes
#[allow(clippy::float_cmp)] // intentional exact compare: change-detection / identity fast-path / cache-key match
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
#[allow(clippy::single_match_else)] // drag-node (Some) and drag-graph (None) are each ~135-line
                                    // blocks; match labels the two modes far more clearly than
                                    // if-let/else
3
extern "C" fn nodegraph_drag_graph_or_nodes(mut refany: RefAny, mut info: CallbackInfo) -> Update {
3
    let Some(mut refany) = refany.downcast_mut::<NodeGraphLocalDataset>() else {
1
        return Update::DoNothing;
    };
2
    let refany = &mut *refany;
2
    let Some(prev) = info.get_previous_mouse_state() else {
2
        return Update::DoNothing;
    };
    let cur = info.get_current_mouse_state();
    if !(cur.left_down && prev.left_down) {
        // event is not a drag event
        return Update::DoNothing;
    }
    let (InWindow(current_mouse_pos), InWindow(previous_mouse_pos)) =
        (cur.cursor_position, prev.cursor_position)
    else {
        return Update::DoNothing;
    };
    let dx = (current_mouse_pos.x - previous_mouse_pos.x) * (1.0 / refany.node_graph.scale_factor);
    let dy = (current_mouse_pos.y - previous_mouse_pos.y) * (1.0 / refany.node_graph.scale_factor);
    let nodegraph_node = info.get_hit_node();
    let should_update = match refany.active_node_being_dragged {
        // drag node
        Some(node_graph_node_id) => {
            let dragged_node_marker = node_marker(&refany.marker_prefix, node_graph_node_id);
            let connections_marker: AzString =
                format!("{}-connections", refany.marker_prefix.as_str()).into();
            let _nodegraph_node = info.get_hit_node();
            let result = match refany.callbacks.on_node_dragged.as_ref() {
                Some(OnNodeDragged { callback, refany }) => (callback.cb)(
                    refany.clone(),
                    info,
                    node_graph_node_id,
                    NodeDragAmount { x: dx, y: dy },
                ),
                None => Update::DoNothing,
            };
            // update the visual transform of the node in the UI
            let node_position = match refany
                .node_graph
                .nodes
                .iter_mut()
                .find(|i| i.node_id == node_graph_node_id)
            {
                Some(s) => {
                    s.node.position.x += dx;
                    s.node.position.y += dy;
                    s.node.position
                }
                None => return Update::DoNothing,
            };
            let Some(visual_node_id) = info.get_node_id_by_marker(dragged_node_marker) else {
                return Update::DoNothing;
            };
            let node_transform = StyleTransformTranslate2D {
                x: PixelValue::px(node_position.x + refany.node_graph.offset.x),
                y: PixelValue::px(node_position.y + refany.node_graph.offset.y),
            };
            info.set_css_property(
                visual_node_id,
                CssProperty::transform(
                    if refany.node_graph.scale_factor == 1.0 {
                        vec![StyleTransform::Translate(node_transform)]
                    } else {
                        vec![
                            StyleTransform::Translate(node_transform),
                            StyleTransform::ScaleX(PercentageValue::new(
                                refany.node_graph.scale_factor * 100.0,
                            )),
                            StyleTransform::ScaleY(PercentageValue::new(
                                refany.node_graph.scale_factor * 100.0,
                            )),
                        ]
                    }
                    .into(),
                ),
            );
            // get the NodeId of the node containing all the connection lines
            let Some(connection_container_nodeid) = info.get_node_id_by_marker(connections_marker)
            else {
                return result;
            };
            // animate all the connections
            let mut first_connection_child = info.get_first_child(connection_container_nodeid);
            while let Some(connection_nodeid) = first_connection_child {
                first_connection_child = info.get_next_sibling(connection_nodeid);
                let Some(first_child) = info.get_first_child(connection_nodeid) else {
                    continue;
                };
                let Some(mut dataset) = info.get_dataset(first_child) else {
                    continue;
                };
                let Some(mut cld) = dataset.downcast_mut::<ConnectionLocalDataset>() else {
                    continue;
                };
                if !(cld.out_node_id == node_graph_node_id || cld.in_node_id == node_graph_node_id)
                {
                    continue; // connection does not need to be modified
                }
                let Some((new_rect, swap_vert, swap_horz)) = get_rect(&refany.node_graph, *cld)
                else {
                    continue;
                };
                cld.swap_vert = swap_vert;
                cld.swap_horz = swap_horz;
                let node_transform = StyleTransformTranslate2D {
                    x: PixelValue::px(refany.node_graph.offset.x + new_rect.origin.x),
                    y: PixelValue::px(refany.node_graph.offset.y + new_rect.origin.y),
                };
                info.set_css_property(
                    first_child,
                    CssProperty::transform(
                        if refany.node_graph.scale_factor == 1.0 {
                            vec![StyleTransform::Translate(node_transform)]
                        } else {
                            vec![
                                StyleTransform::Translate(node_transform),
                                StyleTransform::ScaleX(PercentageValue::new(
                                    refany.node_graph.scale_factor * 100.0,
                                )),
                                StyleTransform::ScaleY(PercentageValue::new(
                                    refany.node_graph.scale_factor * 100.0,
                                )),
                            ]
                        }
                        .into(),
                    ),
                );
                info.set_css_property(
                    first_child,
                    CssProperty::Width(LayoutWidthValue::Exact(LayoutWidth::Px(PixelValue::px(
                        new_rect.size.width,
                    )))),
                );
                info.set_css_property(
                    first_child,
                    CssProperty::Height(LayoutHeightValue::Exact(LayoutHeight::Px(
                        PixelValue::px(new_rect.size.height),
                    ))),
                );
            }
            result
        }
        // drag graph
        None => {
            let result = match refany.callbacks.on_node_graph_dragged.as_ref() {
                Some(OnNodeGraphDragged { callback, refany }) => {
                    (callback.cb)(refany.clone(), info, GraphDragAmount { x: dx, y: dy })
                }
                None => Update::DoNothing,
            };
            refany.node_graph.offset.x += dx;
            refany.node_graph.offset.y += dy;
            // Update the visual node positions
            let Some(node_container) = info.get_first_child(nodegraph_node) else {
                return Update::DoNothing;
            };
            let Some(node_container) = info.get_next_sibling(node_container) else {
                return Update::DoNothing;
            };
            let Some(mut node) = info.get_first_child(node_container) else {
                return Update::DoNothing;
            };
            loop {
                let Some(node_first_child) = info.get_first_child(node) else {
                    return Update::DoNothing;
                };
                let Some(mut node_local_dataset) = info.get_dataset(node_first_child) else {
                    return Update::DoNothing;
                };
                let Some(node_graph_node_id) =
                    node_local_dataset.downcast_ref::<NodeLocalDataset>()
                else {
                    continue;
                };
                let node_graph_node_id = node_graph_node_id.node_id;
                let node_position = match refany
                    .node_graph
                    .nodes
                    .iter()
                    .find(|i| i.node_id == node_graph_node_id)
                {
                    Some(s) => s.node.position,
                    None => continue,
                };
                let node_transform = StyleTransformTranslate2D {
                    x: PixelValue::px(node_position.x + refany.node_graph.offset.x),
                    y: PixelValue::px(node_position.y + refany.node_graph.offset.y),
                };
                info.set_css_property(
                    node_first_child,
                    CssProperty::transform(
                        if refany.node_graph.scale_factor == 1.0 {
                            vec![StyleTransform::Translate(node_transform)]
                        } else {
                            vec![
                                StyleTransform::Translate(node_transform),
                                StyleTransform::ScaleX(PercentageValue::new(
                                    refany.node_graph.scale_factor * 100.0,
                                )),
                                StyleTransform::ScaleY(PercentageValue::new(
                                    refany.node_graph.scale_factor * 100.0,
                                )),
                            ]
                        }
                        .into(),
                    ),
                );
                node = match info.get_next_sibling(node) {
                    Some(s) => s,
                    None => break,
                };
            }
            let connections_marker: AzString =
                format!("{}-connections", refany.marker_prefix.as_str()).into();
            // Update the connection positions
            let Some(connection_container_nodeid) = info.get_node_id_by_marker(connections_marker)
            else {
                return result;
            };
            let mut first_connection_child = info.get_first_child(connection_container_nodeid);
            while let Some(connection_nodeid) = first_connection_child {
                first_connection_child = info.get_next_sibling(connection_nodeid);
                let Some(first_child) = info.get_first_child(connection_nodeid) else {
                    continue;
                };
                let Some(mut dataset) = info.get_dataset(first_child) else {
                    continue;
                };
                let Some(cld) = dataset.downcast_ref::<ConnectionLocalDataset>() else {
                    continue;
                };
                let Some((new_rect, _, _)) = get_rect(&refany.node_graph, *cld) else {
                    continue;
                };
                info.set_css_property(
                    first_child,
                    CssProperty::transform(
                        vec![
                            StyleTransform::Translate(StyleTransformTranslate2D {
                                x: PixelValue::px(refany.node_graph.offset.x + new_rect.origin.x),
                                y: PixelValue::px(refany.node_graph.offset.y + new_rect.origin.y),
                            }),
                            StyleTransform::ScaleX(PercentageValue::new(
                                refany.node_graph.scale_factor * 100.0,
                            )),
                            StyleTransform::ScaleY(PercentageValue::new(
                                refany.node_graph.scale_factor * 100.0,
                            )),
                        ]
                        .into(),
                    ),
                );
            }
            result
        }
    };
    info.stop_propagation();
    should_update
3
}
2
extern "C" fn nodegraph_duplicate_node(mut refany: RefAny, _info: CallbackInfo) -> Update {
2
    let Some(_data) = refany.downcast_mut::<NodeLocalDataset>() else {
1
        return Update::DoNothing;
    };
1
    Update::DoNothing // TODO
2
}
5
extern "C" fn nodegraph_delete_node(mut refany: RefAny, mut info: CallbackInfo) -> Update {
5
    let Some(mut refany) = refany.downcast_mut::<NodeLocalDataset>() else {
1
        return Update::DoNothing;
    };
4
    let node_id = refany.node_id;
4
    let Some(mut backref) = refany.backref.downcast_mut::<NodeGraphLocalDataset>() else {
1
        return Update::DoNothing;
    };
3
    let result = match backref.callbacks.on_node_removed.as_ref() {
2
        Some(OnNodeRemoved { callback, refany }) => (callback.cb)(refany.clone(), info, node_id),
1
        None => Update::DoNothing,
    };
3
    result
5
}
#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant
                                  // (or cross-type bindings that can't merge)
4
extern "C" fn nodegraph_context_menu_click(mut refany: RefAny, mut info: CallbackInfo) -> Update {
    use azul_core::window::CursorPosition;
4
    let Some(mut refany) = refany.downcast_mut::<ContextMenuEntryLocalDataset>() else {
1
        return Update::DoNothing;
    };
3
    let new_node_type = refany.node_type;
3
    let Some(mut backref) = refany.backref.downcast_mut::<NodeGraphLocalDataset>() else {
        return Update::DoNothing;
    };
    // The wrapper root carries the render's marker prefix (see
    // `NodeGraph::dom`); resolving it is what tells us whether this graph is
    // actually in the DOM right now.
3
    let Some(node_graph_wrapper_id) = info.get_node_id_by_marker(backref.marker_prefix.clone())
    else {
1
        return Update::DoNothing;
    };
2
    let node_wrapper_offset = info
2
        .get_node_position(node_graph_wrapper_id)
2
        .map_or((0.0, 0.0), |p| (p.x, p.y));
2
    let cursor_in_viewport = match info.get_current_mouse_state().cursor_position {
        InWindow(i) => i,
        CursorPosition::OutOfWindow(i) => i,
2
        CursorPosition::Uninitialized => LogicalPosition::zero(),
    };
2
    let new_node_pos = NodeGraphNodePosition {
2
        x: (cursor_in_viewport.x - node_wrapper_offset.0) * (1.0 / backref.node_graph.scale_factor)
2
            - backref.node_graph.offset.x,
2
        y: (cursor_in_viewport.y - node_wrapper_offset.1) * (1.0 / backref.node_graph.scale_factor)
2
            - backref.node_graph.offset.y,
2
    };
2
    let new_node_id = backref.node_graph.generate_unique_node_id();
2
    let result = match backref.callbacks.on_node_added.as_ref() {
2
        Some(OnNodeAdded { callback, refany }) => (callback.cb)(
2
            refany.clone(),
2
            info,
2
            new_node_type,
2
            new_node_id,
2
            new_node_pos,
2
        ),
        None => Update::DoNothing,
    };
2
    result
4
}
21
extern "C" fn nodegraph_input_output_connect(mut refany: RefAny, mut info: CallbackInfo) -> Update {
    use self::InputOrOutput::{Input, Output};
21
    let Some(mut refany) = refany.downcast_mut::<NodeInputOutputLocalDataset>() else {
1
        return Update::DoNothing;
    };
20
    let io_id = refany.io_id;
20
    let Some(mut backref) = refany.backref.downcast_mut::<NodeLocalDataset>() else {
1
        return Update::DoNothing;
    };
19
    let node_id = backref.node_id;
19
    let Some(mut backref) = backref.backref.downcast_mut::<NodeGraphLocalDataset>() else {
1
        return Update::DoNothing;
    };
7
    let (input_node, input_index, output_node, output_index) =
18
        match backref.last_input_or_output_clicked {
            None => {
9
                backref.last_input_or_output_clicked = Some((node_id, io_id));
9
                return Update::DoNothing;
            }
9
            Some((prev_node_id, prev_io_id)) => {
9
                match (prev_io_id, io_id) {
1
                    (Input(i), Output(o)) => (prev_node_id, i, node_id, o),
6
                    (Output(o), Input(i)) => (node_id, i, prev_node_id, o),
                    _ => {
                        // error: trying to connect input to input or output to output
2
                        backref.last_input_or_output_clicked = None;
2
                        return Update::DoNothing;
                    }
                }
            }
        };
    // verify that the nodetype matches
7
    match backref.node_graph.connect_input_output(
7
        input_node,
7
        input_index,
7
        output_node,
7
        output_index,
7
    ) {
5
        Ok(()) => {}
2
        Err(e) => {
2
            eprintln!("{e:?}");
2
            backref.last_input_or_output_clicked = None;
2
            return Update::DoNothing;
        }
    }
5
    let result = match backref.callbacks.on_node_connected.as_ref() {
3
        Some(OnNodeConnected { callback, refany }) => {
3
            let r = (callback.cb)(
3
                refany.clone(),
3
                info,
3
                input_node,
3
                input_index,
3
                output_node,
3
                output_index,
3
            );
3
            backref.last_input_or_output_clicked = None;
3
            r
        }
2
        None => Update::DoNothing,
    };
5
    result
21
}
6
extern "C" fn nodegraph_input_output_disconnect(mut refany: RefAny, info: CallbackInfo) -> Update {
    use self::InputOrOutput::{Input, Output};
6
    let Some(mut refany) = refany.downcast_mut::<NodeInputOutputLocalDataset>() else {
1
        return Update::DoNothing;
    };
5
    let io_id = refany.io_id;
5
    let Some(mut backref) = refany.backref.downcast_mut::<NodeLocalDataset>() else {
        return Update::DoNothing;
    };
5
    let node_id = backref.node_id;
5
    let Some(mut backref) = backref.backref.downcast_mut::<NodeGraphLocalDataset>() else {
        return Update::DoNothing;
    };
5
    let mut result = Update::DoNothing;
5
    match io_id {
3
        Input(i) => {
3
            result.max_self(
3
                match backref.callbacks.on_node_input_disconnected.as_ref() {
2
                    Some(OnNodeInputDisconnected { callback, refany }) => {
2
                        (callback.cb)(refany.clone(), info, node_id, i)
                    }
1
                    None => Update::DoNothing,
                },
            );
        }
2
        Output(o) => {
2
            result.max_self(
2
                match backref.callbacks.on_node_output_disconnected.as_ref() {
2
                    Some(OnNodeOutputDisconnected { callback, refany }) => {
2
                        (callback.cb)(refany.clone(), info, node_id, o)
                    }
                    None => Update::DoNothing,
                },
            );
        }
    }
5
    result
6
}
6
extern "C" fn nodegraph_on_textinput_focus_lost(
6
    mut refany: RefAny,
6
    info: CallbackInfo,
6
    textinputstate: TextInputState,
6
) -> Update {
6
    let Some(mut refany) = refany.downcast_mut::<NodeFieldLocalDataset>() else {
1
        return Update::DoNothing;
    };
5
    let field_idx = refany.field_idx;
5
    let Some(mut node_local_dataset) = refany.backref.downcast_mut::<NodeLocalDataset>() else {
        return Update::DoNothing;
    };
5
    let node_id = node_local_dataset.node_id;
5
    let Some(mut node_graph) = node_local_dataset
5
        .backref
5
        .downcast_mut::<NodeGraphLocalDataset>()
    else {
        return Update::DoNothing;
    };
5
    let node_type = match node_graph
5
        .node_graph
5
        .nodes
5
        .iter()
9
        .find(|i| i.node_id == node_id)
    {
4
        Some(s) => s.node.node_type,
1
        None => return Update::DoNothing,
    };
4
    let result = match node_graph.callbacks.on_node_field_edited.as_ref() {
4
        Some(OnNodeFieldEdited { refany, callback }) => (callback.cb)(
4
            refany.clone(),
4
            info,
4
            node_id,
4
            field_idx,
4
            node_type,
4
            NodeTypeFieldValue::TextInput(textinputstate.get_text().into()),
4
        ),
        None => Update::DoNothing,
    };
4
    result
6
}
11
extern "C" fn nodegraph_on_numberinput_focus_lost(
11
    mut refany: RefAny,
11
    info: CallbackInfo,
11
    numberinputstate: NumberInputState,
11
) -> Update {
11
    let Some(mut refany) = refany.downcast_mut::<NodeFieldLocalDataset>() else {
1
        return Update::DoNothing;
    };
10
    let field_idx = refany.field_idx;
10
    let Some(mut node_local_dataset) = refany.backref.downcast_mut::<NodeLocalDataset>() else {
        return Update::DoNothing;
    };
10
    let node_id = node_local_dataset.node_id;
10
    let Some(mut node_graph) = node_local_dataset
10
        .backref
10
        .downcast_mut::<NodeGraphLocalDataset>()
    else {
        return Update::DoNothing;
    };
10
    let node_type = match node_graph
10
        .node_graph
10
        .nodes
10
        .iter()
13
        .find(|i| i.node_id == node_id)
    {
9
        Some(s) => s.node.node_type,
1
        None => return Update::DoNothing,
    };
9
    let result = match node_graph.callbacks.on_node_field_edited.as_ref() {
9
        Some(OnNodeFieldEdited { refany, callback }) => (callback.cb)(
9
            refany.clone(),
9
            info,
9
            node_id,
9
            field_idx,
9
            node_type,
9
            NodeTypeFieldValue::NumberInput(numberinputstate.number),
9
        ),
        None => Update::DoNothing,
    };
9
    result
11
}
7
extern "C" fn nodegraph_on_checkbox_value_changed(
7
    mut refany: RefAny,
7
    info: CallbackInfo,
7
    checkboxinputstate: CheckBoxState,
7
) -> Update {
7
    let Some(mut refany) = refany.downcast_mut::<NodeFieldLocalDataset>() else {
1
        return Update::DoNothing;
    };
6
    let field_idx = refany.field_idx;
6
    let Some(mut node_local_dataset) = refany.backref.downcast_mut::<NodeLocalDataset>() else {
        return Update::DoNothing;
    };
6
    let node_id = node_local_dataset.node_id;
6
    let Some(mut node_graph) = node_local_dataset
6
        .backref
6
        .downcast_mut::<NodeGraphLocalDataset>()
    else {
        return Update::DoNothing;
    };
6
    let node_type = match node_graph
6
        .node_graph
6
        .nodes
6
        .iter()
9
        .find(|i| i.node_id == node_id)
    {
5
        Some(s) => s.node.node_type,
1
        None => return Update::DoNothing,
    };
5
    let result = match node_graph.callbacks.on_node_field_edited.as_ref() {
4
        Some(OnNodeFieldEdited { refany, callback }) => (callback.cb)(
4
            refany.clone(),
4
            info,
4
            node_id,
4
            field_idx,
4
            node_type,
4
            NodeTypeFieldValue::CheckBox(checkboxinputstate.checked),
4
        ),
1
        None => Update::DoNothing,
    };
5
    result
7
}
5
extern "C" fn nodegraph_on_colorinput_value_changed(
5
    mut refany: RefAny,
5
    info: CallbackInfo,
5
    colorinputstate: ColorInputState,
5
) -> Update {
5
    let Some(mut refany) = refany.downcast_mut::<NodeFieldLocalDataset>() else {
1
        return Update::DoNothing;
    };
4
    let field_idx = refany.field_idx;
4
    let Some(mut node_local_dataset) = refany.backref.downcast_mut::<NodeLocalDataset>() else {
        return Update::DoNothing;
    };
4
    let node_id = node_local_dataset.node_id;
4
    let Some(mut node_graph) = node_local_dataset
4
        .backref
4
        .downcast_mut::<NodeGraphLocalDataset>()
    else {
        return Update::DoNothing;
    };
4
    let node_type = match node_graph
4
        .node_graph
4
        .nodes
4
        .iter()
7
        .find(|i| i.node_id == node_id)
    {
3
        Some(s) => s.node.node_type,
1
        None => return Update::DoNothing,
    };
3
    let result = match node_graph.callbacks.on_node_field_edited.as_ref() {
3
        Some(OnNodeFieldEdited { refany, callback }) => (callback.cb)(
3
            refany.clone(),
3
            info,
3
            node_id,
3
            field_idx,
3
            node_type,
3
            NodeTypeFieldValue::ColorInput(colorinputstate.color),
3
        ),
        None => Update::DoNothing,
    };
3
    result
5
}
5
extern "C" fn nodegraph_on_fileinput_button_clicked(
5
    mut refany: RefAny,
5
    info: CallbackInfo,
5
    file: FileInputState,
5
) -> Update {
5
    let Some(mut refany) = refany.downcast_mut::<NodeFieldLocalDataset>() else {
1
        return Update::DoNothing;
    };
4
    let field_idx = refany.field_idx;
4
    let Some(mut node_local_dataset) = refany.backref.downcast_mut::<NodeLocalDataset>() else {
        return Update::DoNothing;
    };
4
    let node_id = node_local_dataset.node_id;
4
    let Some(mut node_graph) = node_local_dataset
4
        .backref
4
        .downcast_mut::<NodeGraphLocalDataset>()
    else {
        return Update::DoNothing;
    };
4
    let node_type = match node_graph
4
        .node_graph
4
        .nodes
4
        .iter()
7
        .find(|i| i.node_id == node_id)
    {
3
        Some(s) => s.node.node_type,
1
        None => return Update::DoNothing,
    };
    // If a new file was selected, invoke callback
3
    let result = match node_graph.callbacks.on_node_field_edited.as_ref() {
2
        Some(OnNodeFieldEdited { refany, callback }) => (callback.cb)(
2
            refany.clone(),
2
            info,
2
            node_id,
2
            field_idx,
2
            node_type,
2
            NodeTypeFieldValue::FileInput(file.path),
2
        ),
1
        None => return Update::DoNothing,
    };
2
    result
5
}
#[cfg(all(test, feature = "std"))]
#[allow(clippy::float_cmp, clippy::too_many_lines)]
mod autotest_generated {
    use std::{
        collections::{BTreeMap, HashMap},
        sync::{Arc, Mutex},
    };
    use azul_core::{
        dom::{DomId, DomNodeId},
        geom::{LogicalRect, OptionLogicalPosition},
        gl::OptionGlContextPtr,
        hit_test::ScrollPosition,
        resources::RendererResources,
        styled_dom::{NodeHierarchyItemId, StyledDom},
        window::{MonitorVec, RawWindowHandle},
    };
    use rust_fontconfig::FcFontCache;
    use super::*;
    #[cfg(feature = "icu")]
    use crate::icu::IcuLocalizerHandle;
    use crate::{
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
        window::{DomLayoutResult, LayoutWindow},
        window_state::FullWindowState,
    };
    // ------------------------------------------------------------------
    // Fixtures
    // ------------------------------------------------------------------
    /// Two node types that are deliberately *type-incompatible*: `TYPE_A` speaks
    /// `IO_INT` on both ends, `TYPE_B` speaks `IO_FLOAT`. Every "mime type mismatch"
    /// assertion below is A-to-B; every legal connection is A-to-A.
    const TYPE_A: NodeTypeId = NodeTypeId { inner: 1 };
    const TYPE_B: NodeTypeId = NodeTypeId { inner: 2 };
    /// A node type id that is *never* registered in `node_types`.
    const TYPE_UNREGISTERED: NodeTypeId = NodeTypeId { inner: 99 };
    const IO_INT: InputOutputTypeId = InputOutputTypeId { inner: 10 };
    const IO_FLOAT: InputOutputTypeId = InputOutputTypeId { inner: 20 };
    /// An I/O type id that has no entry in `input_output_types` (so no color).
    const IO_COLORLESS: InputOutputTypeId = InputOutputTypeId { inner: 77 };
    const N1: NodeGraphNodeId = NodeGraphNodeId { inner: 1 };
    const N2: NodeGraphNodeId = NodeGraphNodeId { inner: 2 };
    const N3: NodeGraphNodeId = NodeGraphNodeId { inner: 3 };
    const N4: NodeGraphNodeId = NodeGraphNodeId { inner: 4 };
    /// A node id that is never in the graph.
    const MISSING: NodeGraphNodeId = NodeGraphNodeId { inner: 999 };
    /// The four geometry constants `get_rect` is built from, restated here so that a
    /// silent change to any of them fails the geometry tests loudly instead of
    /// silently re-deriving the "expected" value from the same source.
    const EXPECT_NODE_WIDTH: f32 = 250.0;
    const EXPECT_V_OFFSET: f32 = 71.0;
    const EXPECT_PORT_PITCH: f32 = 25.0; // DIST_BETWEEN_NODES + CONNECTION_DOT_HEIGHT
    const EXPECT_DOT_HEIGHT: f32 = 15.0;
    fn io_types() -> InputOutputTypeIdInfoMapVec {
        vec![
            InputOutputTypeIdInfoMap {
                io_type_id: IO_INT,
                io_info: InputOutputInfo {
                    data_type: AzString::from_const_str("int"),
                    color: ColorU {
                        r: 1,
                        g: 2,
                        b: 3,
                        a: 255,
                    },
                },
            },
            InputOutputTypeIdInfoMap {
                io_type_id: IO_FLOAT,
                io_info: InputOutputInfo {
                    data_type: AzString::from_const_str("float"),
                    color: ColorU {
                        r: 4,
                        g: 5,
                        b: 6,
                        a: 255,
                    },
                },
            },
        ]
        .into()
    }
    fn node_types() -> NodeTypeIdInfoMapVec {
        vec![
            NodeTypeIdInfoMap {
                node_type_id: TYPE_A,
                node_type_info: NodeTypeInfo {
                    is_root: true,
                    node_type_name: AzString::from_const_str("A"),
                    inputs: vec![IO_INT].into(),
                    outputs: vec![IO_INT].into(),
                },
            },
            NodeTypeIdInfoMap {
                node_type_id: TYPE_B,
                node_type_info: NodeTypeInfo {
                    is_root: false,
                    node_type_name: AzString::from_const_str("B"),
                    inputs: vec![IO_FLOAT].into(),
                    outputs: vec![IO_FLOAT].into(),
                },
            },
        ]
        .into()
    }
    fn mk_node(node_type: NodeTypeId, x: f32, y: f32) -> Node {
        Node {
            node_type,
            position: NodeGraphNodePosition { x, y },
            fields: NodeTypeFieldVec::new(),
            connect_in: InputConnectionVec::new(),
            connect_out: OutputConnectionVec::new(),
        }
    }
    /// Four nodes: `N1`, `N3`, `N4` are `TYPE_A` (int), `N2` is `TYPE_B` (float).
    /// So `N1 -> N3`, `N1 -> N4` and `N3 -> N4` are legal connections and anything
    /// touching `N2` is a mime-type mismatch.
    fn graph() -> NodeGraph {
        NodeGraph {
            node_types: node_types(),
            input_output_types: io_types(),
            nodes: vec![
                NodeIdNodeMap {
                    node_id: N1,
                    node: mk_node(TYPE_A, 0.0, 0.0),
                },
                NodeIdNodeMap {
                    node_id: N2,
                    node: mk_node(TYPE_B, 400.0, 100.0),
                },
                NodeIdNodeMap {
                    node_id: N3,
                    node: mk_node(TYPE_A, 800.0, 50.0),
                },
                NodeIdNodeMap {
                    node_id: N4,
                    node: mk_node(TYPE_A, -100.0, 200.0),
                },
            ]
            .into(),
            ..NodeGraph::default()
        }
    }
    /// `(input_index, [(output_node_id, output_index)])` for every input port of `id`.
    fn inputs_of(g: &NodeGraph, id: NodeGraphNodeId) -> Vec<(usize, Vec<(u64, usize)>)> {
        g.nodes
            .iter()
            .find(|n| n.node_id == id)
            .map_or_else(Vec::new, |n| {
                n.node
                    .connect_in
                    .iter()
                    .map(|c| {
                        (
                            c.input_index,
                            c.connects_to
                                .iter()
                                .map(|o| (o.node_id.inner, o.output_index))
                                .collect(),
                        )
                    })
                    .collect()
            })
    }
    /// `(output_index, [(input_node_id, input_index)])` for every output port of `id`.
    fn outputs_of(g: &NodeGraph, id: NodeGraphNodeId) -> Vec<(usize, Vec<(u64, usize)>)> {
        g.nodes
            .iter()
            .find(|n| n.node_id == id)
            .map_or_else(Vec::new, |n| {
                n.node
                    .connect_out
                    .iter()
                    .map(|c| {
                        (
                            c.output_index,
                            c.connects_to
                                .iter()
                                .map(|i| (i.node_id.inner, i.input_index))
                                .collect(),
                        )
                    })
                    .collect()
            })
    }
    /// The full wiring of the graph, as a comparable value — the "encoding" that the
    /// connect/disconnect round-trip tests compare before and after.
    type Wiring = Vec<(
        u64,
        Vec<(usize, Vec<(u64, usize)>)>,
        Vec<(usize, Vec<(u64, usize)>)>,
    )>;
    fn wiring(g: &NodeGraph) -> Wiring {
        g.nodes
            .iter()
            .map(|n| {
                (
                    n.node_id.inner,
                    inputs_of(g, n.node_id),
                    outputs_of(g, n.node_id),
                )
            })
            .collect()
    }
    /// Pushes an output connection *without* going through `connect_input_output`, so
    /// that structurally-impossible graphs (dangling target, out-of-range port, port
    /// with no registered color) can be handed to the renderers.
    fn force_out_connection(
        mut g: NodeGraph,
        from: NodeGraphNodeId,
        out_idx: usize,
        to: NodeGraphNodeId,
        in_idx: usize,
    ) -> NodeGraph {
        if let Some(n) = g.nodes.as_mut().iter_mut().find(|n| n.node_id == from) {
            n.node.connect_out.push(OutputConnection {
                output_index: out_idx,
                connects_to: vec![InputNodeAndIndex {
                    node_id: to,
                    input_index: in_idx,
                }]
                .into(),
            });
        }
        g
    }
    fn count_nodes(dom: &Dom) -> usize {
        1 + dom.children.iter().map(count_nodes).sum::<usize>()
    }
    /// A `RefAny<NodeGraphLocalDataset>` wrapping a snapshot of `g` — the payload every
    /// node-graph callback expects to find at the end of its `backref` chain.
    fn graph_dataset(g: &NodeGraph) -> RefAny {
        RefAny::new(NodeGraphLocalDataset {
            node_graph: g.clone(),
            last_input_or_output_clicked: None,
            active_node_being_dragged: None,
            marker_prefix: "azul-nodegraph-test".into(),
            callbacks: g.callbacks.clone(),
        })
    }
    /// Reads the graph back out of a `NodeGraphLocalDataset` handle.
    fn dataset_graph(handle: &RefAny) -> NodeGraph {
        let mut handle = handle.clone();
        let d = handle
            .downcast_ref::<NodeGraphLocalDataset>()
            .expect("not a NodeGraphLocalDataset");
        d.node_graph.clone()
    }
    /// `InputOrOutput` is not `PartialEq`, so flatten it into something that is.
    fn io_kind(io: InputOrOutput) -> (bool, usize) {
        match io {
            InputOrOutput::Input(i) => (true, i),
            InputOrOutput::Output(o) => (false, o),
        }
    }
    fn pending_click(handle: &RefAny) -> Option<(u64, (bool, usize))> {
        let mut handle = handle.clone();
        let d = handle
            .downcast_ref::<NodeGraphLocalDataset>()
            .expect("not a NodeGraphLocalDataset");
        d.last_input_or_output_clicked
            .map(|(id, io)| (id.inner, io_kind(io)))
    }
    // ------------------------------------------------------------------
    // Callback harness (mirrors the one in check_box.rs / color_input.rs)
    // ------------------------------------------------------------------
    /// A `DomNodeId` whose node component is `None` — "no concrete node was hit".
    fn hit_none() -> DomNodeId {
        DomNodeId {
            dom: DomId::ROOT_ID,
            node: NodeHierarchyItemId::NONE,
        }
    }
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
        DomLayoutResult {
            styled_dom,
            layout_tree: LayoutTree {
                nodes: Vec::new(),
                warm: Vec::new(),
                cold: Vec::new(),
                root: 0,
                dom_to_layout: BTreeMap::new(),
                children_arena: Vec::new(),
                children_offsets: Vec::new(),
                subtree_needs_intrinsic: Vec::new(),
            },
            calculated_positions: Vec::new(),
            viewport: LogicalRect::zero(),
            display_list: Arc::new(DisplayList::default()),
            scroll_ids: HashMap::new(),
            scroll_id_to_node_id: HashMap::new(),
        }
    }
    /// Runs `f` with a `CallbackInfo` whose window holds `styled_dom` as the root DOM.
    /// `previous_window_state` is deliberately `None`, which is what makes
    /// `get_previous_mouse_state()` return `None` in the drag tests.
    fn with_info<R>(
        styled_dom: StyledDom,
        hit: DomNodeId,
        f: impl FnOnce(&mut CallbackInfo) -> R,
    ) -> (R, Vec<CallbackChange>) {
        let mut layout_window =
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
        layout_window
            .layout_results
            .insert(DomId::ROOT_ID, layout_result(styled_dom));
        let renderer_resources = RendererResources::default();
        let previous_window_state: Option<FullWindowState> = None;
        let current_window_state = FullWindowState::default();
        let gl_context = OptionGlContextPtr::None;
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
            BTreeMap::new();
        let window_handle = RawWindowHandle::Unsupported;
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
        let ref_data = CallbackInfoRefData {
            layout_window: &layout_window,
            renderer_resources: &renderer_resources,
            previous_window_state: &previous_window_state,
            current_window_state: &current_window_state,
            gl_context: &gl_context,
            current_scroll_manager: &scroll_states,
            current_window_handle: &window_handle,
            system_callbacks: &system_callbacks,
            system_style: Arc::new(system::SystemStyle::default()),
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
            #[cfg(feature = "icu")]
            icu_localizer: IcuLocalizerHandle::default(),
            ctx: OptionRefAny::None,
        };
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
        let mut info = CallbackInfo::new(
            &ref_data,
            &changes,
            hit,
            OptionLogicalPosition::None,
            OptionLogicalPosition::None,
        );
        let r = f(&mut info);
        let pushed = info.take_changes();
        (r, pushed)
    }
    /// Shorthand for "deliver one event to `cb` with an otherwise-empty window".
    fn fire(cb: impl FnOnce(CallbackInfo) -> Update) -> Update {
        with_info(StyledDom::default(), hit_none(), |info| cb(*info)).0
    }
    // ------------------------------------------------------------------
    // User-callback recorder
    // ------------------------------------------------------------------
    /// Everything the widget's user-facing callbacks were handed, in call order.
    #[derive(Debug, Default)]
    struct Log {
        removed: Vec<u64>,
        added: Vec<(u64, u64, f32, f32)>,
        connected: Vec<(u64, usize, u64, usize)>,
        input_disconnected: Vec<(u64, usize)>,
        output_disconnected: Vec<(u64, usize)>,
        /// `(node_id, field_idx, node_type)` of every `on_node_field_edited` call.
        edited: Vec<(u64, usize, u64)>,
        text_values: Vec<String>,
        number_values: Vec<f32>,
        bool_values: Vec<bool>,
        color_values: Vec<(u8, u8, u8, u8)>,
        file_values: Vec<Option<String>>,
    }
    fn log_of(handle: &RefAny, f: impl FnOnce(&Log)) {
        let mut handle = handle.clone();
        let l = handle.downcast_ref::<Log>().expect("not a Log");
        f(&l);
    }
    extern "C" fn rec_removed(
        mut refany: RefAny,
        _info: CallbackInfo,
        node_id: NodeGraphNodeId,
    ) -> Update {
        if let Some(mut l) = refany.downcast_mut::<Log>() {
            l.removed.push(node_id.inner);
        }
        Update::RefreshDom
    }
    extern "C" fn rec_added(
        mut refany: RefAny,
        _info: CallbackInfo,
        new_node_type: NodeTypeId,
        new_node_id: NodeGraphNodeId,
        new_node_position: NodeGraphNodePosition,
    ) -> Update {
        if let Some(mut l) = refany.downcast_mut::<Log>() {
            l.added.push((
                new_node_type.inner,
                new_node_id.inner,
                new_node_position.x,
                new_node_position.y,
            ));
        }
        Update::RefreshDomAllWindows
    }
    extern "C" fn rec_connected(
        mut refany: RefAny,
        _info: CallbackInfo,
        input: NodeGraphNodeId,
        input_index: usize,
        output: NodeGraphNodeId,
        output_index: usize,
    ) -> Update {
        if let Some(mut l) = refany.downcast_mut::<Log>() {
            l.connected
                .push((input.inner, input_index, output.inner, output_index));
        }
        Update::RefreshDom
    }
    extern "C" fn rec_input_disconnected(
        mut refany: RefAny,
        _info: CallbackInfo,
        input: NodeGraphNodeId,
        input_index: usize,
    ) -> Update {
        if let Some(mut l) = refany.downcast_mut::<Log>() {
            l.input_disconnected.push((input.inner, input_index));
        }
        Update::RefreshDom
    }
    extern "C" fn rec_output_disconnected(
        mut refany: RefAny,
        _info: CallbackInfo,
        output: NodeGraphNodeId,
        output_index: usize,
    ) -> Update {
        if let Some(mut l) = refany.downcast_mut::<Log>() {
            l.output_disconnected.push((output.inner, output_index));
        }
        Update::RefreshDomAllWindows
    }
    extern "C" fn rec_field_edited(
        mut refany: RefAny,
        _info: CallbackInfo,
        node_id: NodeGraphNodeId,
        field_id: usize,
        node_type: NodeTypeId,
        new_value: NodeTypeFieldValue,
    ) -> Update {
        if let Some(mut l) = refany.downcast_mut::<Log>() {
            l.edited.push((node_id.inner, field_id, node_type.inner));
            match new_value {
                NodeTypeFieldValue::TextInput(s) => l.text_values.push(s.as_str().to_string()),
                NodeTypeFieldValue::NumberInput(n) => l.number_values.push(n),
                NodeTypeFieldValue::CheckBox(b) => l.bool_values.push(b),
                NodeTypeFieldValue::ColorInput(c) => l.color_values.push((c.r, c.g, c.b, c.a)),
                NodeTypeFieldValue::FileInput(p) => l
                    .file_values
                    .push(p.as_ref().map(|s| s.as_str().to_string())),
            }
        }
        Update::RefreshDom
    }
    /// A graph whose callbacks all funnel into one freshly-created `Log`.
    fn graph_with_log() -> (NodeGraph, RefAny) {
        let log = RefAny::new(Log::default());
        let mut g = graph();
        g.callbacks = NodeGraphCallbacks {
            on_node_removed: OptionOnNodeRemoved::Some(OnNodeRemoved {
                refany: log.clone(),
                callback: OnNodeRemovedCallback {
                    cb: rec_removed,
                    ctx: OptionRefAny::None,
                },
            }),
            on_node_added: OptionOnNodeAdded::Some(OnNodeAdded {
                refany: log.clone(),
                callback: OnNodeAddedCallback {
                    cb: rec_added,
                    ctx: OptionRefAny::None,
                },
            }),
            on_node_connected: OptionOnNodeConnected::Some(OnNodeConnected {
                refany: log.clone(),
                callback: OnNodeConnectedCallback {
                    cb: rec_connected,
                    ctx: OptionRefAny::None,
                },
            }),
            on_node_input_disconnected: OptionOnNodeInputDisconnected::Some(
                OnNodeInputDisconnected {
                    refany: log.clone(),
                    callback: OnNodeInputDisconnectedCallback {
                        cb: rec_input_disconnected,
                        ctx: OptionRefAny::None,
                    },
                },
            ),
            on_node_output_disconnected: OptionOnNodeOutputDisconnected::Some(
                OnNodeOutputDisconnected {
                    refany: log.clone(),
                    callback: OnNodeOutputDisconnectedCallback {
                        cb: rec_output_disconnected,
                        ctx: OptionRefAny::None,
                    },
                },
            ),
            on_node_field_edited: OptionOnNodeFieldEdited::Some(OnNodeFieldEdited {
                refany: log.clone(),
                callback: OnNodeFieldEditedCallback {
                    cb: rec_field_edited,
                    ctx: OptionRefAny::None,
                },
            }),
            ..NodeGraphCallbacks::default()
        };
        (g, log)
    }
    // ==================================================================
    // 1. NodeGraph::generate_unique_node_id
    // ==================================================================
    #[test]
    fn generate_unique_node_id_on_an_empty_graph_is_one_not_zero() {
        // `0` is a perfectly valid node id, so the generator must not hand it out for
        // the first node either — `max().unwrap_or(0) + 1`.
        assert_eq!(NodeGraph::default().generate_unique_node_id().inner, 1);
    }
    #[test]
    fn generate_unique_node_id_returns_max_plus_one_and_ignores_gaps_and_order() {
        // Ids are deliberately unsorted and non-contiguous: the generator must take the
        // maximum, not the last element and not the length.
        let g = NodeGraph {
            nodes: vec![
                NodeIdNodeMap {
                    node_id: NodeGraphNodeId { inner: 7 },
                    node: mk_node(TYPE_A, 0.0, 0.0),
                },
                NodeIdNodeMap {
                    node_id: NodeGraphNodeId { inner: 0 },
                    node: mk_node(TYPE_A, 0.0, 0.0),
                },
                NodeIdNodeMap {
                    node_id: NodeGraphNodeId { inner: 3 },
                    node: mk_node(TYPE_A, 0.0, 0.0),
                },
            ]
            .into(),
            ..Default::default()
        };
        assert_eq!(g.generate_unique_node_id().inner, 8);
    }
    #[test]
    fn generate_unique_node_id_tolerates_duplicate_ids_in_the_graph() {
        let g = NodeGraph {
            nodes: vec![
                NodeIdNodeMap {
                    node_id: N2,
                    node: mk_node(TYPE_A, 0.0, 0.0),
                },
                NodeIdNodeMap {
                    node_id: N2,
                    node: mk_node(TYPE_A, 0.0, 0.0),
                },
            ]
            .into(),
            ..Default::default()
        };
        assert_eq!(g.generate_unique_node_id().inner, 3);
    }
    #[test]
    fn generate_unique_node_id_saturates_instead_of_overflowing_at_u64_max() {
        // `saturating_add(1)` means the id at the top of the range is NOT unique: it
        // collides with the existing node. That is a real (if unreachable in practice)
        // limitation — what matters here is that it saturates rather than wrapping to
        // 0 or panicking in a debug build.
        let mut g = NodeGraph {
            nodes: vec![NodeIdNodeMap {
                node_id: NodeGraphNodeId { inner: u64::MAX },
                node: mk_node(TYPE_A, 0.0, 0.0),
            }]
            .into(),
            ..Default::default()
        };
        let id = g.generate_unique_node_id();
        assert_eq!(id.inner, u64::MAX);
        assert!(
            g.nodes.iter().any(|n| n.node_id == id),
            "at u64::MAX the generated id collides — documented saturation, not wraparound",
        );
        // ...and one below the top still behaves normally.
        g.nodes = vec![NodeIdNodeMap {
            node_id: NodeGraphNodeId {
                inner: u64::MAX - 1,
            },
            node: mk_node(TYPE_A, 0.0, 0.0),
        }]
        .into();
        assert_eq!(g.generate_unique_node_id().inner, u64::MAX);
    }
    #[test]
    fn generate_unique_node_id_is_pure_and_repeats_until_the_node_is_inserted() {
        let g = graph();
        let first = g.generate_unique_node_id();
        assert_eq!(first, g.generate_unique_node_id());
        assert_eq!(first.inner, 5); // max(1,2,3,4) + 1
    }
    // ==================================================================
    // 2. NodeGraphError: Display / Debug
    // ==================================================================
    const ALL_ERRORS: [NodeGraphError; 4] = [
        NodeGraphError::NodeMimeTypeMismatch,
        NodeGraphError::NodeInvalidIndex,
        NodeGraphError::NodeInvalidNode,
        NodeGraphError::NoRootNode,
    ];
    #[test]
    fn node_graph_error_display_is_non_empty_ascii_and_single_line() {
        for e in ALL_ERRORS {
            let s = format!("{e}");
            assert!(!s.is_empty(), "{e:?} formatted to the empty string");
            assert!(!s.contains('\n'), "{e:?} formatted to a multi-line string");
            assert!(s.is_ascii(), "{e:?} formatted to non-ascii: {s}");
        }
    }
    #[test]
    fn node_graph_error_display_distinguishes_every_variant() {
        // A copy-pasted match arm that returns the same message for two variants would
        // make the error useless in a log; this is the assertion that catches it.
        let mut seen: Vec<String> = ALL_ERRORS.iter().map(|e| format!("{e}")).collect();
        seen.sort();
        seen.dedup();
        assert_eq!(seen.len(), ALL_ERRORS.len());
    }
    #[test]
    fn node_graph_error_display_survives_width_precision_and_fill_specifiers() {
        // `write!` inside a Display impl ignores the outer format spec, but the spec
        // must not make the impl panic or truncate to nothing.
        for e in ALL_ERRORS {
            assert!(!format!("{e:>80}").is_empty());
            assert!(!format!("{e:*^3}").is_empty());
            assert!(!format!("{e:.1}").is_empty());
            assert!(!format!("{e:?}").is_empty());
        }
    }
    #[test]
    fn node_graph_error_debug_and_display_are_both_usable_and_differ_in_style() {
        // Debug is the derived variant name; Display is prose. They should not be the
        // same string, otherwise one of the two impls is missing.
        for e in ALL_ERRORS {
            assert_ne!(format!("{e:?}"), format!("{e}"));
        }
    }
    // ==================================================================
    // 3. NodeGraph::swap_with_default
    // ==================================================================
    /// Everything about a `NodeGraph` that is cheaply comparable.
    fn summary(g: &NodeGraph) -> (usize, usize, usize, bool, f32, f32, f32, String) {
        (
            g.node_types.len(),
            g.input_output_types.len(),
            g.nodes.len(),
            g.allow_multiple_root_nodes,
            g.offset.x,
            g.offset.y,
            g.scale_factor,
            g.add_node_str.as_str().to_string(),
        )
    }
    fn distinctive() -> NodeGraph {
        NodeGraph {
            allow_multiple_root_nodes: true,
            offset: LogicalPosition { x: -3.5, y: 12.25 },
            scale_factor: 2.5,
            add_node_str: AzString::from_const_str("Ajouter un nœud"),
            ..graph()
        }
    }
    #[test]
    fn swap_with_default_hands_back_the_old_value_and_leaves_a_default_behind() {
        let mut g = distinctive();
        let expected = summary(&g);
        let taken = g.swap_with_default();
        assert_eq!(summary(&taken), expected);
        assert_eq!(summary(&g), summary(&NodeGraph::default()));
    }
    #[test]
    fn swap_with_default_round_trips_a_graph_through_two_owners() {
        // encode == decode: moving a graph out and back must not lose a single field.
        let mut a = distinctive();
        let expected = summary(&a);
        let mut b = a.swap_with_default(); // a := default, b := original
        let c = b.swap_with_default(); // b := default, c := original again
        assert_eq!(summary(&c), expected);
        assert_eq!(summary(&b), summary(&NodeGraph::default()));
        assert_eq!(summary(&a), summary(&NodeGraph::default()));
    }
    #[test]
    fn swap_with_default_on_an_already_default_graph_is_a_no_op() {
        let mut g = NodeGraph::default();
        let taken = g.swap_with_default();
        assert_eq!(summary(&taken), summary(&NodeGraph::default()));
        assert_eq!(summary(&g), summary(&NodeGraph::default()));
    }
    #[test]
    fn swap_with_default_preserves_non_finite_offsets_and_scale_verbatim() {
        // The swap is a `mem::swap`, so NaN/inf must survive bit-for-bit rather than
        // being normalised away.
        let mut g = NodeGraph {
            offset: LogicalPosition {
                x: f32::INFINITY,
                y: f32::NEG_INFINITY,
            },
            scale_factor: f32::NAN,
            ..NodeGraph::default()
        };
        let taken = g.swap_with_default();
        assert!(taken.offset.x.is_infinite() && taken.offset.x.is_sign_positive());
        assert!(taken.offset.y.is_infinite() && taken.offset.y.is_sign_negative());
        assert!(taken.scale_factor.is_nan());
        assert_eq!(g.scale_factor, 1.0);
    }
    #[test]
    fn swap_with_default_moves_the_connections_not_just_the_node_list() {
        let mut g = graph();
        g.connect_input_output(N3, 0, N1, 0)
            .expect("legal A->A wire");
        let before = wiring(&g);
        let taken = g.swap_with_default();
        assert_eq!(wiring(&taken), before);
        assert!(g.nodes.is_empty());
    }
    // ==================================================================
    // 4. NodeGraph::verify_nodetype_match
    // ==================================================================
    #[test]
    fn verify_nodetype_match_accepts_matching_types_at_index_zero() {
        let g = graph();
        assert_eq!(g.verify_nodetype_match(N1, 0, N3, 0), Ok(()));
    }
    #[test]
    fn verify_nodetype_match_rejects_a_type_mismatch() {
        let g = graph();
        // N1 emits `int`, N2 consumes `float`.
        assert_eq!(
            g.verify_nodetype_match(N1, 0, N2, 0),
            Err(NodeGraphError::NodeMimeTypeMismatch)
        );
    }
    #[test]
    fn verify_nodetype_match_reports_a_missing_node_on_either_side() {
        let g = graph();
        assert_eq!(
            g.verify_nodetype_match(MISSING, 0, N3, 0),
            Err(NodeGraphError::NodeInvalidNode)
        );
        assert_eq!(
            g.verify_nodetype_match(N1, 0, MISSING, 0),
            Err(NodeGraphError::NodeInvalidNode)
        );
    }
    #[test]
    fn verify_nodetype_match_reports_a_node_whose_type_is_not_registered() {
        let mut g = graph();
        g.nodes.push(NodeIdNodeMap {
            node_id: NodeGraphNodeId { inner: 50 },
            node: mk_node(TYPE_UNREGISTERED, 0.0, 0.0),
        });
        assert_eq!(
            g.verify_nodetype_match(NodeGraphNodeId { inner: 50 }, 0, N3, 0),
            Err(NodeGraphError::NodeInvalidNode)
        );
        assert_eq!(
            g.verify_nodetype_match(N1, 0, NodeGraphNodeId { inner: 50 }, 0),
            Err(NodeGraphError::NodeInvalidNode)
        );
    }
    #[test]
    fn verify_nodetype_match_rejects_out_of_range_port_indices() {
        let g = graph();
        // Both node types declare exactly one input and one output, so index 1 is the
        // first out-of-range index.
        assert_eq!(
            g.verify_nodetype_match(N1, 1, N3, 0),
            Err(NodeGraphError::NodeInvalidIndex)
        );
        assert_eq!(
            g.verify_nodetype_match(N1, 0, N3, 1),
            Err(NodeGraphError::NodeInvalidIndex)
        );
    }
    #[test]
    fn verify_nodetype_match_does_not_panic_at_usize_max_indices() {
        // `Vec::get(usize::MAX)` must be the thing that fails, not an unchecked index.
        let g = graph();
        assert_eq!(
            g.verify_nodetype_match(N1, usize::MAX, N3, 0),
            Err(NodeGraphError::NodeInvalidIndex)
        );
        assert_eq!(
            g.verify_nodetype_match(N1, 0, N3, usize::MAX),
            Err(NodeGraphError::NodeInvalidIndex)
        );
        assert_eq!(
            g.verify_nodetype_match(N1, usize::MAX, N3, usize::MAX),
            Err(NodeGraphError::NodeInvalidIndex)
        );
    }
    #[test]
    fn verify_nodetype_match_checks_nodes_before_indices() {
        // Ordering matters for the error a user sees: a missing node is reported even
        // when the index is also nonsense.
        let g = graph();
        assert_eq!(
            g.verify_nodetype_match(MISSING, usize::MAX, N3, usize::MAX),
            Err(NodeGraphError::NodeInvalidNode)
        );
    }
    #[test]
    fn verify_nodetype_match_allows_a_node_to_be_wired_to_itself() {
        // Documented behaviour: there is no self-loop / cycle check at this layer.
        let g = graph();
        assert_eq!(g.verify_nodetype_match(N1, 0, N1, 0), Ok(()));
    }
    #[test]
    fn verify_nodetype_match_does_not_mutate_the_graph() {
        let g = graph();
        let before = wiring(&g);
        let _ = g.verify_nodetype_match(N1, 0, N3, 0);
        let _ = g.verify_nodetype_match(MISSING, usize::MAX, N2, 9);
        assert_eq!(wiring(&g), before);
    }
    // ==================================================================
    // 5. NodeGraph::connect_input_output
    // ==================================================================
    #[test]
    fn connect_input_output_wires_both_directions_at_index_zero() {
        let mut g = graph();
        assert_eq!(g.connect_input_output(N3, 0, N1, 0), Ok(()));
        assert_eq!(inputs_of(&g, N3), vec![(0, vec![(N1.inner, 0)])]);
        assert_eq!(outputs_of(&g, N1), vec![(0, vec![(N3.inner, 0)])]);
        // ...and nothing else moved.
        assert!(outputs_of(&g, N3).is_empty());
        assert!(inputs_of(&g, N1).is_empty());
    }
    #[test]
    fn connect_input_output_rejects_a_mime_type_mismatch_without_mutating() {
        let mut g = graph();
        let before = wiring(&g);
        assert_eq!(
            g.connect_input_output(N2, 0, N1, 0),
            Err(NodeGraphError::NodeMimeTypeMismatch)
        );
        assert_eq!(wiring(&g), before, "a rejected connect must be atomic");
    }
    #[test]
    fn connect_input_output_rejects_missing_nodes_without_mutating() {
        for (input, output) in [(MISSING, N1), (N3, MISSING), (MISSING, MISSING)] {
            let mut g = graph();
            let before = wiring(&g);
            assert_eq!(
                g.connect_input_output(input, 0, output, 0),
                Err(NodeGraphError::NodeInvalidNode)
            );
            assert_eq!(wiring(&g), before);
        }
    }
    #[test]
    fn connect_input_output_rejects_out_of_range_and_usize_max_indices() {
        for (in_idx, out_idx) in [
            (1_usize, 0_usize),
            (0, 1),
            (usize::MAX, 0),
            (0, usize::MAX),
            (usize::MAX, usize::MAX),
        ] {
            let mut g = graph();
            let before = wiring(&g);
            assert_eq!(
                g.connect_input_output(N3, in_idx, N1, out_idx),
                Err(NodeGraphError::NodeInvalidIndex),
                "in={in_idx} out={out_idx}",
            );
            assert_eq!(wiring(&g), before);
        }
    }
    #[test]
    fn connect_input_output_appends_to_an_existing_port_rather_than_replacing_it() {
        // Two different sources feeding the same input port must both be recorded.
        let mut g = graph();
        g.connect_input_output(N4, 0, N1, 0).expect("N1 -> N4");
        g.connect_input_output(N4, 0, N3, 0).expect("N3 -> N4");
        assert_eq!(
            inputs_of(&g, N4),
            vec![(0, vec![(N1.inner, 0), (N3.inner, 0)])],
            "the second wire must not overwrite the first",
        );
        assert_eq!(outputs_of(&g, N1), vec![(0, vec![(N4.inner, 0)])]);
        assert_eq!(outputs_of(&g, N3), vec![(0, vec![(N4.inner, 0)])]);
    }
    #[test]
    fn connect_input_output_records_a_duplicate_wire_twice() {
        // Documented behaviour: there is no de-duplication, so connecting the same two
        // ports twice yields two identical entries on both sides.
        let mut g = graph();
        g.connect_input_output(N3, 0, N1, 0).expect("first");
        g.connect_input_output(N3, 0, N1, 0).expect("second");
        assert_eq!(
            inputs_of(&g, N3),
            vec![(0, vec![(N1.inner, 0), (N1.inner, 0)])]
        );
        assert_eq!(
            outputs_of(&g, N1),
            vec![(0, vec![(N3.inner, 0), (N3.inner, 0)])]
        );
    }
    #[test]
    fn connect_input_output_permits_a_self_loop() {
        // No cycle detection at this layer — the node ends up wired to itself.
        let mut g = graph();
        assert_eq!(g.connect_input_output(N1, 0, N1, 0), Ok(()));
        assert_eq!(inputs_of(&g, N1), vec![(0, vec![(N1.inner, 0)])]);
        assert_eq!(outputs_of(&g, N1), vec![(0, vec![(N1.inner, 0)])]);
    }
    // ==================================================================
    // 6. NodeGraph::disconnect_input
    // ==================================================================
    #[test]
    fn disconnect_input_round_trips_a_single_connection() {
        // encode == decode: connect then disconnect restores the exact wiring.
        let mut g = graph();
        let before = wiring(&g);
        g.connect_input_output(N3, 0, N1, 0).expect("connect");
        assert_ne!(wiring(&g), before);
        assert_eq!(g.disconnect_input(N3, 0), Ok(()));
        assert_eq!(wiring(&g), before);
    }
    #[test]
    fn disconnect_input_reports_a_missing_node() {
        let mut g = graph();
        assert_eq!(
            g.disconnect_input(MISSING, 0),
            Err(NodeGraphError::NodeInvalidNode)
        );
    }
    #[test]
    fn disconnect_input_on_an_unconnected_port_is_ok_and_changes_nothing() {
        let mut g = graph();
        let before = wiring(&g);
        assert_eq!(g.disconnect_input(N3, 0), Ok(()));
        assert_eq!(wiring(&g), before);
    }
    #[test]
    fn disconnect_input_at_usize_max_is_ok_rather_than_invalid_index() {
        // Documented behaviour: an index that is not present short-circuits to `Ok(())`
        // *before* any range validation, so even `usize::MAX` is accepted silently.
        let mut g = graph();
        let before = wiring(&g);
        assert_eq!(g.disconnect_input(N3, usize::MAX), Ok(()));
        assert_eq!(wiring(&g), before);
    }
    #[test]
    fn disconnect_input_clears_every_source_feeding_that_port() {
        let mut g = graph();
        let before = wiring(&g);
        g.connect_input_output(N4, 0, N1, 0).expect("N1 -> N4");
        g.connect_input_output(N4, 0, N3, 0).expect("N3 -> N4");
        assert_eq!(g.disconnect_input(N4, 0), Ok(()));
        assert_eq!(
            wiring(&g),
            before,
            "both upstream ports must be released, not just the first",
        );
    }
    #[test]
    fn disconnect_input_orphans_a_sibling_sharing_the_same_output_port() {
        // BUG (characterised, not endorsed): `disconnect_input` removes the *whole*
        // `OutputConnection` entry of the upstream port instead of removing just the
        // one `InputNodeAndIndex` that pointed back. When two inputs are fed by the
        // same output, disconnecting one of them silently drops the other's
        // forward edge while leaving its backward edge in place — the two halves of
        // the graph disagree afterwards.
        let mut g = graph();
        g.connect_input_output(N3, 0, N1, 0).expect("N1 -> N3");
        g.connect_input_output(N4, 0, N1, 0).expect("N1 -> N4");
        assert_eq!(
            outputs_of(&g, N1),
            vec![(0, vec![(N3.inner, 0), (N4.inner, 0)])]
        );
        assert_eq!(g.disconnect_input(N3, 0), Ok(()));
        assert!(inputs_of(&g, N3).is_empty(), "the requested edge is gone");
        assert_eq!(
            inputs_of(&g, N4),
            vec![(0, vec![(N1.inner, 0)])],
            "N4 still believes it is connected to N1",
        );
        assert!(
            outputs_of(&g, N1).is_empty(),
            "...but N1 no longer lists N4 — the collateral damage this test pins down",
        );
    }
    // ==================================================================
    // 7. NodeGraph::disconnect_output
    // ==================================================================
    #[test]
    fn disconnect_output_round_trips_a_single_connection() {
        let mut g = graph();
        let before = wiring(&g);
        g.connect_input_output(N3, 0, N1, 0).expect("connect");
        assert_eq!(g.disconnect_output(N1, 0), Ok(()));
        assert_eq!(wiring(&g), before);
    }
    #[test]
    fn disconnect_output_reports_a_missing_node() {
        let mut g = graph();
        assert_eq!(
            g.disconnect_output(MISSING, 0),
            Err(NodeGraphError::NodeInvalidNode)
        );
    }
    #[test]
    fn disconnect_output_on_an_unconnected_port_is_ok_and_changes_nothing() {
        let mut g = graph();
        let before = wiring(&g);
        assert_eq!(g.disconnect_output(N1, 0), Ok(()));
        assert_eq!(wiring(&g), before);
    }
    #[test]
    fn disconnect_output_at_usize_max_is_ok_rather_than_invalid_index() {
        let mut g = graph();
        let before = wiring(&g);
        assert_eq!(g.disconnect_output(N1, usize::MAX), Ok(()));
        assert_eq!(wiring(&g), before);
    }
    #[test]
    fn disconnect_output_releases_every_downstream_input_it_fed() {
        // The mirror image of `disconnect_input_orphans_a_sibling...`: here the fan-out
        // case *is* handled correctly, because the loop walks the cloned target list.
        let mut g = graph();
        let before = wiring(&g);
        g.connect_input_output(N3, 0, N1, 0).expect("N1 -> N3");
        g.connect_input_output(N4, 0, N1, 0).expect("N1 -> N4");
        assert_eq!(g.disconnect_output(N1, 0), Ok(()));
        assert_eq!(wiring(&g), before, "no dangling back-reference may survive");
    }
    #[test]
    fn disconnect_output_of_a_self_loop_leaves_no_residue() {
        let mut g = graph();
        let before = wiring(&g);
        g.connect_input_output(N1, 0, N1, 0).expect("self loop");
        assert_eq!(g.disconnect_output(N1, 0), Ok(()));
        assert_eq!(wiring(&g), before);
    }
    // ==================================================================
    // 8. get_rect
    // ==================================================================
    fn connection(
        out: NodeGraphNodeId,
        out_idx: usize,
        inn: NodeGraphNodeId,
        in_idx: usize,
    ) -> ConnectionLocalDataset {
        ConnectionLocalDataset {
            out_node_id: out,
            out_idx,
            in_node_id: inn,
            in_idx,
            // Deliberately wrong: `get_rect` must recompute both flags from geometry.
            swap_vert: true,
            swap_horz: true,
            color: ColorU {
                r: 0,
                g: 0,
                b: 0,
                a: 0,
            },
        }
    }
    #[test]
    fn get_rect_returns_none_for_a_dangling_endpoint() {
        let g = graph();
        assert!(get_rect(&g, connection(MISSING, 0, N3, 0)).is_none());
        assert!(get_rect(&g, connection(N1, 0, MISSING, 0)).is_none());
        assert!(get_rect(&g, connection(MISSING, 0, MISSING, 0)).is_none());
    }
    #[test]
    fn get_rect_computes_the_bounding_box_of_the_two_ports() {
        // N1 sits at (0, 0), N3 at (800, 50); both use port 0.
        let g = graph();
        let (rect, swap_vert, swap_horz) =
            get_rect(&g, connection(N1, 0, N3, 0)).expect("both nodes exist");
        let x_out = 0.0 + EXPECT_NODE_WIDTH;
        let y_out = 0.0 + EXPECT_V_OFFSET;
        let x_in = 800.0;
        let y_in = 50.0 + EXPECT_V_OFFSET;
        assert_eq!(rect.origin.x, x_out.min(x_in));
        assert_eq!(rect.origin.y, y_out.min(y_in));
        assert_eq!(rect.size.width, (x_in - x_out).abs());
        assert_eq!(rect.size.height, (y_in - y_out).abs() + EXPECT_DOT_HEIGHT);
        assert!(swap_vert, "the input port sits below the output port");
        assert!(!swap_horz, "the input node is to the right of the output");
    }
    #[test]
    fn get_rect_recomputes_the_swap_flags_and_ignores_the_ones_it_was_handed() {
        // The fixture passes `swap_vert: true, swap_horz: true` every time; here both
        // must come back `false`, proving the incoming values are not echoed.
        let g = graph();
        // N3 (800, 50) -> N1 (0, 0): input is left of, and above, the output.
        let (_, swap_vert, swap_horz) = get_rect(&g, connection(N3, 0, N1, 0)).expect("exists");
        assert!(!swap_vert);
        assert!(swap_horz);
    }
    #[test]
    fn get_rect_height_is_never_below_the_connection_dot() {
        // Two nodes at the same height give a zero-height span; the dot height is the
        // floor that keeps the rect drawable.
        let mut g = graph();
        g.nodes.as_mut()[2].node.position = NodeGraphNodePosition { x: 800.0, y: 0.0 };
        let (rect, _, _) = get_rect(&g, connection(N1, 0, N3, 0)).expect("exists");
        assert_eq!(rect.size.height, EXPECT_DOT_HEIGHT);
    }
    #[test]
    fn get_rect_port_index_shifts_the_endpoint_by_a_fixed_pitch() {
        // N1's output port (y = 71) is the topmost point of the rect; moving N3's input
        // down by three port pitches must therefore grow the height by exactly three
        // pitches and leave the origin where it was.
        let g = graph();
        let (base, _, _) = get_rect(&g, connection(N1, 0, N3, 0)).expect("exists");
        let (shifted, _, _) = get_rect(&g, connection(N1, 0, N3, 3)).expect("exists");
        assert_eq!(shifted.origin.y, base.origin.y);
        assert_eq!(
            shifted.size.height - base.size.height,
            3.0 * EXPECT_PORT_PITCH,
        );
    }
    #[test]
    fn get_rect_stays_finite_at_usize_max_port_indices() {
        // `usize::MAX as f32` is ~1.8e19 — large, but multiplying by the 25px pitch
        // still lands well inside f32 range, so nothing may become inf or NaN.
        let g = graph();
        let (rect, _, _) =
            get_rect(&g, connection(N1, usize::MAX, N3, usize::MAX)).expect("both nodes exist");
        assert!(rect.origin.y.is_finite(), "y = {}", rect.origin.y);
        assert!(rect.size.height.is_finite(), "h = {}", rect.size.height);
        assert!(rect.size.width.is_finite());
        assert!(rect.size.height >= EXPECT_DOT_HEIGHT);
    }
    #[test]
    fn get_rect_with_a_nan_position_yields_nan_extent_but_a_finite_origin() {
        // `f32::min` returns the non-NaN operand, so the origin survives even though
        // the extent does not. Neither may panic.
        let mut g = graph();
        g.nodes.as_mut()[2].node.position = NodeGraphNodePosition {
            x: f32::NAN,
            y: f32::NAN,
        };
        let (rect, swap_vert, swap_horz) = get_rect(&g, connection(N1, 0, N3, 0)).expect("exists");
        assert!(rect.size.width.is_nan());
        assert!(rect.size.height.is_nan());
        assert_eq!(rect.origin.x, EXPECT_NODE_WIDTH);
        assert_eq!(rect.origin.y, EXPECT_V_OFFSET);
        // NaN compares false against everything, so both flags fall to `false`.
        assert!(!swap_vert);
        assert!(!swap_horz);
    }
    #[test]
    fn get_rect_with_infinite_positions_does_not_panic() {
        let mut g = graph();
        g.nodes.as_mut()[2].node.position = NodeGraphNodePosition {
            x: f32::INFINITY,
            y: f32::NEG_INFINITY,
        };
        let (rect, swap_vert, swap_horz) = get_rect(&g, connection(N1, 0, N3, 0)).expect("exists");
        assert!(rect.size.width.is_infinite());
        assert!(rect.size.height.is_infinite());
        assert!(!swap_vert, "-inf is not above the output port");
        assert!(!swap_horz, "+inf is not left of the output port");
        // Both endpoints infinite in the same direction => inf - inf => NaN extent.
        g.nodes.as_mut()[0].node.position = NodeGraphNodePosition {
            x: f32::INFINITY,
            y: f32::NEG_INFINITY,
        };
        let (rect, _, _) = get_rect(&g, connection(N1, 0, N3, 0)).expect("exists");
        assert!(rect.size.width.is_nan());
    }
    #[test]
    fn get_rect_is_a_pure_query() {
        let g = graph();
        let before = wiring(&g);
        let _ = get_rect(&g, connection(N1, usize::MAX, N3, 0));
        assert_eq!(wiring(&g), before);
    }
    // ==================================================================
    // 9. render_node
    // ==================================================================
    fn node_dataset(g: &NodeGraph, id: NodeGraphNodeId) -> NodeLocalDataset {
        NodeLocalDataset {
            node_id: id,
            backref: graph_dataset(g),
        }
    }
    fn render_one(g: &NodeGraph, id: NodeGraphNodeId, offset: (f32, f32), scale: f32) -> Dom {
        let n = g
            .nodes
            .iter()
            .find(|n| n.node_id == id)
            .expect("node in fixture");
        let ty = g
            .node_types
            .iter()
            .find(|t| t.node_type_id == n.node.node_type)
            .expect("type in fixture");
        render_node(
            &n.node,
            offset,
            &ty.node_type_info,
            node_dataset(g, id),
            scale,
            node_marker(&"azul-nodegraph-test".into(), id),
        )
    }
    #[test]
    fn render_node_produces_a_single_wrapper_child_carrying_the_dataset() {
        let g = graph();
        let dom = render_one(&g, N1, (0.0, 0.0), 1.0);
        assert_eq!(dom.children.len(), 1);
        let inner = &dom.children.as_slice()[0];
        let mut ds = inner
            .root
            .get_dataset()
            .cloned()
            .expect("the node body must carry its NodeLocalDataset");
        assert!(ds.downcast_ref::<NodeLocalDataset>().is_some());
    }
    #[test]
    fn render_node_survives_every_pathological_scale_factor() {
        // `scale_factor == 1.0` picks a shorter transform list; every other value takes
        // the scale branch, where the f32 is pushed through `PercentageValue::new`.
        let g = graph();
        let baseline = count_nodes(&render_one(&g, N1, (0.0, 0.0), 1.0));
        for scale in [
            0.0,
            -0.0,
            -1.0,
            1e-30,
            f32::MAX,
            f32::MIN,
            f32::EPSILON,
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::NAN,
        ] {
            let dom = render_one(&g, N1, (0.0, 0.0), scale);
            assert_eq!(
                count_nodes(&dom),
                baseline,
                "scale {scale} changed the node structure",
            );
        }
    }
    #[test]
    fn render_node_survives_every_pathological_graph_offset() {
        let g = graph();
        let baseline = count_nodes(&render_one(&g, N1, (0.0, 0.0), 1.0));
        for offset in [
            (f32::NAN, f32::NAN),
            (f32::INFINITY, f32::NEG_INFINITY),
            (f32::MAX, f32::MIN),
            (-1e30, 1e30),
        ] {
            assert_eq!(count_nodes(&render_one(&g, N1, offset, 1.0)), baseline);
        }
    }
    #[test]
    fn render_node_survives_a_node_positioned_at_nan_and_infinity() {
        let mut g = graph();
        g.nodes.as_mut()[0].node.position = NodeGraphNodePosition {
            x: f32::NAN,
            y: f32::INFINITY,
        };
        let dom = render_one(&g, N1, (0.0, 0.0), 1.0);
        assert!(count_nodes(&dom) > 1);
    }
    #[test]
    fn render_node_drops_all_ports_when_the_backref_is_not_a_node_graph_dataset() {
        // Both port lists are built by downcasting through `backref`; a foreign payload
        // must degrade to "no ports" rather than panicking.
        let g = graph();
        let n = g.nodes.iter().find(|n| n.node_id == N1).expect("fixture");
        let ty = g
            .node_types
            .iter()
            .find(|t| t.node_type_id == TYPE_A)
            .expect("fixture");
        let broken = render_node(
            &n.node,
            (0.0, 0.0),
            &ty.node_type_info,
            NodeLocalDataset {
                node_id: N1,
                backref: RefAny::new(0xDEAD_BEEF_u32),
            },
            1.0,
            node_marker(&"azul-nodegraph-test".into(), N1),
        );
        let intact = render_one(&g, N1, (0.0, 0.0), 1.0);
        assert!(count_nodes(&broken) > 1, "the node body still renders");
        assert!(
            count_nodes(&broken) < count_nodes(&intact),
            "a broken backref must cost the ports: {} vs {}",
            count_nodes(&broken),
            count_nodes(&intact),
        );
    }
    #[test]
    fn render_node_drops_ports_whose_io_type_has_no_registered_info() {
        let mut g = graph();
        // Point TYPE_A's single input at an I/O id that has no `InputOutputInfo`.
        g.node_types.as_mut()[0].node_type_info.inputs = vec![IO_COLORLESS].into();
        let stripped = count_nodes(&render_one(&g, N1, (0.0, 0.0), 1.0));
        let intact = count_nodes(&render_one(&graph(), N1, (0.0, 0.0), 1.0));
        assert!(stripped < intact, "{stripped} vs {intact}");
    }
    #[test]
    fn render_node_renders_all_five_field_widget_kinds() {
        let mut g = graph();
        g.nodes.as_mut()[0].node.fields = vec![
            NodeTypeField {
                key: AzString::from_const_str("text"),
                value: NodeTypeFieldValue::TextInput(AzString::from_const_str("hello")),
            },
            NodeTypeField {
                key: AzString::from_const_str("number"),
                value: NodeTypeFieldValue::NumberInput(1.5),
            },
            NodeTypeField {
                key: AzString::from_const_str("check"),
                value: NodeTypeFieldValue::CheckBox(true),
            },
            NodeTypeField {
                key: AzString::from_const_str("color"),
                value: NodeTypeFieldValue::ColorInput(ColorU {
                    r: 9,
                    g: 8,
                    b: 7,
                    a: 6,
                }),
            },
            NodeTypeField {
                key: AzString::from_const_str("file"),
                value: NodeTypeFieldValue::FileInput(OptionString::None),
            },
        ]
        .into();
        let with_fields = count_nodes(&render_one(&g, N1, (0.0, 0.0), 1.0));
        let without = count_nodes(&render_one(&graph(), N1, (0.0, 0.0), 1.0));
        assert!(with_fields > without, "{with_fields} vs {without}");
    }
    #[test]
    fn render_node_field_count_is_monotonic() {
        let base = count_nodes(&render_one(&graph(), N1, (0.0, 0.0), 1.0));
        let mut previous = base;
        for count in 1..=4_usize {
            let mut g = graph();
            g.nodes.as_mut()[0].node.fields = (0..count)
                .map(|_| NodeTypeField {
                    key: AzString::from_const_str("f"),
                    value: NodeTypeFieldValue::CheckBox(false),
                })
                .collect::<Vec<_>>()
                .into();
            let now = count_nodes(&render_one(&g, N1, (0.0, 0.0), 1.0));
            assert!(now > previous, "{count} fields: {now} !> {previous}");
            previous = now;
        }
    }
    #[test]
    fn render_node_accepts_pathological_field_values() {
        // Empty / emoji / RTL / zero-width labels, NaN and infinite numbers, a fully
        // transparent color and a unicode file path.
        let mut g = graph();
        g.nodes.as_mut()[0].node.fields = vec![
            NodeTypeField {
                key: AzString::from_const_str(""),
                value: NodeTypeFieldValue::TextInput(AzString::from_const_str("")),
            },
            NodeTypeField {
                key: AzString::from_const_str("🎉\u{200b}اختبار"),
                value: NodeTypeFieldValue::TextInput(AzString::from_const_str("𝕬\u{0301}\u{feff}")),
            },
            NodeTypeField {
                key: AzString::from_const_str("nan"),
                value: NodeTypeFieldValue::NumberInput(f32::NAN),
            },
            NodeTypeField {
                key: AzString::from_const_str("inf"),
                value: NodeTypeFieldValue::NumberInput(f32::NEG_INFINITY),
            },
            NodeTypeField {
                key: AzString::from_const_str("max"),
                value: NodeTypeFieldValue::NumberInput(f32::MAX),
            },
            NodeTypeField {
                key: AzString::from_const_str("clear"),
                value: NodeTypeFieldValue::ColorInput(ColorU {
                    r: 0,
                    g: 0,
                    b: 0,
                    a: 0,
                }),
            },
            NodeTypeField {
                key: AzString::from_const_str("path"),
                value: NodeTypeFieldValue::FileInput(OptionString::Some(AzString::from_const_str(
                    "/tmp/日本語/🎉.txt",
                ))),
            },
        ]
        .into();
        assert!(count_nodes(&render_one(&g, N1, (f32::NAN, f32::NAN), f32::NAN)) > 1);
    }
    // ==================================================================
    // 10. render_connections
    // ==================================================================
    fn marker() -> AzString {
        "azul-nodegraph-test-connections".into()
    }
    #[test]
    fn render_connections_of_an_unwired_graph_has_no_children() {
        let dom = render_connections(&graph(), marker());
        assert_eq!(dom.children.len(), 0);
        assert!(
            dom.root.get_marker().is_some(),
            "the container must keep the MARKER that drag-handling resolves",
        );
    }
    #[test]
    fn render_connections_emits_exactly_one_child_per_wire() {
        let mut g = graph();
        g.connect_input_output(N3, 0, N1, 0).expect("N1 -> N3");
        assert_eq!(render_connections(&g, marker()).children.len(), 1);
        g.connect_input_output(N4, 0, N1, 0).expect("N1 -> N4");
        assert_eq!(render_connections(&g, marker()).children.len(), 2);
        g.connect_input_output(N4, 0, N3, 0).expect("N3 -> N4");
        assert_eq!(render_connections(&g, marker()).children.len(), 3);
    }
    #[test]
    fn render_connections_skips_a_wire_to_a_node_that_no_longer_exists() {
        // `get_rect` returns `None`; the renderer must drop the wire, not unwrap it.
        let g = force_out_connection(graph(), N1, 0, MISSING, 0);
        assert_eq!(render_connections(&g, marker()).children.len(), 0);
    }
    #[test]
    fn render_connections_skips_an_out_of_range_output_port() {
        for out_idx in [1_usize, 99, usize::MAX] {
            let g = force_out_connection(graph(), N1, out_idx, N3, 0);
            assert_eq!(
                render_connections(&g, marker()).children.len(),
                0,
                "output index {out_idx} must be skipped",
            );
        }
    }
    #[test]
    fn render_connections_skips_a_node_whose_type_is_not_registered() {
        let mut g = graph();
        g.nodes.push(NodeIdNodeMap {
            node_id: NodeGraphNodeId { inner: 50 },
            node: mk_node(TYPE_UNREGISTERED, 0.0, 0.0),
        });
        let g = force_out_connection(g, NodeGraphNodeId { inner: 50 }, 0, N3, 0);
        assert_eq!(render_connections(&g, marker()).children.len(), 0);
    }
    #[test]
    fn render_connections_skips_a_port_whose_io_type_has_no_color() {
        let mut g = graph();
        g.node_types.as_mut()[0].node_type_info.outputs = vec![IO_COLORLESS].into();
        let g = force_out_connection(g, N1, 0, N3, 0);
        assert_eq!(render_connections(&g, marker()).children.len(), 0);
    }
    #[test]
    fn render_connections_survives_nan_positions_and_scale() {
        let mut g = graph();
        g.scale_factor = f32::NAN;
        g.offset = LogicalPosition {
            x: f32::INFINITY,
            y: f32::NAN,
        };
        g.nodes.as_mut()[0].node.position = NodeGraphNodePosition {
            x: f32::NAN,
            y: f32::NAN,
        };
        g.connect_input_output(N3, 0, N1, 0).expect("N1 -> N3");
        assert_eq!(render_connections(&g, marker()).children.len(), 1);
    }
    #[test]
    fn render_connections_renders_a_self_loop() {
        let mut g = graph();
        g.connect_input_output(N1, 0, N1, 0).expect("self loop");
        assert_eq!(render_connections(&g, marker()).children.len(), 1);
    }
    // ==================================================================
    // 11. draw_connection
    // ==================================================================
    #[test]
    fn draw_connection_returns_a_fixed_100x100_null_image() {
        // The real curve rendering is stubbed out pending `RenderImageCallbackInfo`;
        // until then the size is a constant and must not depend on the payload.
        let img = draw_connection(RefAny::new(connection(N1, 0, N3, 0)), ());
        assert_eq!(img.get_size().width, 100.0);
        assert_eq!(img.get_size().height, 100.0);
    }
    #[test]
    fn draw_connection_ignores_a_payload_of_the_wrong_type() {
        for payload in [
            RefAny::new(1_u16),
            RefAny::new(0_u8),
            RefAny::new(String::new()),
        ] {
            let img = draw_connection(payload, ());
            assert_eq!(img.get_size().width, 100.0);
        }
    }
    #[test]
    fn draw_connection_does_not_consume_or_corrupt_its_payload() {
        let cld = RefAny::new(connection(N1, 2, N3, 5));
        let _ = draw_connection(cld.clone(), ());
        let _ = draw_connection(cld.clone(), ());
        let mut probe = cld.clone();
        let read_back = probe
            .downcast_ref::<ConnectionLocalDataset>()
            .expect("payload must still be downcastable after the callback ran");
        assert_eq!(read_back.out_idx, 2);
        assert_eq!(read_back.in_idx, 5);
    }
    #[test]
    fn draw_connection_returns_distinct_image_handles_per_call() {
        let cld = RefAny::new(connection(N1, 0, N3, 0));
        let a = draw_connection(cld.clone(), ());
        let b = draw_connection(cld.clone(), ());
        assert_ne!(a, b, "each call must mint a fresh ImageRef id");
    }
    // ==================================================================
    // 12. NodeGraph::dom
    // ==================================================================
    #[test]
    fn dom_of_a_default_graph_has_the_expected_skeleton() {
        let dom = NodeGraph::default().dom();
        assert!(
            dom.root.get_context_menu().is_some(),
            "the 'add node' context menu is the only way to create nodes",
        );
        assert!(dom.root.get_dataset().is_some());
        assert_eq!(
            dom.children.len(),
            1,
            "wrapper holds exactly the .nodegraph"
        );
        let nodegraph = &dom.children.as_slice()[0];
        assert_eq!(
            nodegraph.children.len(),
            2,
            "connections container + nodes container",
        );
    }
    #[test]
    fn dom_root_dataset_round_trips_back_to_a_node_graph_local_dataset() {
        let dom = graph().dom();
        let mut ds = dom.root.get_dataset().cloned().expect("root dataset");
        let inner = ds
            .downcast_ref::<NodeGraphLocalDataset>()
            .expect("root dataset must be the NodeGraphLocalDataset");
        assert_eq!(inner.node_graph.nodes.len(), 4);
        assert!(inner.last_input_or_output_clicked.is_none());
        assert!(inner.active_node_being_dragged.is_none());
    }
    #[test]
    fn dom_renders_one_child_per_node_and_silently_drops_unregistered_types() {
        let mut g = graph();
        g.nodes.push(NodeIdNodeMap {
            node_id: NodeGraphNodeId { inner: 50 },
            node: mk_node(TYPE_UNREGISTERED, 0.0, 0.0),
        });
        let dom = g.dom();
        let nodes_container = &dom.children.as_slice()[0].children.as_slice()[1];
        assert_eq!(
            nodes_container.children.len(),
            4,
            "the 5th node has no registered type and must be filtered out",
        );
    }
    #[test]
    fn dom_context_menu_lists_one_submenu_entry_per_node_type() {
        let g = graph();
        let dom = g.dom();
        let menu = dom.root.get_context_menu().expect("context menu").clone();
        assert_eq!(menu.items.len(), 1, "one top-level 'add node' entry");
        match &menu.items.as_slice()[0] {
            MenuItem::String(s) => assert_eq!(s.children.len(), 2, "TYPE_A and TYPE_B"),
            other => panic!("expected a string menu item, got {other:?}"),
        }
    }
    #[test]
    fn dom_context_menu_is_present_even_with_no_node_types_at_all() {
        let mut g = graph();
        g.node_types = NodeTypeIdInfoMapVec::new();
        let dom = g.dom();
        let menu = dom.root.get_context_menu().expect("context menu").clone();
        assert_eq!(menu.items.len(), 1);
        match &menu.items.as_slice()[0] {
            MenuItem::String(s) => assert_eq!(s.children.len(), 0),
            other => panic!("expected a string menu item, got {other:?}"),
        }
    }
    #[test]
    fn dom_survives_pathological_scale_offset_and_positions() {
        for (scale, ox, oy) in [
            (f32::NAN, f32::NAN, f32::NAN),
            (0.0, 0.0, 0.0),
            (-1.0, -1e30, 1e30),
            (f32::INFINITY, f32::NEG_INFINITY, f32::INFINITY),
            (f32::MAX, f32::MAX, f32::MIN),
        ] {
            let mut g = graph();
            g.scale_factor = scale;
            g.offset = LogicalPosition { x: ox, y: oy };
            g.nodes.as_mut()[0].node.position = NodeGraphNodePosition {
                x: f32::NAN,
                y: f32::INFINITY,
            };
            g.connect_input_output(N3, 0, N1, 0).expect("N1 -> N3");
            let dom = g.dom();
            assert_eq!(dom.children.len(), 1, "scale {scale}");
        }
    }
    #[test]
    fn dom_of_a_wired_graph_renders_the_connection_container_children() {
        let mut g = graph();
        g.connect_input_output(N3, 0, N1, 0).expect("N1 -> N3");
        let dom = g.dom();
        let connections = &dom.children.as_slice()[0].children.as_slice()[0];
        assert_eq!(connections.children.len(), 1);
    }
    #[test]
    fn dom_can_be_converted_into_a_styled_dom() {
        // `StyledDom::create_from_dom` re-derives the child counters; a mismatch there
        // would panic while building the compact arena.
        let mut g = graph();
        g.connect_input_output(N3, 0, N1, 0).expect("N1 -> N3");
        g.nodes.as_mut()[0].node.fields = vec![NodeTypeField {
            key: AzString::from_const_str("k"),
            value: NodeTypeFieldValue::NumberInput(f32::NAN),
        }]
        .into();
        let styled = StyledDom::create_from_dom(g.dom());
        assert!(styled.node_data.len() > 1);
    }
    // ==================================================================
    // 13. nodegraph_set_active_node / nodegraph_unset_active_node
    // ==================================================================
    #[test]
    fn set_active_node_records_the_node_and_unset_clears_it() {
        let g = graph();
        let gd = graph_dataset(&g);
        let nd = RefAny::new(NodeLocalDataset {
            node_id: N2,
            backref: gd.clone(),
        });
        assert_eq!(
            fire(|info| nodegraph_set_active_node(nd.clone(), info)),
            Update::DoNothing,
        );
        {
            let mut probe = gd.clone();
            let d = probe.downcast_ref::<NodeGraphLocalDataset>().expect("gd");
            assert_eq!(d.active_node_being_dragged, Some(N2),);
        }
        assert_eq!(
            fire(|info| nodegraph_unset_active_node(gd.clone(), info)),
            Update::DoNothing,
        );
        {
            let mut probe = gd.clone();
            let d = probe.downcast_ref::<NodeGraphLocalDataset>().expect("gd");
            assert!(d.active_node_being_dragged.is_none());
        }
    }
    #[test]
    fn set_active_node_ignores_a_payload_of_the_wrong_type() {
        assert_eq!(
            fire(|info| nodegraph_set_active_node(RefAny::new(1_u64), info)),
            Update::DoNothing,
        );
    }
    #[test]
    fn set_active_node_ignores_a_node_dataset_with_a_broken_backref() {
        // The outer downcast succeeds, the inner one does not — no state may change and
        // nothing may panic.
        let nd = RefAny::new(NodeLocalDataset {
            node_id: N2,
            backref: RefAny::new(0_u8),
        });
        assert_eq!(
            fire(|info| nodegraph_set_active_node(nd.clone(), info)),
            Update::DoNothing,
        );
    }
    #[test]
    fn unset_active_node_is_idempotent_and_ignores_wrong_payloads() {
        let g = graph();
        let gd = graph_dataset(&g);
        for _ in 0..3 {
            assert_eq!(
                fire(|info| nodegraph_unset_active_node(gd.clone(), info)),
                Update::DoNothing,
            );
        }
        assert_eq!(
            fire(|info| nodegraph_unset_active_node(RefAny::new(0_i8), info)),
            Update::DoNothing,
        );
    }
    // ==================================================================
    // 14. nodegraph_duplicate_node / nodegraph_delete_node
    // ==================================================================
    #[test]
    fn duplicate_node_is_a_documented_no_op_for_valid_and_invalid_payloads() {
        let g = graph();
        let nd = RefAny::new(NodeLocalDataset {
            node_id: N1,
            backref: graph_dataset(&g),
        });
        assert_eq!(
            fire(|info| nodegraph_duplicate_node(nd.clone(), info)),
            Update::DoNothing,
        );
        assert_eq!(
            fire(|info| nodegraph_duplicate_node(RefAny::new(0_u16), info)),
            Update::DoNothing,
        );
    }
    #[test]
    fn delete_node_forwards_the_node_id_to_on_node_removed() {
        let (g, log) = graph_with_log();
        let nd = RefAny::new(NodeLocalDataset {
            node_id: N3,
            backref: graph_dataset(&g),
        });
        assert_eq!(
            fire(|info| nodegraph_delete_node(nd.clone(), info)),
            Update::RefreshDom,
            "the user callback's Update must be propagated verbatim",
        );
        log_of(&log, |l| assert_eq!(l.removed, vec![N3.inner]));
    }
    #[test]
    fn delete_node_without_a_user_callback_does_nothing() {
        let g = graph();
        let nd = RefAny::new(NodeLocalDataset {
            node_id: N3,
            backref: graph_dataset(&g),
        });
        assert_eq!(
            fire(|info| nodegraph_delete_node(nd.clone(), info)),
            Update::DoNothing,
        );
    }
    #[test]
    fn delete_node_reports_a_node_id_that_is_not_even_in_the_graph() {
        // Documented behaviour: the handler does not validate the id, it just forwards
        // it — removal is entirely the user callback's job.
        let (g, log) = graph_with_log();
        let nd = RefAny::new(NodeLocalDataset {
            node_id: MISSING,
            backref: graph_dataset(&g),
        });
        let _ = fire(|info| nodegraph_delete_node(nd.clone(), info));
        log_of(&log, |l| assert_eq!(l.removed, vec![MISSING.inner]));
    }
    #[test]
    fn delete_node_ignores_broken_payloads() {
        assert_eq!(
            fire(|info| nodegraph_delete_node(RefAny::new(0_u32), info)),
            Update::DoNothing,
        );
        let nd = RefAny::new(NodeLocalDataset {
            node_id: N1,
            backref: RefAny::new(0_u8),
        });
        assert_eq!(
            fire(|info| nodegraph_delete_node(nd.clone(), info)),
            Update::DoNothing,
        );
    }
    // ==================================================================
    // 15. nodegraph_drag_graph_or_nodes
    // ==================================================================
    #[test]
    fn drag_without_a_previous_window_state_does_nothing() {
        // The harness leaves `previous_window_state` as `None`, which is exactly the
        // very-first-event case: no delta can be computed, so nothing may move.
        let (g, _log) = graph_with_log();
        let gd = graph_dataset(&g);
        let before = wiring(&dataset_graph(&gd));
        assert_eq!(
            fire(|info| nodegraph_drag_graph_or_nodes(gd.clone(), info)),
            Update::DoNothing,
        );
        assert_eq!(wiring(&dataset_graph(&gd)), before);
        let after = dataset_graph(&gd);
        assert_eq!(after.offset.x, 0.0);
        assert_eq!(after.offset.y, 0.0);
    }
    #[test]
    fn drag_ignores_a_payload_of_the_wrong_type() {
        assert_eq!(
            fire(|info| nodegraph_drag_graph_or_nodes(RefAny::new(0_u64), info)),
            Update::DoNothing,
        );
    }
    #[test]
    fn drag_does_not_dereference_the_active_node_before_checking_the_mouse() {
        // An "active node" that is not in the graph would be an unwrap hazard if the
        // mouse-state guard were ever reordered after the lookup.
        let g = graph();
        let gd = graph_dataset(&g);
        {
            let mut probe = gd.clone();
            let mut d = probe.downcast_mut::<NodeGraphLocalDataset>().expect("gd");
            d.active_node_being_dragged = Some(MISSING);
        }
        assert_eq!(
            fire(|info| nodegraph_drag_graph_or_nodes(gd.clone(), info)),
            Update::DoNothing,
        );
    }
    // ==================================================================
    // 16. nodegraph_input_output_connect / _disconnect
    // ==================================================================
    fn io_dataset(gd: &RefAny, node_id: NodeGraphNodeId, io: InputOrOutput) -> RefAny {
        RefAny::new(NodeInputOutputLocalDataset {
            io_id: io,
            backref: RefAny::new(NodeLocalDataset {
                node_id,
                backref: gd.clone(),
            }),
        })
    }
    #[test]
    fn connect_click_one_only_arms_the_pending_port() {
        let g = graph();
        let gd = graph_dataset(&g);
        let first = io_dataset(&gd, N1, InputOrOutput::Output(0));
        assert_eq!(
            fire(|info| nodegraph_input_output_connect(first.clone(), info)),
            Update::DoNothing,
        );
        assert_eq!(pending_click(&gd), Some((N1.inner, (false, 0))));
        assert_eq!(
            wiring(&dataset_graph(&gd)),
            wiring(&graph()),
            "arming a port must not wire anything yet",
        );
    }
    #[test]
    fn connect_output_then_input_wires_the_graph_inside_the_dataset() {
        let (g, log) = graph_with_log();
        let gd = graph_dataset(&g);
        let out = io_dataset(&gd, N1, InputOrOutput::Output(0));
        let inn = io_dataset(&gd, N3, InputOrOutput::Input(0));
        let _ = fire(|info| nodegraph_input_output_connect(out.clone(), info));
        assert_eq!(
            fire(|info| nodegraph_input_output_connect(inn.clone(), info)),
            Update::RefreshDom,
        );
        let wired = dataset_graph(&gd);
        assert_eq!(inputs_of(&wired, N3), vec![(0, vec![(N1.inner, 0)])]);
        assert_eq!(outputs_of(&wired, N1), vec![(0, vec![(N3.inner, 0)])]);
        log_of(&log, |l| {
            assert_eq!(l.connected, vec![(N3.inner, 0, N1.inner, 0)]);
        });
        assert_eq!(
            pending_click(&gd),
            None,
            "a completed connection must disarm the pending port",
        );
    }
    #[test]
    fn connect_input_then_output_wires_the_same_edge_in_the_same_direction() {
        // Clicking input-first and output-first must produce identical graphs — the
        // handler swaps the roles itself.
        let (g, _log) = graph_with_log();
        let gd_a = graph_dataset(&g);
        let _ = fire(|info| {
            nodegraph_input_output_connect(io_dataset(&gd_a, N1, InputOrOutput::Output(0)), info)
        });
        let _ = fire(|info| {
            nodegraph_input_output_connect(io_dataset(&gd_a, N3, InputOrOutput::Input(0)), info)
        });
        let gd_b = graph_dataset(&g);
        let _ = fire(|info| {
            nodegraph_input_output_connect(io_dataset(&gd_b, N3, InputOrOutput::Input(0)), info)
        });
        let _ = fire(|info| {
            nodegraph_input_output_connect(io_dataset(&gd_b, N1, InputOrOutput::Output(0)), info)
        });
        assert_eq!(wiring(&dataset_graph(&gd_a)), wiring(&dataset_graph(&gd_b)));
    }
    #[test]
    fn connect_output_to_output_disarms_instead_of_wiring() {
        let (g, log) = graph_with_log();
        let gd = graph_dataset(&g);
        let _ = fire(|info| {
            nodegraph_input_output_connect(io_dataset(&gd, N1, InputOrOutput::Output(0)), info)
        });
        assert_eq!(
            fire(|info| {
                nodegraph_input_output_connect(io_dataset(&gd, N3, InputOrOutput::Output(0)), info)
            }),
            Update::DoNothing,
        );
        assert_eq!(pending_click(&gd), None);
        assert_eq!(wiring(&dataset_graph(&gd)), wiring(&graph()));
        log_of(&log, |l| assert!(l.connected.is_empty()));
    }
    #[test]
    fn connect_input_to_input_disarms_instead_of_wiring() {
        let (g, _log) = graph_with_log();
        let gd = graph_dataset(&g);
        let _ = fire(|info| {
            nodegraph_input_output_connect(io_dataset(&gd, N1, InputOrOutput::Input(0)), info)
        });
        assert_eq!(
            fire(|info| {
                nodegraph_input_output_connect(io_dataset(&gd, N3, InputOrOutput::Input(0)), info)
            }),
            Update::DoNothing,
        );
        assert_eq!(pending_click(&gd), None);
        assert_eq!(wiring(&dataset_graph(&gd)), wiring(&graph()));
    }
    #[test]
    fn connect_across_incompatible_types_disarms_and_leaves_the_graph_alone() {
        let (g, log) = graph_with_log();
        let gd = graph_dataset(&g);
        // N1 emits `int`, N2 consumes `float`.
        let _ = fire(|info| {
            nodegraph_input_output_connect(io_dataset(&gd, N1, InputOrOutput::Output(0)), info)
        });
        assert_eq!(
            fire(|info| {
                nodegraph_input_output_connect(io_dataset(&gd, N2, InputOrOutput::Input(0)), info)
            }),
            Update::DoNothing,
        );
        assert_eq!(pending_click(&gd), None);
        assert_eq!(wiring(&dataset_graph(&gd)), wiring(&graph()));
        log_of(&log, |l| assert!(l.connected.is_empty()));
    }
    #[test]
    fn connect_with_an_out_of_range_port_index_is_rejected() {
        let (g, _log) = graph_with_log();
        let gd = graph_dataset(&g);
        let _ = fire(|info| {
            nodegraph_input_output_connect(
                io_dataset(&gd, N1, InputOrOutput::Output(usize::MAX)),
                info,
            )
        });
        assert_eq!(
            fire(|info| {
                nodegraph_input_output_connect(io_dataset(&gd, N3, InputOrOutput::Input(0)), info)
            }),
            Update::DoNothing,
        );
        assert_eq!(wiring(&dataset_graph(&gd)), wiring(&graph()));
    }
    #[test]
    fn connect_leaves_the_pending_port_armed_when_no_user_callback_is_installed() {
        // BUG (characterised): `last_input_or_output_clicked` is only cleared inside the
        // `Some(OnNodeConnected)` arm. A graph with no `on_node_connected` callback
        // therefore keeps the *first* click armed after a successful wire, so the next
        // port click re-uses the stale port and wires the wrong edge.
        let g = graph(); // no callbacks
        let gd = graph_dataset(&g);
        let _ = fire(|info| {
            nodegraph_input_output_connect(io_dataset(&gd, N1, InputOrOutput::Output(0)), info)
        });
        let _ = fire(|info| {
            nodegraph_input_output_connect(io_dataset(&gd, N3, InputOrOutput::Input(0)), info)
        });
        let wired = dataset_graph(&gd);
        assert_eq!(inputs_of(&wired, N3), vec![(0, vec![(N1.inner, 0)])]);
        assert_eq!(
            pending_click(&gd),
            Some((N1.inner, (false, 0))),
            "N1's output stays armed after the wire was already made",
        );
        // ...and the very next input click silently wires a second edge from it.
        let _ = fire(|info| {
            nodegraph_input_output_connect(io_dataset(&gd, N4, InputOrOutput::Input(0)), info)
        });
        assert_eq!(
            inputs_of(&dataset_graph(&gd), N4),
            vec![(0, vec![(N1.inner, 0)])],
            "the stale port produced an edge the user never armed",
        );
    }
    #[test]
    fn connect_ignores_broken_payloads_at_every_level_of_the_backref_chain() {
        assert_eq!(
            fire(|info| nodegraph_input_output_connect(RefAny::new(0_u32), info)),
            Update::DoNothing,
        );
        let bad_mid = RefAny::new(NodeInputOutputLocalDataset {
            io_id: InputOrOutput::Input(0),
            backref: RefAny::new(0_u8),
        });
        assert_eq!(
            fire(|info| nodegraph_input_output_connect(bad_mid.clone(), info)),
            Update::DoNothing,
        );
        let bad_tail = RefAny::new(NodeInputOutputLocalDataset {
            io_id: InputOrOutput::Input(0),
            backref: RefAny::new(NodeLocalDataset {
                node_id: N1,
                backref: RefAny::new(0_u16),
            }),
        });
        assert_eq!(
            fire(|info| nodegraph_input_output_connect(bad_tail.clone(), info)),
            Update::DoNothing,
        );
    }
    #[test]
    fn disconnect_notifies_the_input_or_the_output_callback_but_never_both() {
        let (g, log) = graph_with_log();
        let gd = graph_dataset(&g);
        assert_eq!(
            fire(|info| {
                nodegraph_input_output_disconnect(
                    io_dataset(&gd, N3, InputOrOutput::Input(4)),
                    info,
                )
            }),
            Update::RefreshDom,
        );
        log_of(&log, |l| {
            assert_eq!(l.input_disconnected, vec![(N3.inner, 4)]);
            assert!(l.output_disconnected.is_empty());
        });
        assert_eq!(
            fire(|info| {
                nodegraph_input_output_disconnect(
                    io_dataset(&gd, N1, InputOrOutput::Output(7)),
                    info,
                )
            }),
            Update::RefreshDomAllWindows,
        );
        log_of(&log, |l| {
            assert_eq!(l.input_disconnected, vec![(N3.inner, 4)]);
            assert_eq!(l.output_disconnected, vec![(N1.inner, 7)]);
        });
    }
    #[test]
    fn disconnect_notifies_but_does_not_actually_unwire_the_graph() {
        // BUG (characterised): the handler calls neither `disconnect_input` nor
        // `disconnect_output`, so the middle-click gesture fires the user callback while
        // the widget's own copy of the graph keeps the edge. Unless the user callback
        // rebuilds the graph, the connection stays on screen.
        let (mut g, _log) = graph_with_log();
        g.connect_input_output(N3, 0, N1, 0).expect("N1 -> N3");
        let gd = graph_dataset(&g);
        let before = wiring(&dataset_graph(&gd));
        let _ = fire(|info| {
            nodegraph_input_output_disconnect(io_dataset(&gd, N3, InputOrOutput::Input(0)), info)
        });
        assert_eq!(
            wiring(&dataset_graph(&gd)),
            before,
            "the model is untouched by the disconnect gesture",
        );
    }
    #[test]
    fn disconnect_without_user_callbacks_does_nothing() {
        let g = graph();
        let gd = graph_dataset(&g);
        assert_eq!(
            fire(|info| {
                nodegraph_input_output_disconnect(
                    io_dataset(&gd, N1, InputOrOutput::Input(0)),
                    info,
                )
            }),
            Update::DoNothing,
        );
        assert_eq!(
            fire(|info| nodegraph_input_output_disconnect(RefAny::new(0_u32), info)),
            Update::DoNothing,
        );
    }
    #[test]
    fn disconnect_forwards_usize_max_port_indices_unclamped() {
        let (g, log) = graph_with_log();
        let gd = graph_dataset(&g);
        let _ = fire(|info| {
            nodegraph_input_output_disconnect(
                io_dataset(&gd, N1, InputOrOutput::Output(usize::MAX)),
                info,
            )
        });
        log_of(&log, |l| {
            assert_eq!(l.output_disconnected, vec![(N1.inner, usize::MAX)]);
        });
    }
    // ==================================================================
    // 17. nodegraph_context_menu_click
    // ==================================================================
    #[test]
    fn context_menu_click_does_nothing_when_the_graph_is_not_in_the_dom() {
        // `get_node_id_by_marker` finds nothing in an empty window, so the handler
        // must bail out before touching the (still valid) backref.
        let (g, log) = graph_with_log();
        let cm = RefAny::new(ContextMenuEntryLocalDataset {
            node_type: TYPE_A,
            backref: graph_dataset(&g),
        });
        assert_eq!(
            fire(|info| nodegraph_context_menu_click(cm.clone(), info)),
            Update::DoNothing,
        );
        log_of(&log, |l| assert!(l.added.is_empty()));
    }
    #[test]
    fn context_menu_click_reports_a_fresh_node_id_at_the_cursor() {
        let (g, log) = graph_with_log();
        let dom = g.dom();
        let gd = dom.root.get_dataset().cloned().expect("root dataset");
        let styled = StyledDom::create_from_dom(dom);
        let cm = RefAny::new(ContextMenuEntryLocalDataset {
            node_type: TYPE_B,
            backref: gd,
        });
        let (update, _) = with_info(styled, hit_none(), |info| {
            nodegraph_context_menu_click(cm.clone(), *info)
        });
        assert_eq!(update, Update::RefreshDomAllWindows);
        log_of(&log, |l| {
            // Cursor is `Uninitialized` and there is no layout, so both the cursor and
            // the wrapper offset are (0, 0) — the position must be exactly zero, not NaN.
            assert_eq!(l.added, vec![(TYPE_B.inner, 5, 0.0, 0.0)]);
        });
    }
    #[test]
    fn context_menu_click_position_degrades_to_nan_at_a_zero_scale_factor() {
        // `1.0 / scale_factor` is `inf` at zero; `0 * inf` is NaN. This pins down what
        // the widget actually hands the user callback in that case.
        let (mut g, log) = graph_with_log();
        g.scale_factor = 0.0;
        let dom = g.dom();
        let gd = dom.root.get_dataset().cloned().expect("root dataset");
        let styled = StyledDom::create_from_dom(dom);
        let cm = RefAny::new(ContextMenuEntryLocalDataset {
            node_type: TYPE_A,
            backref: gd,
        });
        let (_, _) = with_info(styled, hit_none(), |info| {
            nodegraph_context_menu_click(cm.clone(), *info)
        });
        log_of(&log, |l| {
            assert_eq!(l.added.len(), 1);
            let (_, id, x, y) = l.added[0];
            assert_eq!(id, 5, "the id must still be generated normally");
            assert!(x.is_nan() && y.is_nan(), "0 * inf == NaN, got ({x}, {y})");
        });
    }
    #[test]
    fn context_menu_click_ignores_a_payload_of_the_wrong_type() {
        assert_eq!(
            fire(|info| nodegraph_context_menu_click(RefAny::new(0_u32), info)),
            Update::DoNothing,
        );
    }
    // ==================================================================
    // 18. field-edit callbacks
    // ==================================================================
    #[test]
    fn textinput_focus_lost_forwards_the_decoded_text() {
        let (g, log) = graph_with_log();
        let fd = RefAny::new(NodeFieldLocalDataset {
            field_idx: 2,
            backref: RefAny::new(NodeLocalDataset {
                node_id: N2,
                backref: graph_dataset(&g),
            }),
        });
        // 'H', a lone surrogate (never a valid char), then U+1F389 — `get_text` drops
        // the surrogate, so the callback must see exactly "H🎉".
        let state = TextInputState {
            text: vec![0x48_u32, 0xD800, 0x1F389].into(),
            ..TextInputState::default()
        };
        assert_eq!(
            fire(|info| nodegraph_on_textinput_focus_lost(fd.clone(), info, state.clone())),
            Update::RefreshDom,
        );
        log_of(&log, |l| {
            assert_eq!(l.edited, vec![(N2.inner, 2, TYPE_B.inner)]);
            assert_eq!(l.text_values, vec!["H\u{1F389}".to_string()]);
        });
    }
    #[test]
    fn textinput_focus_lost_handles_an_empty_and_an_out_of_range_scalar() {
        let (g, log) = graph_with_log();
        let fd = RefAny::new(NodeFieldLocalDataset {
            field_idx: 0,
            backref: RefAny::new(NodeLocalDataset {
                node_id: N1,
                backref: graph_dataset(&g),
            }),
        });
        for (raw, expected) in [
            (vec![], ""),
            (vec![0x11_0000_u32, 0xFFFF_FFFF], ""), // both above the Unicode range
            (vec![0x0041, 0x0301], "A\u{0301}"),    // combining mark survives
        ] {
            let state = TextInputState {
                text: raw.into(),
                ..TextInputState::default()
            };
            let _ = fire(|info| nodegraph_on_textinput_focus_lost(fd.clone(), info, state.clone()));
            log_of(&log, |l| {
                assert_eq!(l.text_values.last().map(String::as_str), Some(expected));
            });
        }
    }
    #[test]
    fn numberinput_focus_lost_forwards_nan_and_infinities_verbatim() {
        let (g, log) = graph_with_log();
        let fd = RefAny::new(NodeFieldLocalDataset {
            field_idx: 1,
            backref: RefAny::new(NodeLocalDataset {
                node_id: N1,
                backref: graph_dataset(&g),
            }),
        });
        for n in [
            0.0_f32,
            -0.0,
            f32::MAX,
            f32::MIN,
            f32::MIN_POSITIVE,
            f32::EPSILON,
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::NAN,
        ] {
            let state = NumberInputState {
                number: n,
                ..NumberInputState::default()
            };
            assert_eq!(
                fire(|info| nodegraph_on_numberinput_focus_lost(fd.clone(), info, state)),
                Update::RefreshDom,
            );
        }
        log_of(&log, |l| {
            assert_eq!(l.number_values.len(), 9);
            assert_eq!(l.number_values[0], 0.0);
            assert_eq!(l.number_values[2], f32::MAX);
            assert!(l.number_values[6].is_infinite());
            assert!(l.number_values[8].is_nan(), "NaN must not be normalised");
            assert!(l.edited.iter().all(|e| *e == (N1.inner, 1, TYPE_A.inner)));
        });
    }
    #[test]
    fn checkbox_change_forwards_both_states() {
        let (g, log) = graph_with_log();
        let fd = RefAny::new(NodeFieldLocalDataset {
            field_idx: 0,
            backref: RefAny::new(NodeLocalDataset {
                node_id: N1,
                backref: graph_dataset(&g),
            }),
        });
        for checked in [true, false, true] {
            let _ = fire(|info| {
                nodegraph_on_checkbox_value_changed(fd.clone(), info, CheckBoxState { checked })
            });
        }
        log_of(&log, |l| assert_eq!(l.bool_values, vec![true, false, true]));
    }
    #[test]
    fn colorinput_change_forwards_every_channel_including_alpha_extremes() {
        let (g, log) = graph_with_log();
        let fd = RefAny::new(NodeFieldLocalDataset {
            field_idx: 3,
            backref: RefAny::new(NodeLocalDataset {
                node_id: N1,
                backref: graph_dataset(&g),
            }),
        });
        // {1,2,3,4} catches a channel swap that greys would hide; 0 and 255 alpha are
        // the two extremes.
        for c in [
            ColorU {
                r: 1,
                g: 2,
                b: 3,
                a: 4,
            },
            ColorU {
                r: 0,
                g: 0,
                b: 0,
                a: 0,
            },
            ColorU {
                r: 255,
                g: 255,
                b: 255,
                a: 255,
            },
        ] {
            let _ = fire(|info| {
                nodegraph_on_colorinput_value_changed(
                    fd.clone(),
                    info,
                    ColorInputState { color: c },
                )
            });
        }
        log_of(&log, |l| {
            assert_eq!(
                l.color_values,
                vec![(1, 2, 3, 4), (0, 0, 0, 0), (255, 255, 255, 255)],
            );
        });
    }
    #[test]
    fn fileinput_click_forwards_both_a_missing_and_a_unicode_path() {
        let (g, log) = graph_with_log();
        let fd = RefAny::new(NodeFieldLocalDataset {
            field_idx: 4,
            backref: RefAny::new(NodeLocalDataset {
                node_id: N1,
                backref: graph_dataset(&g),
            }),
        });
        let _ = fire(|info| {
            nodegraph_on_fileinput_button_clicked(
                fd.clone(),
                info,
                FileInputState {
                    path: OptionString::None,
                },
            )
        });
        let _ = fire(|info| {
            nodegraph_on_fileinput_button_clicked(
                fd.clone(),
                info,
                FileInputState {
                    path: OptionString::Some(AzString::from_const_str("/tmp/日本語/🎉.txt")),
                },
            )
        });
        log_of(&log, |l| {
            assert_eq!(
                l.file_values,
                vec![None, Some("/tmp/日本語/🎉.txt".to_string())],
            );
        });
    }
    #[test]
    fn field_callbacks_bail_out_when_the_node_is_not_in_the_graph() {
        // Every one of the five handlers looks the node type up first; a stale
        // `node_id` must return `DoNothing` instead of unwrapping.
        let (g, log) = graph_with_log();
        let fd = RefAny::new(NodeFieldLocalDataset {
            field_idx: 0,
            backref: RefAny::new(NodeLocalDataset {
                node_id: MISSING,
                backref: graph_dataset(&g),
            }),
        });
        assert_eq!(
            fire(|info| nodegraph_on_textinput_focus_lost(
                fd.clone(),
                info,
                TextInputState::default()
            )),
            Update::DoNothing,
        );
        assert_eq!(
            fire(|info| nodegraph_on_numberinput_focus_lost(
                fd.clone(),
                info,
                NumberInputState::default()
            )),
            Update::DoNothing,
        );
        assert_eq!(
            fire(|info| nodegraph_on_checkbox_value_changed(
                fd.clone(),
                info,
                CheckBoxState::default()
            )),
            Update::DoNothing,
        );
        assert_eq!(
            fire(|info| nodegraph_on_colorinput_value_changed(
                fd.clone(),
                info,
                ColorInputState::default()
            )),
            Update::DoNothing,
        );
        assert_eq!(
            fire(|info| nodegraph_on_fileinput_button_clicked(
                fd.clone(),
                info,
                FileInputState::default()
            )),
            Update::DoNothing,
        );
        log_of(&log, |l| assert!(l.edited.is_empty()));
    }
    #[test]
    fn field_callbacks_bail_out_on_a_payload_of_the_wrong_type() {
        assert_eq!(
            fire(|info| nodegraph_on_textinput_focus_lost(
                RefAny::new(0_u32),
                info,
                TextInputState::default()
            )),
            Update::DoNothing,
        );
        assert_eq!(
            fire(|info| nodegraph_on_numberinput_focus_lost(
                RefAny::new(0_u32),
                info,
                NumberInputState::default()
            )),
            Update::DoNothing,
        );
        assert_eq!(
            fire(|info| nodegraph_on_checkbox_value_changed(
                RefAny::new(0_u32),
                info,
                CheckBoxState::default()
            )),
            Update::DoNothing,
        );
        assert_eq!(
            fire(|info| nodegraph_on_colorinput_value_changed(
                RefAny::new(0_u32),
                info,
                ColorInputState::default()
            )),
            Update::DoNothing,
        );
        assert_eq!(
            fire(|info| nodegraph_on_fileinput_button_clicked(
                RefAny::new(0_u32),
                info,
                FileInputState::default()
            )),
            Update::DoNothing,
        );
    }
    #[test]
    fn field_callbacks_forward_a_usize_max_field_index_unclamped() {
        // The field index is an opaque token as far as the widget is concerned — it is
        // never used to index anything here, so even `usize::MAX` must pass through.
        let (g, log) = graph_with_log();
        let fd = RefAny::new(NodeFieldLocalDataset {
            field_idx: usize::MAX,
            backref: RefAny::new(NodeLocalDataset {
                node_id: N1,
                backref: graph_dataset(&g),
            }),
        });
        let _ = fire(|info| {
            nodegraph_on_checkbox_value_changed(fd.clone(), info, CheckBoxState { checked: true })
        });
        log_of(&log, |l| {
            assert_eq!(l.edited, vec![(N1.inner, usize::MAX, TYPE_A.inner)]);
        });
    }
    #[test]
    fn field_callbacks_without_a_user_callback_do_nothing() {
        let g = graph(); // no callbacks installed
        let fd = RefAny::new(NodeFieldLocalDataset {
            field_idx: 0,
            backref: RefAny::new(NodeLocalDataset {
                node_id: N1,
                backref: graph_dataset(&g),
            }),
        });
        assert_eq!(
            fire(|info| nodegraph_on_checkbox_value_changed(
                fd.clone(),
                info,
                CheckBoxState::default()
            )),
            Update::DoNothing,
        );
        assert_eq!(
            fire(|info| nodegraph_on_fileinput_button_clicked(
                fd.clone(),
                info,
                FileInputState::default()
            )),
            Update::DoNothing,
        );
    }
}