Skip to main content

ftui_widgets/
drag.rs

1#![forbid(unsafe_code)]
2
3//! Drag-and-drop protocol (bd-1csc.1 + bd-1csc.2).
4//!
5//! Defines the [`Draggable`] trait for drag sources and [`DropTarget`] trait
6//! for drop targets, along with [`DragPayload`] for transferring typed data,
7//! [`DragState`] for tracking active drags, [`DropPosition`] for specifying
8//! where within a target the drop occurs, and [`DropResult`] for communicating
9//! drop outcomes.
10//!
11//! # Design
12//!
13//! ## Integration with Semantic Events
14//!
15//! Drag detection is handled by the gesture recognizer in `ftui-core`, which
16//! emits `SemanticEvent::DragStart`, `DragMove`, `DragEnd`, and `DragCancel`;
17//! its `GestureConfig::drag_threshold` decides when a drag starts. Nothing in
18//! this crate consumes those events for you: the application listens for them,
19//! identifies the source widget by hit-test, and calls the [`Draggable`] and
20//! [`DropTarget`] methods itself. These types are the protocol it uses.
21//!
22//! ## Invariants
23//!
24//! 1. A drag operation is well-formed: exactly one `DragStart` followed by
25//!    zero or more `DragMove` events, ending in either `DragEnd` or
26//!    `DragCancel`.
27//! 2. `on_drag_start` is called exactly once per drag, before any `DragMove`.
28//! 3. `on_drag_end` is called exactly once per drag, with `success = true`
29//!    if dropped on a valid target, `false` otherwise.
30//! 4. `drag_type` must return a stable string for the lifetime of the drag.
31//!
32//! ## Failure Modes
33//!
34//! | Failure | Cause | Fallback |
35//! |---------|-------|----------|
36//! | No hit-test match at drag start | Click outside any draggable | Drag not initiated |
37//! | Payload decode failure | Type mismatch at drop target | Drop rejected |
38//! | Focus loss mid-drag | Window deactivation | `DragCancel` emitted |
39//! | Escape pressed mid-drag | User cancellation | `DragCancel` emitted by the gesture recognizer |
40
41use crate::Widget;
42use crate::measure_cache::WidgetId;
43use ftui_core::geometry::Rect;
44use ftui_core::semantic_event::Position;
45use ftui_render::cell::PackedRgba;
46use ftui_render::frame::Frame;
47use ftui_style::Style;
48
49// ---------------------------------------------------------------------------
50// DragPayload
51// ---------------------------------------------------------------------------
52
53/// Data carried during a drag operation.
54///
55/// The payload uses a MIME-like type string for matching against drop targets
56/// and raw bytes for the actual data. This decouples the drag source from
57/// the drop target — they only need to agree on the type string and byte
58/// format.
59///
60/// # Examples
61///
62/// ```
63/// # use ftui_widgets::drag::DragPayload;
64/// let payload = DragPayload::text("hello world");
65/// assert_eq!(payload.drag_type, "text/plain");
66/// assert_eq!(payload.display_text.as_deref(), Some("hello world"));
67/// ```
68#[derive(Clone, Debug)]
69pub struct DragPayload {
70    /// MIME-like type identifier (e.g., `"text/plain"`, `"widget/list-item"`).
71    pub drag_type: String,
72    /// Raw serialized data.
73    pub data: Vec<u8>,
74    /// Human-readable preview text shown during drag (optional).
75    pub display_text: Option<String>,
76}
77
78impl DragPayload {
79    /// Create a payload with raw bytes.
80    #[must_use]
81    pub fn new(drag_type: impl Into<String>, data: Vec<u8>) -> Self {
82        Self {
83            drag_type: drag_type.into(),
84            data,
85            display_text: None,
86        }
87    }
88
89    /// Create a plain-text payload.
90    #[must_use]
91    pub fn text(text: impl Into<String>) -> Self {
92        let s: String = text.into();
93        let data = s.as_bytes().to_vec();
94        Self {
95            drag_type: "text/plain".to_string(),
96            data,
97            display_text: Some(s),
98        }
99    }
100
101    /// Create a payload with custom display text.
102    #[must_use]
103    pub fn with_display_text(mut self, text: impl Into<String>) -> Self {
104        self.display_text = Some(text.into());
105        self
106    }
107
108    /// Attempt to decode the data as a UTF-8 string.
109    #[must_use]
110    pub fn as_text(&self) -> Option<&str> {
111        std::str::from_utf8(&self.data).ok()
112    }
113
114    /// Returns the byte length of the payload data.
115    #[must_use]
116    pub fn data_len(&self) -> usize {
117        self.data.len()
118    }
119
120    /// Returns true if the payload type matches the given pattern.
121    ///
122    /// Supports exact match and wildcard prefix (e.g., `"text/*"`).
123    #[must_use]
124    pub fn matches_type(&self, pattern: &str) -> bool {
125        if pattern == "*" || pattern == "*/*" {
126            return true;
127        }
128        if let Some(prefix) = pattern.strip_suffix("/*") {
129            self.drag_type.starts_with(prefix)
130                && self.drag_type.as_bytes().get(prefix.len()) == Some(&b'/')
131        } else {
132            self.drag_type == pattern
133        }
134    }
135}
136
137// ---------------------------------------------------------------------------
138// DragState
139// ---------------------------------------------------------------------------
140
141/// Active drag operation state.
142///
143/// Created when a drag starts and destroyed when it ends or is cancelled.
144/// The application's drag handling owns this state.
145pub struct DragState {
146    /// Widget that initiated the drag.
147    pub source_id: WidgetId,
148    /// Data being dragged.
149    pub payload: DragPayload,
150    /// Position where the drag started.
151    pub start_pos: Position,
152    /// Current drag position.
153    pub current_pos: Position,
154    /// Optional custom preview widget.
155    pub preview: Option<Box<dyn Widget>>,
156}
157
158impl std::fmt::Debug for DragState {
159    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160        f.debug_struct("DragState")
161            .field("source_id", &self.source_id)
162            .field("payload", &self.payload)
163            .field("start_pos", &self.start_pos)
164            .field("current_pos", &self.current_pos)
165            .field("preview", &self.preview.as_ref().map(|_| ".."))
166            .finish()
167    }
168}
169
170impl DragState {
171    /// Create a new drag state.
172    #[must_use]
173    pub fn new(source_id: WidgetId, payload: DragPayload, start_pos: Position) -> Self {
174        Self {
175            source_id,
176            payload,
177            start_pos,
178            current_pos: start_pos,
179            preview: None,
180        }
181    }
182
183    /// Set a custom preview widget.
184    #[must_use]
185    pub fn with_preview(mut self, preview: Box<dyn Widget>) -> Self {
186        self.preview = Some(preview);
187        self
188    }
189
190    /// Update the current position during a drag move.
191    pub fn update_position(&mut self, pos: Position) {
192        self.current_pos = pos;
193    }
194
195    /// Manhattan distance from start to current position.
196    #[must_use]
197    pub fn distance(&self) -> u32 {
198        self.start_pos.manhattan_distance(self.current_pos)
199    }
200
201    /// Delta from start to current position as `(dx, dy)`.
202    #[must_use]
203    pub fn delta(&self) -> (i32, i32) {
204        (
205            self.current_pos.x as i32 - self.start_pos.x as i32,
206            self.current_pos.y as i32 - self.start_pos.y as i32,
207        )
208    }
209}
210
211// ---------------------------------------------------------------------------
212// Draggable trait
213// ---------------------------------------------------------------------------
214
215/// Trait for widgets that can be drag sources.
216///
217/// Implement this trait to allow a widget to participate in drag-and-drop
218/// operations. The application's drag handling calls these methods during
219/// the drag lifecycle.
220///
221/// # Example
222///
223/// ```ignore
224/// use ftui_widgets::drag::{Draggable, DragPayload};
225///
226/// struct FileItem { path: String }
227///
228/// impl Draggable for FileItem {
229///     fn drag_type(&self) -> &str { "application/file-path" }
230///
231///     fn drag_data(&self) -> DragPayload {
232///         DragPayload::new("application/file-path", self.path.as_bytes().to_vec())
233///             .with_display_text(&self.path)
234///     }
235/// }
236/// ```
237pub trait Draggable {
238    /// MIME-like type identifier for the dragged data.
239    ///
240    /// Must return a stable string for the lifetime of the drag.
241    /// Examples: `"text/plain"`, `"widget/list-item"`, `"application/file-path"`.
242    fn drag_type(&self) -> &str;
243
244    /// Produce the drag payload.
245    ///
246    /// Called once when the drag starts to capture the data being transferred.
247    fn drag_data(&self) -> DragPayload;
248
249    /// Optional custom preview widget shown during the drag.
250    ///
251    /// Return `None` to use the default text-based preview from
252    /// `DragPayload::display_text`.
253    fn drag_preview(&self) -> Option<Box<dyn Widget>> {
254        None
255    }
256
257    /// Called when a drag operation starts from this widget.
258    ///
259    /// Use this to apply visual feedback (e.g., dim the source item).
260    fn on_drag_start(&mut self) {}
261
262    /// Called when the drag operation ends.
263    ///
264    /// `success` is `true` if the payload was accepted by a drop target,
265    /// `false` if the drag was cancelled or dropped on an invalid target.
266    fn on_drag_end(&mut self, _success: bool) {}
267}
268
269// ---------------------------------------------------------------------------
270// DropPosition
271// ---------------------------------------------------------------------------
272
273/// Where within a drop target the drop will occur.
274///
275/// Used by [`DropTarget::drop_position`] to communicate precise placement
276/// to the drop handler.
277#[derive(Clone, Copy, Debug, PartialEq, Eq)]
278pub enum DropPosition {
279    /// Before the item at the given index.
280    Before(usize),
281    /// After the item at the given index.
282    After(usize),
283    /// Inside the item at the given index (for tree-like targets).
284    Inside(usize),
285    /// Replace the item at the given index.
286    Replace(usize),
287    /// Append to the end of the target's items.
288    Append,
289}
290
291impl DropPosition {
292    /// Returns the index associated with this position, if any.
293    #[must_use]
294    pub fn index(&self) -> Option<usize> {
295        match self {
296            Self::Before(i) | Self::After(i) | Self::Inside(i) | Self::Replace(i) => Some(*i),
297            Self::Append => None,
298        }
299    }
300
301    /// Returns true if this is an insertion position (`Before` or `After`).
302    #[must_use]
303    pub fn is_insertion(&self) -> bool {
304        matches!(self, Self::Before(_) | Self::After(_) | Self::Append)
305    }
306
307    /// Calculate a list drop position from a y coordinate within a list.
308    ///
309    /// Divides each item's height in half: the upper half maps to `Before`,
310    /// the lower half maps to `After`.
311    ///
312    /// # Panics
313    ///
314    /// Panics if `item_height` is zero.
315    #[must_use]
316    pub fn from_list(y: u16, item_height: u16, item_count: usize) -> Self {
317        assert!(item_height > 0, "item_height must be non-zero");
318        if item_count == 0 {
319            return Self::Append;
320        }
321        let item_index = (y / item_height) as usize;
322        if item_index >= item_count {
323            return Self::Append;
324        }
325        let within_item = y % item_height;
326        if within_item < item_height / 2 {
327            Self::Before(item_index)
328        } else {
329            Self::After(item_index)
330        }
331    }
332}
333
334// ---------------------------------------------------------------------------
335// DropResult
336// ---------------------------------------------------------------------------
337
338/// Outcome of a drop operation.
339#[derive(Clone, Debug, PartialEq, Eq)]
340pub enum DropResult {
341    /// Drop was accepted and applied.
342    Accepted,
343    /// Drop was rejected with a reason.
344    Rejected {
345        /// Human-readable explanation for why the drop was rejected.
346        reason: String,
347    },
348}
349
350impl DropResult {
351    /// Create a rejection with the given reason.
352    #[must_use]
353    pub fn rejected(reason: impl Into<String>) -> Self {
354        Self::Rejected {
355            reason: reason.into(),
356        }
357    }
358
359    /// Returns true if the drop was accepted.
360    #[must_use]
361    pub fn is_accepted(&self) -> bool {
362        matches!(self, Self::Accepted)
363    }
364}
365
366// ---------------------------------------------------------------------------
367// DropTarget trait
368// ---------------------------------------------------------------------------
369
370/// Trait for widgets that can accept drops.
371///
372/// Implement this trait to allow a widget to be a drop target. The drag
373/// manager queries these methods during hover and drop to determine
374/// acceptance and placement.
375///
376/// # Example
377///
378/// ```ignore
379/// use ftui_widgets::drag::{DropTarget, DragPayload, DropPosition, DropResult};
380///
381/// struct FileList { files: Vec<String> }
382///
383/// impl DropTarget for FileList {
384///     fn can_accept(&self, drag_type: &str) -> bool {
385///         drag_type == "application/file-path" || drag_type == "text/plain"
386///     }
387///
388///     fn drop_position(&self, pos: Position, _payload: &DragPayload) -> DropPosition {
389///         DropPosition::from_list(pos.y, 1, self.files.len())
390///     }
391///
392///     fn on_drop(&mut self, payload: DragPayload, position: DropPosition) -> DropResult {
393///         if let Some(text) = payload.as_text() {
394///             let idx = match position {
395///                 DropPosition::Before(i) => i,
396///                 DropPosition::After(i) => i + 1,
397///                 DropPosition::Append => self.files.len(),
398///                 _ => return DropResult::rejected("unsupported position"),
399///             };
400///             self.files.insert(idx, text.to_string());
401///             DropResult::Accepted
402///         } else {
403///             DropResult::rejected("expected text payload")
404///         }
405///     }
406/// }
407/// ```
408pub trait DropTarget {
409    /// Check if this target accepts the given drag type.
410    ///
411    /// Called during hover to provide visual feedback (valid vs. invalid
412    /// target). Must be a cheap check — called on every mouse move during
413    /// a drag.
414    fn can_accept(&self, drag_type: &str) -> bool;
415
416    /// Calculate the drop position within this widget.
417    ///
418    /// `pos` is the cursor position relative to the widget's area origin.
419    /// `payload` provides access to the drag data for type-aware positioning.
420    fn drop_position(&self, pos: Position, payload: &DragPayload) -> DropPosition;
421
422    /// Handle the actual drop.
423    ///
424    /// Called when the user releases the mouse button over a valid target.
425    /// Returns [`DropResult::Accepted`] if the drop was handled, or
426    /// [`DropResult::Rejected`] with a reason if it cannot be applied.
427    fn on_drop(&mut self, payload: DragPayload, position: DropPosition) -> DropResult;
428
429    /// Called when a drag enters this target's area.
430    ///
431    /// Use for hover-enter visual feedback.
432    fn on_drag_enter(&mut self) {}
433
434    /// Called when a drag leaves this target's area.
435    ///
436    /// Use to clear hover visual feedback.
437    fn on_drag_leave(&mut self) {}
438
439    /// Accepted drag types as a list of MIME-like patterns.
440    ///
441    /// Override to provide a static list for documentation or introspection.
442    /// Defaults to an empty slice (use `can_accept` for runtime checks).
443    fn accepted_types(&self) -> &[&str] {
444        &[]
445    }
446}
447
448// ---------------------------------------------------------------------------
449// DragPreviewConfig
450// ---------------------------------------------------------------------------
451
452/// Configuration for the drag preview overlay.
453///
454/// Controls visual properties of the widget shown at the cursor during a drag.
455#[derive(Clone, Debug)]
456pub struct DragPreviewConfig {
457    /// Opacity of the preview widget (0.0 = invisible, 1.0 = fully opaque).
458    /// Default: 0.7.
459    pub opacity: f32,
460    /// Horizontal offset from cursor position in cells. Default: 1.
461    pub offset_x: i16,
462    /// Vertical offset from cursor position in cells. Default: 1.
463    pub offset_y: i16,
464    /// Width of the preview area in cells. Default: 20.
465    pub width: u16,
466    /// Height of the preview area in cells. Default: 1.
467    pub height: u16,
468    /// Background color for the preview area.
469    pub background: Option<PackedRgba>,
470    /// Whether to render a border around the preview. Default: false.
471    pub show_border: bool,
472}
473
474impl Default for DragPreviewConfig {
475    fn default() -> Self {
476        Self {
477            opacity: 0.7,
478            offset_x: 1,
479            offset_y: 1,
480            width: 20,
481            height: 1,
482            background: None,
483            show_border: false,
484        }
485    }
486}
487
488impl DragPreviewConfig {
489    /// Set opacity (clamped to 0.0..=1.0).
490    #[must_use]
491    pub fn with_opacity(mut self, opacity: f32) -> Self {
492        self.opacity = opacity.clamp(0.0, 1.0);
493        self
494    }
495
496    /// Set cursor offset.
497    #[must_use]
498    pub fn with_offset(mut self, x: i16, y: i16) -> Self {
499        self.offset_x = x;
500        self.offset_y = y;
501        self
502    }
503
504    /// Set preview dimensions.
505    #[must_use]
506    pub fn with_size(mut self, width: u16, height: u16) -> Self {
507        self.width = width;
508        self.height = height;
509        self
510    }
511
512    /// Set background color.
513    #[must_use]
514    pub fn with_background(mut self, color: PackedRgba) -> Self {
515        self.background = Some(color);
516        self
517    }
518
519    /// Enable border rendering.
520    #[must_use]
521    pub fn with_border(mut self) -> Self {
522        self.show_border = true;
523        self
524    }
525
526    /// Calculate the preview area given cursor position and viewport bounds.
527    ///
528    /// Clamps the preview rectangle to stay within the viewport. Returns
529    /// `None` if the preview would be fully outside the viewport.
530    #[must_use]
531    pub fn preview_rect(&self, cursor: Position, viewport: Rect) -> Option<Rect> {
532        let raw_x = cursor.x as i32 + self.offset_x as i32;
533        let raw_y = cursor.y as i32 + self.offset_y as i32;
534
535        // Clamp to viewport
536        let x = raw_x
537            .max(viewport.x as i32)
538            .min((viewport.x + viewport.width).saturating_sub(self.width) as i32);
539        let y = raw_y
540            .max(viewport.y as i32)
541            .min((viewport.y + viewport.height).saturating_sub(self.height) as i32);
542
543        if x < 0 || y < 0 {
544            return None;
545        }
546
547        let x = x as u16;
548        let y = y as u16;
549
550        // Ensure the rect is within viewport
551        if x >= viewport.x + viewport.width || y >= viewport.y + viewport.height {
552            return None;
553        }
554
555        let w = self.width.min(viewport.x + viewport.width - x);
556        let h = self.height.min(viewport.y + viewport.height - y);
557
558        if w == 0 || h == 0 {
559            return None;
560        }
561
562        Some(Rect::new(x, y, w, h))
563    }
564}
565
566// ---------------------------------------------------------------------------
567// DragPreview
568// ---------------------------------------------------------------------------
569
570/// Overlay widget that renders a drag preview at the cursor position.
571///
572/// The preview renders either a custom widget (from [`DragState::preview`])
573/// or a text-based fallback from [`DragPayload::display_text`].
574///
575/// # Rendering
576///
577/// 1. Pushes the configured opacity onto the buffer's opacity stack.
578/// 2. Optionally fills the background.
579/// 3. Renders the custom preview widget or fallback text.
580/// 4. Optionally draws a border.
581/// 5. Pops the opacity.
582///
583/// # Invariants
584///
585/// - The preview is always clamped to the viewport bounds.
586/// - Opacity is always restored (pop matches push) even if the area is empty.
587/// - At `EssentialOnly` degradation or below, the preview is not rendered
588///   (it is decorative).
589pub struct DragPreview<'a> {
590    /// Current drag state (position, payload, optional custom preview).
591    pub drag_state: &'a DragState,
592    /// Visual configuration.
593    pub config: DragPreviewConfig,
594}
595
596impl<'a> DragPreview<'a> {
597    /// Create a new drag preview for the given state.
598    #[must_use]
599    pub fn new(drag_state: &'a DragState) -> Self {
600        Self {
601            drag_state,
602            config: DragPreviewConfig::default(),
603        }
604    }
605
606    /// Create a drag preview with custom configuration.
607    #[must_use]
608    pub fn with_config(drag_state: &'a DragState, config: DragPreviewConfig) -> Self {
609        Self { drag_state, config }
610    }
611
612    /// Render the fallback text preview.
613    fn render_text_fallback(&self, area: Rect, frame: &mut Frame) {
614        let text = self
615            .drag_state
616            .payload
617            .display_text
618            .as_deref()
619            .or_else(|| self.drag_state.payload.as_text())
620            .unwrap_or("…");
621
622        crate::draw_text_span(
623            frame,
624            area.x,
625            area.y,
626            text,
627            Style::default(),
628            area.x + area.width,
629        );
630    }
631
632    /// Render a simple border around the preview area.
633    fn render_border(&self, area: Rect, frame: &mut Frame) {
634        if area.width < 2 || area.height < 2 {
635            return;
636        }
637
638        let right = area.x + area.width - 1;
639        let bottom = area.y + area.height - 1;
640
641        // Corners
642        frame
643            .buffer
644            .set(area.x, area.y, ftui_render::cell::Cell::from_char('┌'));
645        frame
646            .buffer
647            .set(right, area.y, ftui_render::cell::Cell::from_char('┐'));
648        frame
649            .buffer
650            .set(area.x, bottom, ftui_render::cell::Cell::from_char('└'));
651        frame
652            .buffer
653            .set(right, bottom, ftui_render::cell::Cell::from_char('┘'));
654
655        // Horizontal edges
656        for x in (area.x + 1)..right {
657            frame
658                .buffer
659                .set_fast(x, area.y, ftui_render::cell::Cell::from_char('─'));
660            frame
661                .buffer
662                .set_fast(x, bottom, ftui_render::cell::Cell::from_char('─'));
663        }
664
665        // Vertical edges
666        for y in (area.y + 1)..bottom {
667            frame
668                .buffer
669                .set_fast(area.x, y, ftui_render::cell::Cell::from_char('│'));
670            frame
671                .buffer
672                .set_fast(right, y, ftui_render::cell::Cell::from_char('│'));
673        }
674    }
675}
676
677impl Widget for DragPreview<'_> {
678    fn render(&self, area: Rect, frame: &mut Frame) {
679        if area.is_empty() {
680            return;
681        }
682
683        // Skip decorative preview at degraded rendering levels
684        if !frame.buffer.degradation.render_decorative() {
685            return;
686        }
687
688        let Some(preview_rect) = self.config.preview_rect(self.drag_state.current_pos, area) else {
689            return;
690        };
691
692        // Push opacity for ghost effect
693        frame.buffer.push_opacity(self.config.opacity);
694
695        // Fill background if configured
696        if let Some(bg) = self.config.background {
697            crate::set_style_area(&mut frame.buffer, preview_rect, Style::new().bg(bg));
698        }
699
700        // Render border if enabled (needs to happen before content so content
701        // can render inside the border)
702        if self.config.show_border {
703            self.render_border(preview_rect, frame);
704        }
705
706        // Content area (inset by border if present)
707        let content_rect =
708            if self.config.show_border && preview_rect.width > 2 && preview_rect.height > 2 {
709                Rect::new(
710                    preview_rect.x + 1,
711                    preview_rect.y + 1,
712                    preview_rect.width - 2,
713                    preview_rect.height - 2,
714                )
715            } else {
716                preview_rect
717            };
718
719        // Render custom preview or text fallback
720        if let Some(ref preview_widget) = self.drag_state.preview {
721            preview_widget.render(content_rect, frame);
722        } else {
723            self.render_text_fallback(content_rect, frame);
724        }
725
726        // Restore opacity
727        frame.buffer.pop_opacity();
728    }
729
730    fn is_essential(&self) -> bool {
731        false // Drag preview is decorative
732    }
733}
734
735// ---------------------------------------------------------------------------
736// Tests
737// ---------------------------------------------------------------------------
738
739#[cfg(test)]
740mod tests {
741    use super::*;
742
743    // === DragPayload tests ===
744
745    #[test]
746    fn payload_text_constructor() {
747        let p = DragPayload::text("hello");
748        assert_eq!(p.drag_type, "text/plain");
749        assert_eq!(p.as_text(), Some("hello"));
750        assert_eq!(p.display_text.as_deref(), Some("hello"));
751    }
752
753    #[test]
754    fn payload_raw_bytes() {
755        // 0xFF is never valid in UTF-8
756        let p = DragPayload::new("application/octet-stream", vec![0xFF, 0xFE]);
757        assert_eq!(p.data_len(), 2);
758        assert_eq!(p.data, vec![0xFF, 0xFE]);
759        assert!(p.as_text().is_none()); // not valid UTF-8
760    }
761
762    #[test]
763    fn payload_with_display_text() {
764        let p = DragPayload::new("widget/item", vec![1, 2, 3]).with_display_text("Item #42");
765        assert_eq!(p.display_text.as_deref(), Some("Item #42"));
766    }
767
768    #[test]
769    fn payload_matches_exact_type() {
770        let p = DragPayload::text("test");
771        assert!(p.matches_type("text/plain"));
772        assert!(!p.matches_type("text/html"));
773    }
774
775    #[test]
776    fn payload_matches_wildcard() {
777        let p = DragPayload::text("test");
778        assert!(p.matches_type("text/*"));
779        assert!(p.matches_type("*/*"));
780        assert!(p.matches_type("*"));
781        assert!(!p.matches_type("application/*"));
782    }
783
784    #[test]
785    fn payload_wildcard_requires_slash() {
786        let p = DragPayload::new("textual/data", vec![]);
787        // "text/*" should NOT match "textual/data" — prefix must end at slash
788        assert!(!p.matches_type("text/*"));
789    }
790
791    #[test]
792    fn payload_empty_data() {
793        let p = DragPayload::new("empty/type", vec![]);
794        assert_eq!(p.data_len(), 0);
795        assert_eq!(p.as_text(), Some(""));
796    }
797
798    #[test]
799    fn payload_clone() {
800        let p1 = DragPayload::text("hello").with_display_text("Hello!");
801        let p2 = p1.clone();
802        assert_eq!(p1.drag_type, p2.drag_type);
803        assert_eq!(p1.data, p2.data);
804        assert_eq!(p1.display_text, p2.display_text);
805    }
806
807    // === DragState tests ===
808
809    #[test]
810    fn drag_state_creation() {
811        let state = DragState::new(
812            WidgetId(42),
813            DragPayload::text("dragging"),
814            Position::new(10, 5),
815        );
816        assert_eq!(state.source_id, WidgetId(42));
817        assert_eq!(state.start_pos, Position::new(10, 5));
818        assert_eq!(state.current_pos, Position::new(10, 5));
819        assert!(state.preview.is_none());
820    }
821
822    #[test]
823    fn drag_state_update_position() {
824        let mut state = DragState::new(WidgetId(1), DragPayload::text("test"), Position::new(0, 0));
825        state.update_position(Position::new(5, 3));
826        assert_eq!(state.current_pos, Position::new(5, 3));
827    }
828
829    #[test]
830    fn drag_state_distance() {
831        let mut state = DragState::new(WidgetId(1), DragPayload::text("test"), Position::new(0, 0));
832        state.update_position(Position::new(3, 4));
833        assert_eq!(state.distance(), 7); // manhattan: |3| + |4|
834    }
835
836    #[test]
837    fn drag_state_delta() {
838        let mut state = DragState::new(
839            WidgetId(1),
840            DragPayload::text("test"),
841            Position::new(10, 20),
842        );
843        state.update_position(Position::new(15, 18));
844        assert_eq!(state.delta(), (5, -2));
845    }
846
847    #[test]
848    fn drag_state_zero_distance_at_start() {
849        let state = DragState::new(
850            WidgetId(1),
851            DragPayload::text("test"),
852            Position::new(50, 50),
853        );
854        assert_eq!(state.distance(), 0);
855        assert_eq!(state.delta(), (0, 0));
856    }
857
858    // === Draggable trait tests (via fixtures) ===
859
860    struct DragSourceFixture {
861        label: String,
862        started: bool,
863        ended_with: Option<bool>,
864        log: Vec<String>,
865    }
866
867    impl DragSourceFixture {
868        fn new(label: &str) -> Self {
869            Self {
870                label: label.to_string(),
871                started: false,
872                ended_with: None,
873                log: Vec::new(),
874            }
875        }
876
877        fn drain_log(&mut self) -> Vec<String> {
878            std::mem::take(&mut self.log)
879        }
880    }
881
882    impl Draggable for DragSourceFixture {
883        fn drag_type(&self) -> &str {
884            "text/plain"
885        }
886
887        fn drag_data(&self) -> DragPayload {
888            DragPayload::text(&self.label).with_display_text(&self.label)
889        }
890
891        fn on_drag_start(&mut self) {
892            self.started = true;
893            self.log.push(format!("source:start label={}", self.label));
894        }
895
896        fn on_drag_end(&mut self, success: bool) {
897            self.ended_with = Some(success);
898            self.log.push(format!(
899                "source:end label={} success={}",
900                self.label, success
901            ));
902        }
903    }
904
905    #[test]
906    fn draggable_type_and_data() {
907        let d = DragSourceFixture::new("item-1");
908        assert_eq!(d.drag_type(), "text/plain");
909        let payload = d.drag_data();
910        assert_eq!(
911            payload.as_text(),
912            Some("item-1"),
913            "payload text mismatch for fixture"
914        );
915        assert_eq!(
916            payload.display_text.as_deref(),
917            Some("item-1"),
918            "payload display_text mismatch for fixture"
919        );
920    }
921
922    #[test]
923    fn draggable_default_preview_is_none() {
924        let d = DragSourceFixture::new("item");
925        assert!(d.drag_preview().is_none());
926    }
927
928    #[test]
929    fn draggable_callbacks() {
930        let mut d = DragSourceFixture::new("item");
931        assert!(!d.started);
932        assert!(d.ended_with.is_none());
933
934        d.on_drag_start();
935        assert!(d.started);
936
937        d.on_drag_end(true);
938        assert_eq!(d.ended_with, Some(true));
939        assert_eq!(
940            d.drain_log(),
941            vec![
942                "source:start label=item".to_string(),
943                "source:end label=item success=true".to_string(),
944            ],
945            "unexpected drag log for callbacks"
946        );
947    }
948
949    #[test]
950    fn draggable_callbacks_on_cancel() {
951        let mut d = DragSourceFixture::new("item");
952        d.on_drag_start();
953        d.on_drag_end(false);
954        assert_eq!(d.ended_with, Some(false));
955    }
956
957    // === DropPosition tests ===
958
959    #[test]
960    fn drop_position_index() {
961        assert_eq!(DropPosition::Before(3).index(), Some(3));
962        assert_eq!(DropPosition::After(5).index(), Some(5));
963        assert_eq!(DropPosition::Inside(0).index(), Some(0));
964        assert_eq!(DropPosition::Replace(7).index(), Some(7));
965        assert_eq!(DropPosition::Append.index(), None);
966    }
967
968    #[test]
969    fn drop_position_is_insertion() {
970        assert!(DropPosition::Before(0).is_insertion());
971        assert!(DropPosition::After(0).is_insertion());
972        assert!(DropPosition::Append.is_insertion());
973        assert!(!DropPosition::Inside(0).is_insertion());
974        assert!(!DropPosition::Replace(0).is_insertion());
975    }
976
977    #[test]
978    fn drop_position_from_list_empty() {
979        assert_eq!(DropPosition::from_list(0, 2, 0), DropPosition::Append);
980    }
981
982    #[test]
983    fn drop_position_from_list_upper_half() {
984        // y=0, item_height=4, item_count=3 → within_item=0 < 2 → Before(0)
985        assert_eq!(DropPosition::from_list(0, 4, 3), DropPosition::Before(0));
986        assert_eq!(DropPosition::from_list(1, 4, 3), DropPosition::Before(0));
987    }
988
989    #[test]
990    fn drop_position_from_list_lower_half() {
991        // y=2, item_height=4 → within_item=2 >= 2 → After(0)
992        assert_eq!(DropPosition::from_list(2, 4, 3), DropPosition::After(0));
993        assert_eq!(DropPosition::from_list(3, 4, 3), DropPosition::After(0));
994    }
995
996    #[test]
997    fn drop_position_from_list_second_item() {
998        // y=5, item_height=4 → item_index=1, within_item=1 < 2 → Before(1)
999        assert_eq!(DropPosition::from_list(4, 4, 3), DropPosition::Before(1));
1000        // y=6, item_height=4 → item_index=1, within_item=2 >= 2 → After(1)
1001        assert_eq!(DropPosition::from_list(6, 4, 3), DropPosition::After(1));
1002    }
1003
1004    #[test]
1005    fn drop_position_from_list_beyond_items() {
1006        // y=20, item_height=4, item_count=3 → item_index=5 >= 3 → Append
1007        assert_eq!(DropPosition::from_list(20, 4, 3), DropPosition::Append);
1008    }
1009
1010    #[test]
1011    #[should_panic(expected = "item_height must be non-zero")]
1012    fn drop_position_from_list_zero_height_panics() {
1013        let _ = DropPosition::from_list(0, 0, 5);
1014    }
1015
1016    // === DropResult tests ===
1017
1018    #[test]
1019    fn drop_result_accepted() {
1020        let r = DropResult::Accepted;
1021        assert!(r.is_accepted());
1022    }
1023
1024    #[test]
1025    fn drop_result_rejected() {
1026        let r = DropResult::rejected("type mismatch");
1027        assert!(!r.is_accepted());
1028        match r {
1029            DropResult::Rejected { reason } => assert_eq!(reason, "type mismatch"),
1030            _ => unreachable!("expected Rejected"),
1031        }
1032    }
1033
1034    #[test]
1035    fn drop_result_eq() {
1036        assert_eq!(DropResult::Accepted, DropResult::Accepted);
1037        assert_eq!(
1038            DropResult::rejected("x"),
1039            DropResult::Rejected {
1040                reason: "x".to_string()
1041            }
1042        );
1043        assert_ne!(DropResult::Accepted, DropResult::rejected("y"));
1044    }
1045
1046    // === DropTarget trait tests (via fixtures) ===
1047
1048    struct DropListFixture {
1049        items: Vec<String>,
1050        accepted: Vec<String>,
1051        entered: bool,
1052        log: Vec<String>,
1053    }
1054
1055    impl DropListFixture {
1056        fn new(accepted: &[&str]) -> Self {
1057            Self {
1058                items: Vec::new(),
1059                accepted: accepted.iter().map(|s| s.to_string()).collect(),
1060                entered: false,
1061                log: Vec::new(),
1062            }
1063        }
1064
1065        fn drain_log(&mut self) -> Vec<String> {
1066            std::mem::take(&mut self.log)
1067        }
1068    }
1069
1070    impl DropTarget for DropListFixture {
1071        fn can_accept(&self, drag_type: &str) -> bool {
1072            self.accepted.iter().any(|t| t == drag_type)
1073        }
1074
1075        fn drop_position(&self, pos: Position, _payload: &DragPayload) -> DropPosition {
1076            if self.items.is_empty() {
1077                DropPosition::Append
1078            } else {
1079                DropPosition::from_list(pos.y, 1, self.items.len())
1080            }
1081        }
1082
1083        fn on_drop(&mut self, payload: DragPayload, position: DropPosition) -> DropResult {
1084            if let Some(text) = payload.as_text() {
1085                let idx = match position {
1086                    DropPosition::Before(i) => i,
1087                    DropPosition::After(i) => i + 1,
1088                    DropPosition::Append => self.items.len(),
1089                    _ => return DropResult::rejected("unsupported position"),
1090                };
1091                self.items.insert(idx, text.to_string());
1092                self.log
1093                    .push(format!("target:drop text={text} position={position:?}"));
1094                DropResult::Accepted
1095            } else {
1096                DropResult::rejected("expected text")
1097            }
1098        }
1099
1100        fn on_drag_enter(&mut self) {
1101            self.entered = true;
1102            self.log.push("target:enter".to_string());
1103        }
1104
1105        fn on_drag_leave(&mut self) {
1106            self.entered = false;
1107            self.log.push("target:leave".to_string());
1108        }
1109
1110        fn accepted_types(&self) -> &[&str] {
1111            &[]
1112        }
1113    }
1114
1115    #[test]
1116    fn drop_target_can_accept() {
1117        let target = DropListFixture::new(&["text/plain", "widget/item"]);
1118        assert!(target.can_accept("text/plain"));
1119        assert!(target.can_accept("widget/item"));
1120        assert!(!target.can_accept("image/png"));
1121    }
1122
1123    #[test]
1124    fn drop_target_drop_position_empty() {
1125        let target = DropListFixture::new(&["text/plain"]);
1126        let pos = target.drop_position(Position::new(0, 0), &DragPayload::text("x"));
1127        assert_eq!(pos, DropPosition::Append);
1128    }
1129
1130    #[test]
1131    fn drop_target_on_drop_accepted() {
1132        let mut target = DropListFixture::new(&["text/plain"]);
1133        let result = target.on_drop(DragPayload::text("hello"), DropPosition::Append);
1134        assert!(result.is_accepted());
1135        assert_eq!(target.items, vec!["hello"]);
1136    }
1137
1138    #[test]
1139    fn drop_target_on_drop_insert_before() {
1140        let mut target = DropListFixture::new(&["text/plain"]);
1141        target.items = vec!["a".into(), "b".into()];
1142        let result = target.on_drop(DragPayload::text("x"), DropPosition::Before(1));
1143        assert!(result.is_accepted());
1144        assert_eq!(target.items, vec!["a", "x", "b"]);
1145    }
1146
1147    #[test]
1148    fn drop_target_on_drop_insert_after() {
1149        let mut target = DropListFixture::new(&["text/plain"]);
1150        target.items = vec!["a".into(), "b".into()];
1151        let result = target.on_drop(DragPayload::text("x"), DropPosition::After(0));
1152        assert!(result.is_accepted());
1153        assert_eq!(target.items, vec!["a", "x", "b"]);
1154    }
1155
1156    #[test]
1157    fn drop_target_on_drop_rejected_non_text() {
1158        let mut target = DropListFixture::new(&["application/octet-stream"]);
1159        let payload = DragPayload::new("application/octet-stream", vec![0xFF, 0xFE]);
1160        let result = target.on_drop(payload, DropPosition::Append);
1161        assert!(!result.is_accepted());
1162    }
1163
1164    #[test]
1165    fn drop_target_enter_leave() {
1166        let mut target = DropListFixture::new(&[]);
1167        assert!(!target.entered);
1168        target.on_drag_enter();
1169        assert!(target.entered);
1170        target.on_drag_leave();
1171        assert!(!target.entered);
1172    }
1173
1174    // === DragPreviewConfig tests ===
1175
1176    #[test]
1177    fn preview_config_defaults() {
1178        let cfg = DragPreviewConfig::default();
1179        assert!((cfg.opacity - 0.7).abs() < f32::EPSILON);
1180        assert_eq!(cfg.offset_x, 1);
1181        assert_eq!(cfg.offset_y, 1);
1182        assert_eq!(cfg.width, 20);
1183        assert_eq!(cfg.height, 1);
1184        assert!(cfg.background.is_none());
1185        assert!(!cfg.show_border);
1186    }
1187
1188    #[test]
1189    fn preview_config_builder() {
1190        let cfg = DragPreviewConfig::default()
1191            .with_opacity(0.5)
1192            .with_offset(2, 3)
1193            .with_size(30, 5)
1194            .with_background(PackedRgba::rgb(40, 40, 40))
1195            .with_border();
1196        assert!((cfg.opacity - 0.5).abs() < f32::EPSILON);
1197        assert_eq!(cfg.offset_x, 2);
1198        assert_eq!(cfg.offset_y, 3);
1199        assert_eq!(cfg.width, 30);
1200        assert_eq!(cfg.height, 5);
1201        assert!(cfg.background.is_some());
1202        assert!(cfg.show_border);
1203    }
1204
1205    #[test]
1206    fn preview_config_opacity_clamped() {
1207        let cfg = DragPreviewConfig::default().with_opacity(2.0);
1208        assert!((cfg.opacity - 1.0).abs() < f32::EPSILON);
1209        let cfg = DragPreviewConfig::default().with_opacity(-0.5);
1210        assert!((cfg.opacity - 0.0).abs() < f32::EPSILON);
1211    }
1212
1213    #[test]
1214    fn preview_rect_basic() {
1215        let cfg = DragPreviewConfig::default().with_size(10, 3);
1216        let viewport = Rect::new(0, 0, 80, 24);
1217        let cursor = Position::new(10, 5);
1218        let rect = cfg.preview_rect(cursor, viewport).unwrap();
1219        assert_eq!(rect.x, 11); // cursor.x + offset_x
1220        assert_eq!(rect.y, 6); // cursor.y + offset_y
1221        assert_eq!(rect.width, 10);
1222        assert_eq!(rect.height, 3);
1223    }
1224
1225    #[test]
1226    fn preview_rect_clamped_to_right_edge() {
1227        let cfg = DragPreviewConfig::default().with_size(10, 1);
1228        let viewport = Rect::new(0, 0, 80, 24);
1229        let cursor = Position::new(75, 5);
1230        let rect = cfg.preview_rect(cursor, viewport).unwrap();
1231        // Should be clamped so it doesn't extend past viewport
1232        assert!(rect.x + rect.width <= 80);
1233    }
1234
1235    #[test]
1236    fn preview_rect_clamped_to_bottom_edge() {
1237        let cfg = DragPreviewConfig::default().with_size(10, 3);
1238        let viewport = Rect::new(0, 0, 80, 24);
1239        let cursor = Position::new(5, 22);
1240        let rect = cfg.preview_rect(cursor, viewport).unwrap();
1241        assert!(rect.y + rect.height <= 24);
1242    }
1243
1244    #[test]
1245    fn preview_rect_at_origin() {
1246        let cfg = DragPreviewConfig::default()
1247            .with_offset(0, 0)
1248            .with_size(5, 2);
1249        let viewport = Rect::new(0, 0, 80, 24);
1250        let cursor = Position::new(0, 0);
1251        let rect = cfg.preview_rect(cursor, viewport).unwrap();
1252        assert_eq!(rect.x, 0);
1253        assert_eq!(rect.y, 0);
1254    }
1255
1256    #[test]
1257    fn preview_rect_viewport_offset() {
1258        let cfg = DragPreviewConfig::default()
1259            .with_offset(-5, -5)
1260            .with_size(10, 3);
1261        let viewport = Rect::new(10, 10, 60, 14);
1262        let cursor = Position::new(12, 12);
1263        let rect = cfg.preview_rect(cursor, viewport).unwrap();
1264        // Should clamp to viewport origin
1265        assert!(rect.x >= viewport.x);
1266        assert!(rect.y >= viewport.y);
1267    }
1268
1269    // === DragPreview widget tests ===
1270
1271    #[test]
1272    fn drag_preview_new() {
1273        let state = DragState::new(WidgetId(1), DragPayload::text("hello"), Position::new(5, 5));
1274        let preview = DragPreview::new(&state);
1275        assert!((preview.config.opacity - 0.7).abs() < f32::EPSILON);
1276    }
1277
1278    #[test]
1279    fn drag_preview_with_config() {
1280        let state = DragState::new(WidgetId(1), DragPayload::text("hello"), Position::new(5, 5));
1281        let cfg = DragPreviewConfig::default().with_opacity(0.5);
1282        let preview = DragPreview::with_config(&state, cfg);
1283        assert!((preview.config.opacity - 0.5).abs() < f32::EPSILON);
1284    }
1285
1286    #[test]
1287    fn drag_preview_is_not_essential() {
1288        let state = DragState::new(WidgetId(1), DragPayload::text("hello"), Position::new(5, 5));
1289        let preview = DragPreview::new(&state);
1290        assert!(!preview.is_essential());
1291    }
1292
1293    #[test]
1294    fn drag_preview_render_text_fallback() {
1295        use ftui_render::grapheme_pool::GraphemePool;
1296
1297        let state = DragState::new(
1298            WidgetId(1),
1299            DragPayload::text("dragged item"),
1300            Position::new(5, 5),
1301        );
1302        let preview =
1303            DragPreview::with_config(&state, DragPreviewConfig::default().with_size(20, 1));
1304
1305        let mut pool = GraphemePool::new();
1306        let mut frame = Frame::new(80, 24, &mut pool);
1307        let viewport = Rect::new(0, 0, 80, 24);
1308        preview.render(viewport, &mut frame);
1309
1310        // Text should appear at cursor + offset = (6, 6)
1311        let cell = frame.buffer.get(6, 6).unwrap();
1312        assert_eq!(cell.content.as_char(), Some('d')); // first char of "dragged item"
1313    }
1314
1315    #[test]
1316    fn drag_preview_render_with_border() {
1317        use ftui_render::grapheme_pool::GraphemePool;
1318
1319        let state = DragState::new(WidgetId(1), DragPayload::text("hi"), Position::new(5, 5));
1320        let preview = DragPreview::with_config(
1321            &state,
1322            DragPreviewConfig::default().with_size(10, 3).with_border(),
1323        );
1324
1325        let mut pool = GraphemePool::new();
1326        let mut frame = Frame::new(80, 24, &mut pool);
1327        let viewport = Rect::new(0, 0, 80, 24);
1328        preview.render(viewport, &mut frame);
1329
1330        // Top-left corner should be '┌' at (6, 6)
1331        let corner = frame.buffer.get(6, 6).unwrap();
1332        assert_eq!(corner.content.as_char(), Some('┌'));
1333    }
1334
1335    #[test]
1336    fn drag_preview_empty_area_noop() {
1337        use ftui_render::grapheme_pool::GraphemePool;
1338
1339        let state = DragState::new(WidgetId(1), DragPayload::text("hi"), Position::new(0, 0));
1340        let preview = DragPreview::new(&state);
1341
1342        let mut pool = GraphemePool::new();
1343        let mut frame = Frame::new(80, 24, &mut pool);
1344        // Empty area should not panic
1345        preview.render(Rect::new(0, 0, 0, 0), &mut frame);
1346    }
1347
1348    // === Integration: DragState with Draggable ===
1349
1350    fn run_drag_sequence(
1351        source: &mut DragSourceFixture,
1352        target: Option<&mut DropListFixture>,
1353        start: Position,
1354        moves: &[Position],
1355    ) -> (DragState, Option<DropResult>, Vec<String>) {
1356        let mut log = Vec::new();
1357        log.push(format!("event:start pos=({},{})", start.x, start.y));
1358
1359        source.on_drag_start();
1360        log.extend(source.drain_log());
1361
1362        let payload = source.drag_data();
1363        let mut state = DragState::new(WidgetId(99), payload, start);
1364
1365        for (idx, pos) in moves.iter().enumerate() {
1366            state.update_position(*pos);
1367            log.push(format!(
1368                "event:move#{idx} pos=({},{}) delta={:?}",
1369                pos.x,
1370                pos.y,
1371                state.delta()
1372            ));
1373        }
1374
1375        let drop_result = if let Some(target) = target {
1376            if target.can_accept(&state.payload.drag_type) {
1377                target.on_drag_enter();
1378                log.extend(target.drain_log());
1379                let pos = target.drop_position(state.current_pos, &state.payload);
1380                log.push(format!("event:drop_position={pos:?}"));
1381                let result = target.on_drop(state.payload.clone(), pos);
1382                log.extend(target.drain_log());
1383                target.on_drag_leave();
1384                log.extend(target.drain_log());
1385                source.on_drag_end(result.is_accepted());
1386                log.extend(source.drain_log());
1387                Some(result)
1388            } else {
1389                source.on_drag_end(false);
1390                log.extend(source.drain_log());
1391                None
1392            }
1393        } else {
1394            source.on_drag_end(false);
1395            log.extend(source.drain_log());
1396            None
1397        };
1398
1399        (state, drop_result, log)
1400    }
1401
1402    #[test]
1403    fn full_drag_lifecycle() {
1404        let mut source = DragSourceFixture::new("file.txt");
1405        let moves = [Position::new(10, 8), Position::new(20, 15)];
1406        let (state, result, log) =
1407            run_drag_sequence(&mut source, None, Position::new(5, 5), &moves);
1408
1409        assert!(result.is_none(), "unexpected drop result for no target");
1410        assert_eq!(state.distance(), 25, "distance mismatch after moves");
1411        assert_eq!(source.ended_with, Some(false));
1412        assert_eq!(
1413            state.payload.as_text(),
1414            Some("file.txt"),
1415            "payload text mismatch after drag"
1416        );
1417        assert_eq!(
1418            log,
1419            vec![
1420                "event:start pos=(5,5)".to_string(),
1421                "source:start label=file.txt".to_string(),
1422                "event:move#0 pos=(10,8) delta=(5, 3)".to_string(),
1423                "event:move#1 pos=(20,15) delta=(15, 10)".to_string(),
1424                "source:end label=file.txt success=false".to_string(),
1425            ],
1426            "drag log mismatch"
1427        );
1428    }
1429
1430    #[test]
1431    fn full_drag_and_drop_lifecycle() {
1432        let mut source = DragSourceFixture::new("item-A");
1433        let mut target = DropListFixture::new(&["text/plain"]);
1434        target.items = vec!["existing".into()];
1435
1436        let moves = [Position::new(10, 5)];
1437        let (_state, result, log) =
1438            run_drag_sequence(&mut source, Some(&mut target), Position::new(0, 0), &moves);
1439
1440        let result = match result {
1441            Some(result) => result,
1442            None => unreachable!("expected drop result from target"),
1443        };
1444
1445        assert!(result.is_accepted(), "drop result should be accepted");
1446        assert_eq!(source.ended_with, Some(true));
1447        assert!(!target.entered, "target should be left after drop");
1448        assert_eq!(target.items.len(), 2, "target item count mismatch");
1449        assert_eq!(
1450            log,
1451            vec![
1452                "event:start pos=(0,0)".to_string(),
1453                "source:start label=item-A".to_string(),
1454                "event:move#0 pos=(10,5) delta=(10, 5)".to_string(),
1455                "target:enter".to_string(),
1456                "event:drop_position=Append".to_string(),
1457                "target:drop text=item-A position=Append".to_string(),
1458                "target:leave".to_string(),
1459                "source:end label=item-A success=true".to_string(),
1460            ],
1461            "drag/drop log mismatch"
1462        );
1463    }
1464}