Skip to main content

crisol_core/state/layout/
node.rs

1//! Editor groups, tabs, and the layout tree.
2
3use std::fmt;
4
5/// A stable editor-group id.
6#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8#[cfg_attr(feature = "serde", serde(transparent))]
9/// # Example
10///
11/// ```
12/// use crisol_core::state::EditorGroupId;
13/// ```
14pub struct EditorGroupId(pub u64);
15
16impl fmt::Display for EditorGroupId {
17    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
18        write!(formatter, "{}", self.0)
19    }
20}
21
22/// How a split lays out its two children.
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
24#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
25#[non_exhaustive]
26/// # Example
27///
28/// ```
29/// use crisol_core::state::SplitDirection;
30/// ```
31pub enum SplitDirection {
32    /// Two columns.
33    #[default]
34    Horizontal,
35    /// Two rows.
36    Vertical,
37}
38
39/// One tab in an editor group.
40#[derive(Clone, Debug, PartialEq)]
41#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
42#[non_exhaustive]
43/// # Example
44///
45/// ```
46/// use crisol_core::state::LayoutTab;
47/// ```
48pub struct LayoutTab {
49    /// Stable application id.
50    pub id: String,
51    /// Tab title.
52    pub title: String,
53    /// Pinned tabs survive "close others" and move with the group.
54    pub pinned: bool,
55    /// A preview tab is replaced by the next preview open.
56    pub preview: bool,
57}
58
59impl LayoutTab {
60    /// A regular tab.
61    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
62        Self {
63            id: id.into(),
64            title: title.into(),
65            pinned: false,
66            preview: false,
67        }
68    }
69
70    /// A pinned tab.
71    pub fn pinned(mut self) -> Self {
72        self.pinned = true;
73        self.preview = false;
74        self
75    }
76
77    /// A preview tab.
78    pub fn preview(mut self) -> Self {
79        self.preview = true;
80        self.pinned = false;
81        self
82    }
83}
84
85/// One editor group.
86#[derive(Clone, Debug, PartialEq)]
87#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
88#[non_exhaustive]
89/// # Example
90///
91/// ```
92/// use crisol_core::state::EditorGroup;
93/// ```
94pub struct EditorGroup {
95    /// Stable id.
96    pub id: EditorGroupId,
97    /// Tabs in order.
98    pub tabs: Vec<LayoutTab>,
99    /// Active tab index.
100    pub active: usize,
101}
102
103impl EditorGroup {
104    /// An empty group.
105    pub fn new(id: EditorGroupId) -> Self {
106        Self {
107            id,
108            tabs: Vec::new(),
109            active: 0,
110        }
111    }
112
113    /// A group with tabs, the first active.
114    pub fn with_tabs(id: EditorGroupId, tabs: Vec<LayoutTab>) -> Self {
115        Self { id, tabs, active: 0 }
116    }
117
118    /// The active tab.
119    pub fn active_tab(&self) -> Option<&LayoutTab> {
120        self.tabs.get(self.active)
121    }
122
123    /// Clamp the active index after a removal or a load.
124    pub fn normalize(&mut self) {
125        if self.tabs.is_empty() {
126            self.active = 0;
127        } else {
128            self.active = self.active.min(self.tabs.len() - 1);
129        }
130    }
131}
132
133/// A node of the layout tree.
134#[derive(Clone, Debug, PartialEq)]
135#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
136#[cfg_attr(feature = "serde", serde(tag = "kind", rename_all = "snake_case"))]
137#[non_exhaustive]
138/// # Example
139///
140/// ```
141/// use crisol_core::state::LayoutNode;
142/// ```
143pub enum LayoutNode {
144    /// A leaf with an editor group.
145    Group(EditorGroup),
146    /// Two children side by side or stacked.
147    Split {
148        /// Direction.
149        direction: SplitDirection,
150        /// Fraction of the space given to `first`, 0.1–0.9.
151        ratio: f32,
152        /// First child.
153        first: Box<LayoutNode>,
154        /// Second child.
155        second: Box<LayoutNode>,
156    },
157}
158
159impl LayoutNode {
160    /// The group with `id`, if present.
161    pub fn group(&self, id: EditorGroupId) -> Option<&EditorGroup> {
162        match self {
163            Self::Group(group) => (group.id == id).then_some(group),
164            Self::Split { first, second, .. } => first.group(id).or_else(|| second.group(id)),
165        }
166    }
167
168    /// The group with `id`, mutably.
169    pub fn group_mut(&mut self, id: EditorGroupId) -> Option<&mut EditorGroup> {
170        match self {
171            Self::Group(group) => (group.id == id).then_some(group),
172            Self::Split { first, second, .. } => first.group_mut(id).or_else(|| second.group_mut(id)),
173        }
174    }
175
176    /// The group ids in depth-first order.
177    pub fn ids(&self) -> Vec<EditorGroupId> {
178        let mut ids = Vec::new();
179        self.collect_ids(&mut ids);
180        ids
181    }
182
183    fn collect_ids(&self, ids: &mut Vec<EditorGroupId>) {
184        match self {
185            Self::Group(group) => ids.push(group.id),
186            Self::Split { first, second, .. } => {
187                first.collect_ids(ids);
188                second.collect_ids(ids);
189            }
190        }
191    }
192
193    /// The first group id, used when splitting an unknown group.
194    pub fn first_id(&self) -> Option<EditorGroupId> {
195        self.ids().first().copied()
196    }
197
198    pub(super) fn remove_group(&mut self, id: EditorGroupId) -> bool {
199        match self {
200            Self::Group(_) => false,
201            Self::Split { first, second, .. } => {
202                if matches!(&**first, Self::Group(group) if group.id == id) {
203                    let replacement = std::mem::replace(&mut **second, Self::Group(EditorGroup::new(id)));
204                    *self = replacement;
205                    return true;
206                }
207                if matches!(&**second, Self::Group(group) if group.id == id) {
208                    let replacement = std::mem::replace(&mut **first, Self::Group(EditorGroup::new(id)));
209                    *self = replacement;
210                    return true;
211                }
212                first.remove_group(id) || second.remove_group(id)
213            }
214        }
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    fn split() -> LayoutNode {
223        LayoutNode::Split {
224            direction: SplitDirection::Horizontal,
225            ratio: 0.5,
226            first: Box::new(LayoutNode::Group(EditorGroup::new(EditorGroupId(1)))),
227            second: Box::new(LayoutNode::Group(EditorGroup::new(EditorGroupId(2)))),
228        }
229    }
230
231    #[test]
232    fn groups_are_found_in_both_children_and_ids_follow_document_order() {
233        let mut node = split();
234        assert!(node.group(EditorGroupId(1)).is_some());
235        assert!(node.group(EditorGroupId(3)).is_none());
236        assert!(node.group_mut(EditorGroupId(2)).is_some());
237        assert!(node.group_mut(EditorGroupId(3)).is_none());
238        assert_eq!(node.ids(), [EditorGroupId(1), EditorGroupId(2)]);
239        assert_eq!(node.first_id(), Some(EditorGroupId(1)));
240    }
241
242    #[test]
243    fn removing_each_child_promotes_the_sibling() {
244        let mut first = split();
245        assert!(first.remove_group(EditorGroupId(1)));
246        assert_eq!(first.ids(), [EditorGroupId(2)]);
247        let mut second = split();
248        assert!(second.remove_group(EditorGroupId(2)));
249        assert_eq!(second.ids(), [EditorGroupId(1)]);
250        assert!(!LayoutNode::Group(EditorGroup::new(EditorGroupId(4))).remove_group(EditorGroupId(4)));
251        assert!(!second.remove_group(EditorGroupId(9)));
252    }
253
254    #[test]
255    fn groups_normalize_empty_and_active_tabs() {
256        let mut group = EditorGroup::with_tabs(
257            EditorGroupId(1),
258            vec![LayoutTab::new("a", "A"), LayoutTab::new("b", "B").pinned()],
259        );
260        group.active = 9;
261        group.normalize();
262        assert_eq!(group.active, 1);
263        assert_eq!(group.active_tab().map(|tab| tab.title.as_str()), Some("B"));
264        group.tabs.clear();
265        group.normalize();
266        assert_eq!(group.active, 0);
267        assert!(group.active_tab().is_none());
268    }
269}