ratatui_toolkit/primitives/split_layout/methods/
move_pane.rs

1use crate::primitives::split_layout::enums::layout_node::LayoutNode;
2use crate::primitives::split_layout::PaneId;
3use crate::primitives::split_layout::SplitLayout;
4
5impl SplitLayout {
6    /// Moves a pane by swapping it with another pane.
7    ///
8    /// # Arguments
9    /// - `pane_id`: The pane to move.
10    /// - `target_pane_id`: The pane that receives the original pane's position.
11    ///
12    /// # Returns
13    /// `true` when both panes exist and the swap completed.
14    ///
15    /// # Errors
16    /// - None.
17    ///
18    /// # Panics
19    /// - Does not panic.
20    ///
21    /// # Safety
22    /// - No safety requirements.
23    ///
24    /// # Performance
25    /// - O(n) to locate both panes.
26    ///
27    /// # Example
28    /// ```rust
29    /// use ratatui_toolkit::primitives::split_layout::SplitLayout;
30    ///
31    /// let mut layout = SplitLayout::new(1);
32    /// let pane_id = layout.split_pane_vertically(1).unwrap();
33    /// let _ = layout.move_pane(1, pane_id);
34    /// ```
35    pub fn move_pane(&mut self, pane_id: PaneId, target_pane_id: PaneId) -> bool {
36        let Some(source_index) = self.find_pane_node_index(pane_id) else {
37            return false;
38        };
39        let Some(target_index) = self.find_pane_node_index(target_pane_id) else {
40            return false;
41        };
42
43        if source_index == target_index {
44            return true;
45        }
46
47        let source_id = match self.nodes.get(source_index) {
48            Some(LayoutNode::Pane { id }) => *id,
49            _ => return false,
50        };
51        let target_id = match self.nodes.get(target_index) {
52            Some(LayoutNode::Pane { id }) => *id,
53            _ => return false,
54        };
55
56        self.nodes[source_index] = LayoutNode::Pane { id: target_id };
57        self.nodes[target_index] = LayoutNode::Pane { id: source_id };
58
59        true
60    }
61}