Skip to main content

slint_node_editor/
graph.rs

1use crate::hit_test::{NodeGeometry, SimpleNodeGeometry};
2use crate::state::GeometryCache;
3use slint::{Color, Model, VecModel};
4use std::fmt;
5
6/// Trait for link data to support graph topology and rendering operations.
7///
8/// Implement this trait for your link data type to use with [`crate::LinkManager`]
9/// and other graph operations.
10///
11/// # Example
12///
13/// ```
14/// use slint::Color;
15/// use slint_node_editor::LinkModel;
16///
17/// struct MyLink {
18///     id: i32,
19///     from: i32,
20///     to: i32,
21///     color: Color,
22///     width: f32,
23///     label: String,  // custom field
24/// }
25///
26/// impl LinkModel for MyLink {
27///     fn id(&self) -> i32 { self.id }
28///     fn start_pin_id(&self) -> i32 { self.from }
29///     fn end_pin_id(&self) -> i32 { self.to }
30///     fn color(&self) -> Color { self.color }
31///     fn line_width(&self) -> f32 { self.width }
32/// }
33/// ```
34pub trait LinkModel {
35    /// Unique identifier for the link
36    fn id(&self) -> i32;
37    /// Pin ID where the link starts (typically an output pin)
38    fn start_pin_id(&self) -> i32;
39    /// Pin ID where the link ends (typically an input pin)
40    fn end_pin_id(&self) -> i32;
41    /// Color for rendering the link (default: white).
42    /// Used as fallback when `status()` returns -1 (no status).
43    fn color(&self) -> Color {
44        Color::from_rgb_u8(255, 255, 255)
45    }
46    /// Line width in pixels for rendering the link (default: 2.0)
47    fn line_width(&self) -> f32 {
48        2.0
49    }
50    /// Computation status for the link (default: -1 = no status, use color field).
51    /// When >= 0, the Slint side resolves the color from `LinkStatusColors`.
52    /// Standard values: -1=none, 0=idle, 1=running, 2=succeeded, 3=failed.
53    fn status(&self) -> i32 {
54        -1
55    }
56}
57
58/// The Slint `LinkData` row is the canonical link type, so the library
59/// implements [`LinkModel`] for it directly.
60///
61/// Before `node-editor.slint` was compiled as a library module, `LinkData` was
62/// generated separately into each consumer crate and every consumer wrote this
63/// impl itself. Now the type is ours, so the orphan rule puts the impl here —
64/// and consumers stop repeating it.
65impl LinkModel for crate::nodeeditor::LinkData {
66    fn id(&self) -> i32 {
67        self.id
68    }
69    fn start_pin_id(&self) -> i32 {
70        self.start_pin_id
71    }
72    fn end_pin_id(&self) -> i32 {
73        self.end_pin_id
74    }
75    fn color(&self) -> Color {
76        self.color
77    }
78    fn line_width(&self) -> f32 {
79        self.line_width
80    }
81    fn status(&self) -> i32 {
82        self.status
83    }
84}
85
86/// Simple link data structure implementing [`LinkModel`].
87///
88/// Use this for basic link storage, or implement [`LinkModel`] on your own
89/// type if you need additional fields.
90#[derive(Clone, Debug)]
91pub struct SimpleLink {
92    pub id: i32,
93    pub start_pin_id: i32,
94    pub end_pin_id: i32,
95    pub color: Color,
96    pub line_width: f32,
97    pub status: i32,
98}
99
100impl SimpleLink {
101    /// Create a new link with the specified endpoints, color, and line width.
102    pub fn new(id: i32, start_pin_id: i32, end_pin_id: i32, color: Color) -> Self {
103        Self {
104            id,
105            start_pin_id,
106            end_pin_id,
107            color,
108            line_width: 2.0,
109            status: -1,
110        }
111    }
112
113    /// Create a new link with custom line width.
114    pub fn with_line_width(
115        id: i32,
116        start_pin_id: i32,
117        end_pin_id: i32,
118        color: Color,
119        line_width: f32,
120    ) -> Self {
121        Self {
122            id,
123            start_pin_id,
124            end_pin_id,
125            color,
126            line_width,
127            status: -1,
128        }
129    }
130}
131
132impl LinkModel for SimpleLink {
133    fn id(&self) -> i32 {
134        self.id
135    }
136    fn start_pin_id(&self) -> i32 {
137        self.start_pin_id
138    }
139    fn end_pin_id(&self) -> i32 {
140        self.end_pin_id
141    }
142    fn color(&self) -> Color {
143        self.color
144    }
145    fn line_width(&self) -> f32 {
146        self.line_width
147    }
148    fn status(&self) -> i32 {
149        self.status
150    }
151}
152
153/// Trait for nodes that can be moved (dragged) in the editor.
154/// This allows generic logic to update node positions.
155///
156/// `selected` is part of the contract because a drag commits the *co-selected*
157/// set, not just the dragged node — and it must read that from the same place
158/// the rendering does. The row already carries the flag (the editor renders it
159/// from there); asking a separate set instead is what lets a drag's visuals and
160/// its commit disagree.
161pub trait MovableNode: Clone + 'static {
162    fn id(&self) -> i32;
163    fn x(&self) -> f32;
164    fn y(&self) -> f32;
165    fn selected(&self) -> bool;
166    fn set_x(&mut self, x: f32);
167    fn set_y(&mut self, y: f32);
168}
169
170/// Helper functions for graph operations
171pub struct GraphLogic;
172
173impl GraphLogic {
174    /// Find all links connected to a specific node
175    ///
176    /// # Arguments
177    /// * `node_id` - The ID of the node being deleted/queried
178    /// * `links` - Iterator over the links
179    /// * `cache` - Geometry cache to look up pin ownership
180    pub fn find_links_connected_to_node<I, L, N>(
181        node_id: i32,
182        links: I,
183        cache: &GeometryCache<N>,
184    ) -> Vec<i32>
185    where
186        I: Iterator<Item = L>,
187        L: LinkModel,
188        N: NodeGeometry + Copy,
189    {
190        links
191            .filter(|link| {
192                let start_node = cache
193                    .pin_positions
194                    .get(&link.start_pin_id())
195                    .map(|p| p.node_id);
196                let end_node = cache
197                    .pin_positions
198                    .get(&link.end_pin_id())
199                    .map(|p| p.node_id);
200
201                start_node == Some(node_id) || end_node == Some(node_id)
202            })
203            .map(|l| l.id())
204            .collect()
205    }
206
207    /// Normalize a link so (start, end) is always (Output, Input)
208    ///
209    /// Returns (output_pin_id, input_pin_id), or None if either pin is missing.
210    /// Callers must validate direction compatibility first.
211    pub fn normalize_link_direction<N>(
212        pin_a: i32,
213        pin_b: i32,
214        cache: &GeometryCache<N>,
215        output_type: i32,
216    ) -> Option<(i32, i32)>
217    where
218        N: NodeGeometry + Copy,
219    {
220        let pos_a = cache.pin_positions.get(&pin_a)?;
221        cache.pin_positions.get(&pin_b)?;
222        // Direction compatibility must already have been validated.
223
224        if pos_a.pin_type == output_type {
225            Some((pin_a, pin_b))
226        } else {
227            Some((pin_b, pin_a))
228        }
229    }
230
231    /// Commit a finished drag of `dragged_id` into a node model.
232    ///
233    /// A row moves if it is selected, or if it is the dragged node itself. That
234    /// one rule covers every case without a second source of truth to consult:
235    ///
236    /// - Dragging a node that is part of a multi-selection moves the whole
237    ///   selection, because the editor selects an unselected node before it
238    ///   starts dragging it.
239    /// - A host that wires no selection at all has no selected rows, so only
240    ///   the dragged node moves.
241    /// - Splitting nodes across several models composes: the dragged node lives
242    ///   in exactly one of them and always moves, and selected rows in every
243    ///   model move with it. Call this once per model.
244    pub fn commit_drag<T>(model: &VecModel<T>, dragged_id: i32, delta_x: f32, delta_y: f32)
245    where
246        T: MovableNode,
247    {
248        for i in 0..model.row_count() {
249            if let Some(mut node) = model.row_data(i) {
250                if node.selected() || node.id() == dragged_id {
251                    node.set_x(node.x() + delta_x);
252                    node.set_y(node.y() + delta_y);
253                    model.set_row_data(i, node);
254                }
255            }
256        }
257    }
258
259    /// Check if a link with the given direction already exists
260    ///
261    /// Prevents duplicate connections between the same pins.
262    ///
263    /// # Arguments
264    /// * `start_pin` - Start pin ID
265    /// * `end_pin` - End pin ID
266    /// * `links` - Iterator over existing links
267    pub fn duplicate_link_exists<I, L>(start_pin: i32, end_pin: i32, links: I) -> bool
268    where
269        I: IntoIterator<Item = L>,
270        L: LinkModel,
271    {
272        links
273            .into_iter()
274            .any(|link| link.start_pin_id() == start_pin && link.end_pin_id() == end_pin)
275    }
276
277    /// Find a node by ID in a VecModel using a predicate function
278    ///
279    /// Useful for searching multiple node models when IDs need to be matched
280    /// against specific fields.
281    ///
282    /// # Arguments
283    /// * `model` - The VecModel containing nodes
284    /// * `id` - The ID to search for
285    /// * `predicate` - Function that extracts ID from a node
286    ///
287    /// # Example
288    /// ```
289    /// use slint::VecModel;
290    /// use slint_node_editor::GraphLogic;
291    ///
292    /// #[derive(Clone)]
293    /// struct Node { id: i32 }
294    /// let nodes_model = VecModel::from(vec![Node { id: 42 }]);
295    /// let (index, node) = GraphLogic::find_node_by_id(
296    ///     &nodes_model,
297    ///     42,
298    ///     |n| n.id,
299    /// ).unwrap();
300    /// ```
301    pub fn find_node_by_id<T, F>(model: &VecModel<T>, id: i32, predicate: F) -> Option<(usize, T)>
302    where
303        T: Clone + 'static,
304        F: Fn(&T) -> i32,
305    {
306        for i in 0..model.row_count() {
307            if let Some(node) = model.row_data(i) {
308                if predicate(&node) == id {
309                    return Some((i, node));
310                }
311            }
312        }
313        None
314    }
315}
316
317// ============================================================================
318// Link Validation Framework
319// ============================================================================
320
321/// Result of link validation with optional rejection reason
322#[derive(Debug, Clone, PartialEq, Eq)]
323pub enum ValidationResult {
324    /// Link is valid
325    Valid,
326    /// Link is invalid with a reason
327    Invalid(ValidationError),
328}
329
330impl ValidationResult {
331    /// Check if the result is valid
332    pub fn is_valid(&self) -> bool {
333        matches!(self, ValidationResult::Valid)
334    }
335
336    /// Combine two results (AND logic): returns first error if any
337    pub fn and(self, other: ValidationResult) -> ValidationResult {
338        match self {
339            ValidationResult::Valid => other,
340            invalid => invalid,
341        }
342    }
343}
344
345/// Reasons why a link validation failed
346#[derive(Debug, Clone, PartialEq, Eq)]
347pub enum ValidationError {
348    /// Pin does not exist in the geometry cache
349    PinNotFound(i32),
350    /// Cannot link a pin to itself
351    SamePin,
352    /// Cannot link pins on the same node
353    SameNode,
354    /// Both pins are inputs or both are outputs
355    IncompatibleDirection,
356    /// A link between these pins already exists
357    DuplicateLink,
358    /// Pin has reached maximum connections
359    MaxConnectionsReached { pin_id: i32, max: usize },
360    /// Data types are incompatible
361    TypeMismatch { expected: i32, found: i32 },
362    /// Custom validation failure
363    Custom(String),
364}
365
366/// Endpoints of a valid link in the canonical output-to-input order.
367///
368/// [`validate_and_normalize_link`] returns this value only after basic pin
369/// validation and the supplied topology rules have both succeeded. Using the
370/// returned endpoints for link creation keeps duplicate checks and stored link
371/// direction in agreement regardless of which pin started the gesture.
372#[derive(Debug, Clone, Copy, PartialEq, Eq)]
373pub struct NormalizedLink {
374    /// Output pin ID, suitable for [`LinkModel::start_pin_id`].
375    pub output_pin_id: i32,
376    /// Input pin ID, suitable for [`LinkModel::end_pin_id`].
377    pub input_pin_id: i32,
378}
379
380impl fmt::Display for ValidationError {
381    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382        match self {
383            Self::PinNotFound(id) => write!(f, "Pin {} not found", id),
384            Self::SamePin => write!(f, "Cannot link pin to itself"),
385            Self::SameNode => write!(f, "Cannot link pins on same node"),
386            Self::IncompatibleDirection => write!(f, "Must connect input to output"),
387            Self::DuplicateLink => write!(f, "Link already exists"),
388            Self::MaxConnectionsReached { pin_id, max } => {
389                write!(f, "Pin {} has reached max {} connections", pin_id, max)
390            }
391            Self::TypeMismatch { expected, found } => {
392                write!(f, "Type mismatch: expected {}, found {}", expected, found)
393            }
394            Self::Custom(msg) => write!(f, "{}", msg),
395        }
396    }
397}
398
399impl std::error::Error for ValidationError {}
400
401/// Trait for custom link validation logic.
402///
403/// Implement this to add custom validation rules for connecting pins.
404/// Pass topology rules to [`validate_and_normalize_link`] directly or compose
405/// several rules with [`CompositeValidator`].
406///
407/// The trait is generic over:
408/// - `N`: The node geometry type (defaults to `SimpleNodeGeometry`)
409/// - `L`: The link type for accessing existing links (must implement `LinkModel`)
410///
411/// # Example
412///
413/// ```
414/// use slint_node_editor::{
415///     GeometryCache, LinkValidator, NodeGeometry, ValidationResult,
416/// };
417///
418/// struct MyValidator;
419///
420/// impl<N, L> LinkValidator<N, L> for MyValidator
421/// where
422///     N: NodeGeometry + Copy,
423/// {
424///     fn validate(
425///         &self,
426///         start_pin: i32,
427///         end_pin: i32,
428///         _cache: &GeometryCache<N>,
429///         _links: &[L],
430///     ) -> ValidationResult {
431///         // Custom validation logic
432///         ValidationResult::Valid
433///     }
434/// }
435/// ```
436pub trait LinkValidator<N = SimpleNodeGeometry, L = ()> {
437    /// Check if a link between two pins is valid
438    ///
439    /// # Arguments
440    /// * `start_pin` - ID of the starting pin
441    /// * `end_pin` - ID of the ending pin
442    /// * `cache` - Geometry cache for pin information
443    /// * `links` - Slice of existing links for duplicate/fan-out checks
444    ///
445    /// # Returns
446    /// `ValidationResult::Valid` if the link is allowed,
447    /// `ValidationResult::Invalid(reason)` otherwise
448    fn validate(
449        &self,
450        start_pin: i32,
451        end_pin: i32,
452        cache: &GeometryCache<N>,
453        links: &[L],
454    ) -> ValidationResult;
455}
456
457/// Default validator: checks basic I/O compatibility
458///
459/// This validator implements the standard validation rules:
460/// 1. Pins must exist
461/// 2. Pins must be on different nodes
462/// 3. One pin must be input, one must be output
463///
464/// Returns detailed error information via `ValidationResult`.
465///
466/// # Example
467///
468/// ```
469/// use slint_node_editor::{
470///     BasicLinkValidator, GeometryCache, LinkValidator, SimpleLink,
471///     SimpleNodeGeometry,
472/// };
473///
474/// let mut cache = GeometryCache::<SimpleNodeGeometry>::new();
475/// cache.update_node_rect(1, 0.0, 0.0, 100.0, 60.0);
476/// cache.update_node_rect(2, 200.0, 0.0, 100.0, 60.0);
477/// cache.handle_pin_report(3, 1, 2, 100.0, 30.0);
478/// cache.handle_pin_report(4, 2, 1, 0.0, 30.0);
479/// let links = Vec::<SimpleLink>::new();
480/// let validator = BasicLinkValidator::new(2);
481/// assert!(validator.validate(3, 4, &cache, &links).is_valid());
482/// ```
483#[derive(Clone, Copy, Debug)]
484pub struct BasicLinkValidator {
485    output_type: i32,
486}
487
488impl BasicLinkValidator {
489    /// Create a new basic validator
490    ///
491    /// # Arguments
492    /// * `output_type` - The pin type integer representing "Output"
493    ///   (typically `PinTypes::output` which is 2)
494    pub fn new(output_type: i32) -> Self {
495        Self { output_type }
496    }
497}
498
499impl<N, L> LinkValidator<N, L> for BasicLinkValidator
500where
501    N: NodeGeometry + Copy,
502{
503    fn validate(
504        &self,
505        start_pin: i32,
506        end_pin: i32,
507        cache: &GeometryCache<N>,
508        _links: &[L],
509    ) -> ValidationResult {
510        if start_pin == end_pin {
511            return ValidationResult::Invalid(ValidationError::SamePin);
512        }
513
514        let start_pos = match cache.pin_positions.get(&start_pin) {
515            Some(p) => p,
516            None => return ValidationResult::Invalid(ValidationError::PinNotFound(start_pin)),
517        };
518        let end_pos = match cache.pin_positions.get(&end_pin) {
519            Some(p) => p,
520            None => return ValidationResult::Invalid(ValidationError::PinNotFound(end_pin)),
521        };
522
523        if start_pos.node_id == end_pos.node_id {
524            return ValidationResult::Invalid(ValidationError::SameNode);
525        }
526
527        let start_is_output = start_pos.pin_type == self.output_type;
528        let end_is_output = end_pos.pin_type == self.output_type;
529
530        if start_is_output == end_is_output {
531            return ValidationResult::Invalid(ValidationError::IncompatibleDirection);
532        }
533
534        ValidationResult::Valid
535    }
536}
537
538/// Validate a gesture, normalize it to output-to-input order, then apply
539/// topology rules.
540///
541/// The topology validator always receives `(output_pin_id, input_pin_id)`.
542/// Create the logical link from the returned [`NormalizedLink`] so the exact
543/// endpoints checked for duplicates, fan-out limits, or custom policies are
544/// also the endpoints stored by the host.
545///
546/// # Example
547///
548/// ```
549/// use slint::Color;
550/// use slint_node_editor::{
551///     validate_and_normalize_link, GeometryCache, NoDuplicatesValidator,
552///     NormalizedLink, SimpleLink, SimpleNodeGeometry, ValidationError,
553/// };
554///
555/// let mut cache = GeometryCache::<SimpleNodeGeometry>::new();
556/// cache.update_node_rect(1, 0.0, 0.0, 100.0, 60.0);
557/// cache.update_node_rect(2, 200.0, 0.0, 100.0, 60.0);
558/// cache.handle_pin_report(3, 1, 2, 100.0, 30.0);
559/// cache.handle_pin_report(4, 2, 1, 0.0, 30.0);
560/// let links = vec![SimpleLink::new(1, 3, 4, Color::from_rgb_u8(1, 2, 3))];
561///
562/// assert_eq!(
563///     validate_and_normalize_link(
564///         4,
565///         3,
566///         &cache,
567///         &links,
568///         2,
569///         &NoDuplicatesValidator,
570///     ),
571///     Err(ValidationError::DuplicateLink),
572/// );
573///
574/// let normalized = validate_and_normalize_link(
575///     4,
576///     3,
577///     &cache,
578///     &Vec::<SimpleLink>::new(),
579///     2,
580///     &NoDuplicatesValidator,
581/// )?;
582/// assert_eq!(normalized, NormalizedLink {
583///     output_pin_id: 3,
584///     input_pin_id: 4,
585/// });
586/// # Ok::<(), ValidationError>(())
587/// ```
588pub fn validate_and_normalize_link<N, L, V>(
589    pin_a: i32,
590    pin_b: i32,
591    cache: &GeometryCache<N>,
592    links: &[L],
593    output_type: i32,
594    topology_validator: &V,
595) -> Result<NormalizedLink, ValidationError>
596where
597    N: NodeGeometry + Copy,
598    V: LinkValidator<N, L>,
599{
600    match BasicLinkValidator::new(output_type).validate(pin_a, pin_b, cache, links) {
601        ValidationResult::Valid => {}
602        ValidationResult::Invalid(error) => return Err(error),
603    }
604
605    let Some((output_pin_id, input_pin_id)) =
606        GraphLogic::normalize_link_direction(pin_a, pin_b, cache, output_type)
607    else {
608        return Err(ValidationError::PinNotFound(pin_a));
609    };
610
611    match topology_validator.validate(output_pin_id, input_pin_id, cache, links) {
612        ValidationResult::Valid => Ok(NormalizedLink {
613            output_pin_id,
614            input_pin_id,
615        }),
616        ValidationResult::Invalid(error) => Err(error),
617    }
618}
619
620/// Validator that prevents duplicate links
621///
622/// This wraps the existing `GraphLogic::duplicate_link_exists` helper.
623/// Pass it to [`validate_and_normalize_link`] so gestures that begin at an
624/// input pin are normalized before the ordered pair is checked.
625///
626/// # Example
627///
628/// ```
629/// use slint::{Color};
630/// use slint_node_editor::{
631///     GeometryCache, LinkValidator, NoDuplicatesValidator, SimpleLink,
632///     SimpleNodeGeometry, ValidationResult,
633/// };
634///
635/// let cache = GeometryCache::<SimpleNodeGeometry>::new();
636/// let links = vec![SimpleLink::new(1, 3, 4, Color::from_rgb_u8(1, 2, 3))];
637/// let result = NoDuplicatesValidator.validate(3, 4, &cache, &links);
638/// assert!(matches!(result, ValidationResult::Invalid(_)));
639/// ```
640#[derive(Clone, Debug, Default)]
641pub struct NoDuplicatesValidator;
642
643impl<N, L> LinkValidator<N, L> for NoDuplicatesValidator
644where
645    L: LinkModel + Clone,
646{
647    fn validate(
648        &self,
649        start_pin: i32,
650        end_pin: i32,
651        _cache: &GeometryCache<N>,
652        links: &[L],
653    ) -> ValidationResult {
654        // Use existing helper from GraphLogic
655        if GraphLogic::duplicate_link_exists(start_pin, end_pin, links.iter().cloned()) {
656            ValidationResult::Invalid(ValidationError::DuplicateLink)
657        } else {
658            ValidationResult::Valid
659        }
660    }
661}
662
663/// Composite validator that combines multiple validators
664///
665/// All validators must return Valid for the link to be valid (AND logic).
666/// Returns the first error encountered (short-circuits on failure).
667///
668/// Note: Uses `Vec<Box<dyn ...>>` which allocates. For zero-allocation
669/// validation, chain validators manually using `ValidationResult::and()`.
670///
671/// # Example
672///
673/// ```
674/// use slint_node_editor::{
675///     BasicLinkValidator, CompositeValidator, GeometryCache, LinkValidator,
676///     NoDuplicatesValidator, SimpleLink, SimpleNodeGeometry,
677/// };
678///
679/// let mut cache = GeometryCache::<SimpleNodeGeometry>::new();
680/// cache.update_node_rect(1, 0.0, 0.0, 100.0, 60.0);
681/// cache.update_node_rect(2, 200.0, 0.0, 100.0, 60.0);
682/// cache.handle_pin_report(3, 1, 2, 100.0, 30.0);
683/// cache.handle_pin_report(4, 2, 1, 0.0, 30.0);
684/// let links = Vec::<SimpleLink>::new();
685/// let validator = CompositeValidator::new().with(NoDuplicatesValidator);
686///
687/// let normalized = slint_node_editor::validate_and_normalize_link(
688///     4, 3, &cache, &links, 2, &validator,
689/// ).unwrap();
690/// assert_eq!((normalized.output_pin_id, normalized.input_pin_id), (3, 4));
691/// ```
692pub struct CompositeValidator<N = SimpleNodeGeometry, L = ()> {
693    validators: Vec<Box<dyn LinkValidator<N, L>>>,
694}
695
696impl<N, L> Default for CompositeValidator<N, L> {
697    fn default() -> Self {
698        Self::new()
699    }
700}
701
702impl<N, L> CompositeValidator<N, L> {
703    /// Create a new empty composite validator
704    pub fn new() -> Self {
705        Self {
706            validators: Vec::new(),
707        }
708    }
709
710    /// Add a validator to the composite
711    ///
712    /// Validators are checked in the order they were added.
713    /// The first validator to return Invalid will short-circuit.
714    pub fn with<V: LinkValidator<N, L> + 'static>(mut self, validator: V) -> Self {
715        self.validators.push(Box::new(validator));
716        self
717    }
718}
719
720impl<N, L> LinkValidator<N, L> for CompositeValidator<N, L> {
721    fn validate(
722        &self,
723        start_pin: i32,
724        end_pin: i32,
725        cache: &GeometryCache<N>,
726        links: &[L],
727    ) -> ValidationResult {
728        for v in &self.validators {
729            let result = v.validate(start_pin, end_pin, cache, links);
730            if !result.is_valid() {
731                return result;
732            }
733        }
734        ValidationResult::Valid
735    }
736}
737
738// ============================================================================
739// Tests
740// ============================================================================
741
742#[cfg(test)]
743mod tests {
744    use super::*;
745    use crate::hit_test::SimpleNodeGeometry;
746    use crate::state::StoredPin;
747
748    /// Helper to create a test geometry cache with pins
749    fn setup_cache() -> GeometryCache<SimpleNodeGeometry> {
750        let mut cache = GeometryCache::new();
751
752        // Add two nodes
753        cache.node_rects.insert(
754            1,
755            SimpleNodeGeometry {
756                id: 1,
757                x: 0.0,
758                y: 0.0,
759                width: 100.0,
760                height: 50.0,
761            },
762        );
763        cache.node_rects.insert(
764            2,
765            SimpleNodeGeometry {
766                id: 2,
767                x: 200.0,
768                y: 0.0,
769                width: 100.0,
770                height: 50.0,
771            },
772        );
773
774        // Pin 1001: output on node 1 (pin_type = 2)
775        cache.pin_positions.insert(
776            1001,
777            StoredPin {
778                node_id: 1,
779                pin_type: 2,
780                rel_x: 100.0,
781                rel_y: 25.0,
782            },
783        );
784        // Pin 2001: input on node 2 (pin_type = 1)
785        cache.pin_positions.insert(
786            2001,
787            StoredPin {
788                node_id: 2,
789                pin_type: 1,
790                rel_x: 0.0,
791                rel_y: 25.0,
792            },
793        );
794        // Pin 2002: another input on node 2
795        cache.pin_positions.insert(
796            2002,
797            StoredPin {
798                node_id: 2,
799                pin_type: 1,
800                rel_x: 0.0,
801                rel_y: 40.0,
802            },
803        );
804
805        cache
806    }
807
808    // Test helper that implements LinkModel
809    #[derive(Clone, Debug)]
810    struct TestLink {
811        id: i32,
812        start: i32,
813        end: i32,
814    }
815
816    impl LinkModel for TestLink {
817        fn id(&self) -> i32 {
818            self.id
819        }
820        fn start_pin_id(&self) -> i32 {
821            self.start
822        }
823        fn end_pin_id(&self) -> i32 {
824            self.end
825        }
826    }
827
828    #[test]
829    fn test_basic_validator_accepts_valid_link() {
830        let cache = setup_cache();
831        let validator = BasicLinkValidator::new(2); // output_type = 2
832        let links: Vec<TestLink> = vec![];
833
834        let result = validator.validate(1001, 2001, &cache, &links);
835        assert!(result.is_valid());
836    }
837
838    #[test]
839    fn removed_node_pins_are_no_longer_valid_endpoints() {
840        let mut cache = setup_cache();
841        let validator = BasicLinkValidator::new(2);
842        let links: Vec<TestLink> = vec![];
843
844        cache.remove_node(1);
845
846        assert_eq!(
847            validator.validate(1001, 2001, &cache, &links),
848            ValidationResult::Invalid(ValidationError::PinNotFound(1001))
849        );
850    }
851
852    #[test]
853    fn test_basic_validator_rejects_same_pin() {
854        let cache = setup_cache();
855        let validator = BasicLinkValidator::new(2);
856        let links: Vec<TestLink> = vec![];
857
858        let result = validator.validate(1001, 1001, &cache, &links);
859        assert_eq!(result, ValidationResult::Invalid(ValidationError::SamePin));
860    }
861
862    #[test]
863    fn test_basic_validator_rejects_same_node() {
864        let mut cache = setup_cache();
865        // Add another pin on node 1
866        cache.pin_positions.insert(
867            1002,
868            StoredPin {
869                node_id: 1,
870                pin_type: 1,
871                rel_x: 0.0,
872                rel_y: 25.0,
873            },
874        );
875
876        let validator = BasicLinkValidator::new(2);
877        let links: Vec<TestLink> = vec![];
878
879        let result = validator.validate(1001, 1002, &cache, &links);
880        assert_eq!(result, ValidationResult::Invalid(ValidationError::SameNode));
881    }
882
883    #[test]
884    fn test_basic_validator_rejects_same_direction() {
885        let mut cache = setup_cache();
886        // Add another output on node 2
887        cache.pin_positions.insert(
888            2003,
889            StoredPin {
890                node_id: 2,
891                pin_type: 2,
892                rel_x: 100.0,
893                rel_y: 25.0,
894            },
895        );
896
897        let validator = BasicLinkValidator::new(2);
898        let links: Vec<TestLink> = vec![];
899
900        // Both are outputs
901        let result = validator.validate(1001, 2003, &cache, &links);
902        assert_eq!(
903            result,
904            ValidationResult::Invalid(ValidationError::IncompatibleDirection)
905        );
906    }
907
908    #[test]
909    fn test_basic_validator_rejects_missing_pin() {
910        let cache = setup_cache();
911        let validator = BasicLinkValidator::new(2);
912        let links: Vec<TestLink> = vec![];
913
914        let result = validator.validate(1001, 9999, &cache, &links);
915        assert_eq!(
916            result,
917            ValidationResult::Invalid(ValidationError::PinNotFound(9999))
918        );
919    }
920
921    #[test]
922    fn test_no_duplicates_validator_accepts_new_link() {
923        let cache = setup_cache();
924        let validator = NoDuplicatesValidator;
925        let links = vec![TestLink {
926            id: 1,
927            start: 1001,
928            end: 2002,
929        }];
930
931        // Different link - should pass
932        let result = validator.validate(1001, 2001, &cache, &links);
933        assert!(result.is_valid());
934    }
935
936    #[test]
937    fn test_no_duplicates_validator_rejects_duplicate() {
938        let cache = setup_cache();
939        let validator = NoDuplicatesValidator;
940        let links = vec![TestLink {
941            id: 1,
942            start: 1001,
943            end: 2001,
944        }];
945
946        // Same link - should fail
947        let result = validator.validate(1001, 2001, &cache, &links);
948        assert_eq!(
949            result,
950            ValidationResult::Invalid(ValidationError::DuplicateLink)
951        );
952    }
953
954    #[test]
955    fn validation_returns_the_same_normalized_endpoints_for_both_gesture_directions() {
956        let cache = setup_cache();
957        let links: Vec<TestLink> = vec![];
958
959        let output_first =
960            validate_and_normalize_link(1001, 2001, &cache, &links, 2, &NoDuplicatesValidator);
961        let input_first =
962            validate_and_normalize_link(2001, 1001, &cache, &links, 2, &NoDuplicatesValidator);
963
964        let expected = Ok(NormalizedLink {
965            output_pin_id: 1001,
966            input_pin_id: 2001,
967        });
968        assert_eq!(output_first, expected);
969        assert_eq!(input_first, expected);
970    }
971
972    #[test]
973    fn reverse_gesture_is_rejected_after_normalization_when_link_exists() {
974        let cache = setup_cache();
975        let links = vec![TestLink {
976            id: 1,
977            start: 1001,
978            end: 2001,
979        }];
980
981        assert_eq!(
982            validate_and_normalize_link(2001, 1001, &cache, &links, 2, &NoDuplicatesValidator,),
983            Err(ValidationError::DuplicateLink),
984        );
985    }
986
987    #[test]
988    fn topology_rules_receive_normalized_endpoints() {
989        struct RequireExpectedOrder;
990
991        impl<N, L> LinkValidator<N, L> for RequireExpectedOrder {
992            fn validate(
993                &self,
994                start_pin: i32,
995                end_pin: i32,
996                _cache: &GeometryCache<N>,
997                _links: &[L],
998            ) -> ValidationResult {
999                if (start_pin, end_pin) == (1001, 2001) {
1000                    ValidationResult::Valid
1001                } else {
1002                    ValidationResult::Invalid(ValidationError::Custom(format!(
1003                        "received ({start_pin}, {end_pin})"
1004                    )))
1005                }
1006            }
1007        }
1008
1009        let cache = setup_cache();
1010        let links: Vec<TestLink> = vec![];
1011        assert!(
1012            validate_and_normalize_link(2001, 1001, &cache, &links, 2, &RequireExpectedOrder,)
1013                .is_ok()
1014        );
1015    }
1016
1017    #[test]
1018    fn test_composite_validator_passes_all() {
1019        let cache = setup_cache();
1020        let validator: CompositeValidator<_, TestLink> = CompositeValidator::new()
1021            .with(BasicLinkValidator::new(2))
1022            .with(NoDuplicatesValidator);
1023
1024        let links = vec![];
1025
1026        let result = validator.validate(1001, 2001, &cache, &links);
1027        assert!(result.is_valid());
1028    }
1029
1030    #[test]
1031    fn test_composite_validator_short_circuits_on_basic() {
1032        let cache = setup_cache();
1033        let validator: CompositeValidator<_, TestLink> = CompositeValidator::new()
1034            .with(BasicLinkValidator::new(2))
1035            .with(NoDuplicatesValidator);
1036
1037        let links = vec![];
1038
1039        // Should fail on BasicValidator (same pin)
1040        let result = validator.validate(1001, 1001, &cache, &links);
1041        assert_eq!(result, ValidationResult::Invalid(ValidationError::SamePin));
1042    }
1043
1044    #[test]
1045    fn test_composite_validator_short_circuits_on_duplicates() {
1046        let cache = setup_cache();
1047        let validator: CompositeValidator<_, TestLink> = CompositeValidator::new()
1048            .with(BasicLinkValidator::new(2))
1049            .with(NoDuplicatesValidator);
1050
1051        let links = vec![TestLink {
1052            id: 1,
1053            start: 1001,
1054            end: 2001,
1055        }];
1056
1057        // Should pass BasicValidator but fail on NoDuplicatesValidator
1058        let result = validator.validate(1001, 2001, &cache, &links);
1059        assert_eq!(
1060            result,
1061            ValidationResult::Invalid(ValidationError::DuplicateLink)
1062        );
1063    }
1064
1065    #[test]
1066    fn test_validator_validate_directly() {
1067        let cache = setup_cache();
1068        let validator = BasicLinkValidator::new(2);
1069        let links: Vec<TestLink> = vec![];
1070
1071        let result = validator.validate(1001, 2001, &cache, &links);
1072        assert!(result.is_valid());
1073    }
1074
1075    #[test]
1076    fn test_validation_result_and_combinator() {
1077        let result1 = ValidationResult::Valid;
1078        let result2 = ValidationResult::Valid;
1079        assert!(result1.and(result2).is_valid());
1080
1081        let result1 = ValidationResult::Valid;
1082        let result2 = ValidationResult::Invalid(ValidationError::SamePin);
1083        assert_eq!(
1084            result1.and(result2),
1085            ValidationResult::Invalid(ValidationError::SamePin)
1086        );
1087
1088        let result1 = ValidationResult::Invalid(ValidationError::SameNode);
1089        let result2 = ValidationResult::Valid;
1090        assert_eq!(
1091            result1.and(result2),
1092            ValidationResult::Invalid(ValidationError::SameNode)
1093        );
1094
1095        // First error wins
1096        let result1 = ValidationResult::Invalid(ValidationError::SameNode);
1097        let result2 = ValidationResult::Invalid(ValidationError::SamePin);
1098        assert_eq!(
1099            result1.and(result2),
1100            ValidationResult::Invalid(ValidationError::SameNode)
1101        );
1102    }
1103
1104    #[test]
1105    fn test_validation_error_display() {
1106        assert_eq!(
1107            format!("{}", ValidationError::PinNotFound(42)),
1108            "Pin 42 not found"
1109        );
1110        assert_eq!(
1111            format!("{}", ValidationError::SamePin),
1112            "Cannot link pin to itself"
1113        );
1114        assert_eq!(
1115            format!("{}", ValidationError::SameNode),
1116            "Cannot link pins on same node"
1117        );
1118        assert_eq!(
1119            format!("{}", ValidationError::IncompatibleDirection),
1120            "Must connect input to output"
1121        );
1122        assert_eq!(
1123            format!("{}", ValidationError::DuplicateLink),
1124            "Link already exists"
1125        );
1126        assert_eq!(
1127            format!(
1128                "{}",
1129                ValidationError::MaxConnectionsReached {
1130                    pin_id: 123,
1131                    max: 3
1132                }
1133            ),
1134            "Pin 123 has reached max 3 connections"
1135        );
1136        assert_eq!(
1137            format!(
1138                "{}",
1139                ValidationError::TypeMismatch {
1140                    expected: 1,
1141                    found: 2
1142                }
1143            ),
1144            "Type mismatch: expected 1, found 2"
1145        );
1146        assert_eq!(
1147            format!("{}", ValidationError::Custom("Test error".to_string())),
1148            "Test error"
1149        );
1150    }
1151
1152    /// Test a custom validator implementation
1153    #[test]
1154    fn test_custom_validator() {
1155        #[derive(Clone, Copy)]
1156        struct FanOutValidator {
1157            max_connections: usize,
1158        }
1159
1160        impl<N, L> LinkValidator<N, L> for FanOutValidator
1161        where
1162            L: LinkModel,
1163        {
1164            fn validate(
1165                &self,
1166                start_pin: i32,
1167                _end_pin: i32,
1168                _cache: &GeometryCache<N>,
1169                links: &[L],
1170            ) -> ValidationResult {
1171                let existing_count = links
1172                    .iter()
1173                    .filter(|link| link.start_pin_id() == start_pin)
1174                    .count();
1175
1176                if existing_count >= self.max_connections {
1177                    ValidationResult::Invalid(ValidationError::MaxConnectionsReached {
1178                        pin_id: start_pin,
1179                        max: self.max_connections,
1180                    })
1181                } else {
1182                    ValidationResult::Valid
1183                }
1184            }
1185        }
1186
1187        let cache = setup_cache();
1188        let validator = FanOutValidator { max_connections: 1 };
1189
1190        // One existing link from pin 1001
1191        let existing_links = vec![TestLink {
1192            id: 1,
1193            start: 1001,
1194            end: 2001,
1195        }];
1196
1197        // Second connection should be rejected
1198        let result = validator.validate(1001, 2002, &cache, &existing_links);
1199        assert_eq!(
1200            result,
1201            ValidationResult::Invalid(ValidationError::MaxConnectionsReached {
1202                pin_id: 1001,
1203                max: 1,
1204            })
1205        );
1206
1207        // First connection would have been accepted
1208        let no_links: Vec<TestLink> = vec![];
1209        let result = validator.validate(1001, 2001, &cache, &no_links);
1210        assert!(result.is_valid());
1211    }
1212
1213    // ========================================================================
1214    // GraphLogic::find_links_connected_to_node() tests
1215    // ========================================================================
1216
1217    #[test]
1218    fn test_find_links_connected_to_node_by_start() {
1219        let cache = setup_cache();
1220        let links = vec![
1221            TestLink {
1222                id: 1,
1223                start: 1001,
1224                end: 2001,
1225            },
1226            TestLink {
1227                id: 2,
1228                start: 2001,
1229                end: 1001,
1230            },
1231        ];
1232
1233        // Node 1 owns pin 1001 - link 1 starts from it, link 2 ends at it
1234        let connected = GraphLogic::find_links_connected_to_node(1, links.into_iter(), &cache);
1235        assert!(connected.contains(&1));
1236        assert!(connected.contains(&2));
1237    }
1238
1239    #[test]
1240    fn test_find_links_connected_to_node_no_connections() {
1241        let cache = setup_cache();
1242        let links = vec![TestLink {
1243            id: 1,
1244            start: 1001,
1245            end: 2001,
1246        }];
1247
1248        // Node 999 doesn't exist - no links connected
1249        let connected = GraphLogic::find_links_connected_to_node(999, links.into_iter(), &cache);
1250        assert!(connected.is_empty());
1251    }
1252
1253    #[test]
1254    fn test_find_links_connected_to_node_empty_links() {
1255        let cache = setup_cache();
1256        let links: Vec<TestLink> = vec![];
1257
1258        let connected = GraphLogic::find_links_connected_to_node(1, links.into_iter(), &cache);
1259        assert!(connected.is_empty());
1260    }
1261
1262    #[test]
1263    fn test_find_links_connected_to_node_multiple_pins() {
1264        let mut cache = setup_cache();
1265        // Add another pin on node 1
1266        cache.pin_positions.insert(
1267            1002,
1268            StoredPin {
1269                node_id: 1,
1270                pin_type: 1,
1271                rel_x: 0.0,
1272                rel_y: 40.0,
1273            },
1274        );
1275
1276        let links = vec![
1277            TestLink {
1278                id: 1,
1279                start: 1001,
1280                end: 2001,
1281            },
1282            TestLink {
1283                id: 2,
1284                start: 2001,
1285                end: 1002,
1286            },
1287            TestLink {
1288                id: 3,
1289                start: 2001,
1290                end: 2002,
1291            }, // Not connected to node 1
1292        ];
1293
1294        let connected = GraphLogic::find_links_connected_to_node(1, links.into_iter(), &cache);
1295        assert!(connected.contains(&1));
1296        assert!(connected.contains(&2));
1297        assert!(!connected.contains(&3));
1298    }
1299
1300    // ========================================================================
1301    // GraphLogic::normalize_link_direction() tests
1302    // ========================================================================
1303
1304    #[test]
1305    fn test_normalize_link_direction_output_first() {
1306        let cache = setup_cache();
1307        // Pin 1001 is output (pin_type = 2), pin 2001 is input (pin_type = 1)
1308        let result = GraphLogic::normalize_link_direction(1001, 2001, &cache, 2);
1309        assert_eq!(result, Some((1001, 2001)));
1310    }
1311
1312    #[test]
1313    fn test_normalize_link_direction_input_first() {
1314        let cache = setup_cache();
1315        // Pin 2001 is input, pin 1001 is output - should swap
1316        let result = GraphLogic::normalize_link_direction(2001, 1001, &cache, 2);
1317        assert_eq!(result, Some((1001, 2001)));
1318    }
1319
1320    #[test]
1321    fn test_normalize_link_direction_missing_pin() {
1322        let cache = setup_cache();
1323        let result = GraphLogic::normalize_link_direction(9999, 2001, &cache, 2);
1324        assert!(result.is_none());
1325    }
1326
1327    // ========================================================================
1328    // GraphLogic::duplicate_link_exists() tests
1329    // ========================================================================
1330
1331    #[test]
1332    fn test_duplicate_link_exists_true() {
1333        let links = vec![TestLink {
1334            id: 1,
1335            start: 1001,
1336            end: 2001,
1337        }];
1338        assert!(GraphLogic::duplicate_link_exists(1001, 2001, links));
1339    }
1340
1341    #[test]
1342    fn test_duplicate_link_exists_false() {
1343        let links = vec![TestLink {
1344            id: 1,
1345            start: 1001,
1346            end: 2001,
1347        }];
1348        assert!(!GraphLogic::duplicate_link_exists(1001, 2002, links));
1349    }
1350
1351    #[test]
1352    fn test_duplicate_link_exists_empty() {
1353        let links: Vec<TestLink> = vec![];
1354        assert!(!GraphLogic::duplicate_link_exists(1001, 2001, links));
1355    }
1356
1357    #[test]
1358    fn test_duplicate_link_exists_direction_matters() {
1359        let links = vec![TestLink {
1360            id: 1,
1361            start: 1001,
1362            end: 2001,
1363        }];
1364        // Reversed direction - not a duplicate
1365        assert!(!GraphLogic::duplicate_link_exists(2001, 1001, links));
1366    }
1367
1368    // ========================================================================
1369    // GraphLogic::find_node_by_id() tests
1370    // ========================================================================
1371
1372    #[test]
1373    fn test_find_node_by_id_found() {
1374        #[derive(Clone)]
1375        struct TestNode {
1376            id: i32,
1377            name: String,
1378        }
1379
1380        let model = std::rc::Rc::new(VecModel::from(vec![
1381            TestNode {
1382                id: 1,
1383                name: "Node 1".to_string(),
1384            },
1385            TestNode {
1386                id: 2,
1387                name: "Node 2".to_string(),
1388            },
1389            TestNode {
1390                id: 3,
1391                name: "Node 3".to_string(),
1392            },
1393        ]));
1394
1395        let result = GraphLogic::find_node_by_id(&model, 2, |n| n.id);
1396        assert!(result.is_some());
1397        let (index, node) = result.unwrap();
1398        assert_eq!(index, 1);
1399        assert_eq!(node.id, 2);
1400        assert_eq!(node.name, "Node 2");
1401    }
1402
1403    #[test]
1404    fn test_find_node_by_id_not_found() {
1405        #[derive(Clone)]
1406        struct TestNode {
1407            id: i32,
1408        }
1409
1410        let model = std::rc::Rc::new(VecModel::from(vec![TestNode { id: 1 }, TestNode { id: 2 }]));
1411
1412        let result = GraphLogic::find_node_by_id(&model, 999, |n| n.id);
1413        assert!(result.is_none());
1414    }
1415
1416    #[test]
1417    fn test_find_node_by_id_empty_model() {
1418        #[derive(Clone)]
1419        struct TestNode {
1420            id: i32,
1421        }
1422
1423        let model = std::rc::Rc::new(VecModel::<TestNode>::default());
1424
1425        let result = GraphLogic::find_node_by_id(&model, 1, |n| n.id);
1426        assert!(result.is_none());
1427    }
1428
1429    #[test]
1430    fn test_find_node_by_id_first_match() {
1431        #[derive(Clone)]
1432        struct TestNode {
1433            id: i32,
1434            value: i32,
1435        }
1436
1437        // Two nodes with same id - should return first
1438        let model = std::rc::Rc::new(VecModel::from(vec![
1439            TestNode { id: 1, value: 100 },
1440            TestNode { id: 1, value: 200 },
1441        ]));
1442
1443        let result = GraphLogic::find_node_by_id(&model, 1, |n| n.id);
1444        assert!(result.is_some());
1445        let (index, node) = result.unwrap();
1446        assert_eq!(index, 0);
1447        assert_eq!(node.value, 100);
1448    }
1449
1450    // ========================================================================
1451    // GraphLogic::commit_drag() tests
1452    // ========================================================================
1453
1454    #[derive(Clone)]
1455    struct TestMovableNode {
1456        id: i32,
1457        x: f32,
1458        y: f32,
1459        selected: bool,
1460    }
1461
1462    impl MovableNode for TestMovableNode {
1463        fn id(&self) -> i32 {
1464            self.id
1465        }
1466        fn x(&self) -> f32 {
1467            self.x
1468        }
1469        fn y(&self) -> f32 {
1470            self.y
1471        }
1472        fn selected(&self) -> bool {
1473            self.selected
1474        }
1475        fn set_x(&mut self, x: f32) {
1476            self.x = x;
1477        }
1478        fn set_y(&mut self, y: f32) {
1479            self.y = y;
1480        }
1481    }
1482
1483    /// `(id, x, y, selected)` rows.
1484    fn movable_model(rows: &[(i32, f32, f32, bool)]) -> std::rc::Rc<VecModel<TestMovableNode>> {
1485        std::rc::Rc::new(VecModel::from(
1486            rows.iter()
1487                .map(|&(id, x, y, selected)| TestMovableNode { id, x, y, selected })
1488                .collect::<Vec<_>>(),
1489        ))
1490    }
1491
1492    fn positions(model: &VecModel<TestMovableNode>) -> Vec<(f32, f32)> {
1493        (0..model.row_count())
1494            .filter_map(|i| model.row_data(i))
1495            .map(|n| (n.x, n.y))
1496            .collect()
1497    }
1498
1499    #[test]
1500    fn commit_drag_moves_the_whole_selection() {
1501        let model = movable_model(&[
1502            (1, 0.0, 0.0, true),
1503            (2, 100.0, 100.0, false),
1504            (3, 200.0, 200.0, true),
1505        ]);
1506
1507        GraphLogic::commit_drag(&model, 1, 10.0, 20.0);
1508
1509        // The unselected node 2 stays put.
1510        assert_eq!(
1511            positions(&model),
1512            vec![(10.0, 20.0), (100.0, 100.0), (210.0, 220.0)]
1513        );
1514    }
1515
1516    #[test]
1517    fn commit_drag_moves_the_dragged_node_even_when_nothing_is_selected() {
1518        // A host that wires no selection at all still gets working drags.
1519        let model = movable_model(&[(1, 50.0, 50.0, false), (2, 0.0, 0.0, false)]);
1520
1521        GraphLogic::commit_drag(&model, 1, 100.0, 100.0);
1522
1523        assert_eq!(positions(&model), vec![(150.0, 150.0), (0.0, 0.0)]);
1524    }
1525
1526    #[test]
1527    fn commit_drag_ignores_a_dragged_id_from_another_model() {
1528        // Splitting nodes across models: the dragged node lives in exactly one
1529        // of them, and this call sees only the selected rows of its own.
1530        let model = movable_model(&[(1, 0.0, 0.0, true), (2, 100.0, 100.0, false)]);
1531
1532        GraphLogic::commit_drag(&model, 99, 10.0, 10.0);
1533
1534        assert_eq!(positions(&model), vec![(10.0, 10.0), (100.0, 100.0)]);
1535    }
1536
1537    #[test]
1538    fn commit_drag_does_not_move_a_selected_node_twice() {
1539        // The dragged node is normally selected too — the two clauses of the
1540        // rule must not both fire.
1541        let model = movable_model(&[(1, 0.0, 0.0, true)]);
1542
1543        GraphLogic::commit_drag(&model, 1, 10.0, 20.0);
1544
1545        assert_eq!(positions(&model), vec![(10.0, 20.0)]);
1546    }
1547
1548    #[test]
1549    fn commit_drag_accepts_a_negative_delta() {
1550        let model = movable_model(&[(1, 100.0, 100.0, true)]);
1551
1552        GraphLogic::commit_drag(&model, 1, -50.0, -30.0);
1553
1554        assert_eq!(positions(&model), vec![(50.0, 70.0)]);
1555    }
1556}
1557
1558impl crate::nodeeditor::LinkData {
1559    /// Construct a colored link with no status override and a 2px line width.
1560    /// IDs must follow the editor domains: nonnegative link ID, positive pins.
1561    pub fn new(id: i32, start_pin_id: i32, end_pin_id: i32, color: Color) -> Self {
1562        Self {
1563            id,
1564            start_pin_id,
1565            end_pin_id,
1566            color,
1567            line_width: 2.0,
1568            status: -1,
1569            selected: false,
1570        }
1571    }
1572}
1573
1574#[cfg(test)]
1575mod contract_tests {
1576    use super::*;
1577    #[test]
1578    fn normalization_requires_both_endpoints() {
1579        let mut cache = GeometryCache::<SimpleNodeGeometry>::new();
1580        cache.handle_pin_report(1, 1, 2, 0.0, 0.0);
1581        assert_eq!(GraphLogic::normalize_link_direction(1, 2, &cache, 2), None);
1582        assert_eq!(GraphLogic::normalize_link_direction(2, 1, &cache, 2), None);
1583    }
1584    #[test]
1585    fn colored_link_has_no_status_override() {
1586        let color = Color::from_rgb_u8(1, 2, 3);
1587        let link = crate::LinkData::new(0, 1, 2, color);
1588        assert_eq!(link.color, color);
1589        assert_eq!(link.status, -1);
1590        assert_eq!(link.line_width, 2.0);
1591        assert!(!link.selected);
1592    }
1593}