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