rizzler 0.1.0

the rizz editor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#![allow(dead_code)]

use ratatui::layout::{Constraint, Direction, Layout, Rect};

/// Orientation of a window split. `Horizontal` lays children side-by-side
/// (vim's `:vsplit`); `Vertical` stacks them top-to-bottom (vim's `:split`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SplitDir {
    Horizontal,
    Vertical,
}

/// Cardinal direction for moving window focus.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FocusDir {
    Left,
    Right,
    Up,
    Down,
}

impl FocusDir {
    /// Which split orientation a step in this direction can traverse.
    fn split_axis(self) -> SplitDir {
        match self {
            FocusDir::Left | FocusDir::Right => SplitDir::Horizontal,
            FocusDir::Up | FocusDir::Down => SplitDir::Vertical,
        }
    }

    /// True for Right/Down — directions that move toward later siblings.
    fn forward(self) -> bool {
        matches!(self, FocusDir::Right | FocusDir::Down)
    }
}

impl SplitDir {
    fn as_ratatui(self) -> Direction {
        match self {
            SplitDir::Horizontal => Direction::Horizontal,
            SplitDir::Vertical => Direction::Vertical,
        }
    }
}

/// One node in the window tree. Leaves point at a buffer index; splits
/// divide their rect proportionally among children by integer weights.
#[derive(Debug, Clone)]
pub enum Window {
    Leaf {
        bufno: usize,
    },
    Split {
        dir: SplitDir,
        children: Vec<(u16, Window)>,
    },
}

impl Window {
    pub fn leaf(bufno: usize) -> Self {
        Self::Leaf { bufno }
    }
}

/// Index path from root through Split children to a Leaf. Empty path = the
/// root is itself a leaf.
pub type LeafPath = Vec<usize>;

/// Concrete placement of one leaf after layout.
#[derive(Debug, Clone)]
pub struct LeafLayout {
    pub path: LeafPath,
    pub bufno: usize,
    pub area: Rect,
}

/// Editor window tree plus focus tracking. The minibuffer is *not* part of
/// this tree — it's rendered separately by the host renderer.
#[derive(Debug, Clone)]
pub struct WindowTree {
    root: Window,
    focused: LeafPath,
}

impl WindowTree {
    pub fn new(bufno: usize) -> Self {
        Self {
            root: Window::leaf(bufno),
            focused: Vec::new(),
        }
    }

    pub fn focused_path(&self) -> &LeafPath {
        &self.focused
    }

    pub fn focused_bufno(&self) -> usize {
        match self.node_at(&self.focused) {
            Some(Window::Leaf { bufno }) => *bufno,
            _ => panic!("focused path must point to a leaf"),
        }
    }

    /// Point the focused leaf at a different buffer.
    pub fn set_focused_bufno(&mut self, bufno: usize) {
        let path = self.focused.clone();
        if let Some(Window::Leaf { bufno: b }) = self.node_at_mut(&path) {
            *b = bufno;
        }
    }

    /// Lay the tree out into `area`. Returns one entry per leaf, in tree
    /// order (left-to-right, top-to-bottom).
    pub fn layout(&self, area: Rect) -> Vec<LeafLayout> {
        let mut out = Vec::new();
        Self::layout_node(&self.root, area, &mut Vec::new(), &mut out);
        out
    }

    fn layout_node(node: &Window, area: Rect, path: &mut LeafPath, out: &mut Vec<LeafLayout>) {
        match node {
            Window::Leaf { bufno } => out.push(LeafLayout {
                path: path.clone(),
                bufno: *bufno,
                area,
            }),
            Window::Split { dir, children } => {
                let total: u32 = children.iter().map(|(w, _)| *w as u32).sum::<u32>().max(1);
                let constraints: Vec<Constraint> = children
                    .iter()
                    .map(|(w, _)| Constraint::Ratio(*w as u32, total))
                    .collect();
                let rects = Layout::default()
                    .direction(dir.as_ratatui())
                    .constraints(constraints)
                    .split(area);
                for (i, ((_, child), rect)) in children.iter().zip(rects.iter()).enumerate() {
                    path.push(i);
                    Self::layout_node(child, *rect, path, out);
                    path.pop();
                }
            }
        }
    }

    fn node_at(&self, path: &[usize]) -> Option<&Window> {
        let mut node = &self.root;
        for &i in path {
            node = match node {
                Window::Split { children, .. } => &children.get(i)?.1,
                Window::Leaf { .. } => return None,
            };
        }
        Some(node)
    }

    fn node_at_mut(&mut self, path: &[usize]) -> Option<&mut Window> {
        let mut node = &mut self.root;
        for &i in path {
            node = match node {
                Window::Split { children, .. } => &mut children.get_mut(i)?.1,
                Window::Leaf { .. } => return None,
            };
        }
        Some(node)
    }

    /// Replace the focused leaf with a split; the existing buffer stays as
    /// the first child, the new buffer is placed as the second child and
    /// gains focus.
    pub fn split(&mut self, dir: SplitDir, new_bufno: usize) {
        let current_bufno = self.focused_bufno();
        let path = self.focused.clone();
        if let Some(leaf) = self.node_at_mut(&path) {
            *leaf = Window::Split {
                dir,
                children: vec![
                    (1, Window::leaf(current_bufno)),
                    (1, Window::leaf(new_bufno)),
                ],
            };
        }
        self.focused.push(1);
    }

    /// Move focus to the nearest window in `dir`. Walks up the tree until it
    /// finds an ancestor split whose orientation matches `dir` and that has a
    /// sibling in the requested direction; then descends into that sibling's
    /// leftmost/topmost leaf. No-op if no such ancestor exists (focus is
    /// already at the edge along that axis).
    pub fn focus_dir(&mut self, dir: FocusDir) {
        let axis = dir.split_axis();
        let forward = dir.forward();
        let mut path = self.focused.clone();
        while let Some(child_idx) = path.pop() {
            let Some(Window::Split {
                dir: split_dir,
                children,
            }) = self.node_at(&path)
            else {
                continue;
            };
            if *split_dir != axis {
                continue;
            }
            let sibling = if forward {
                (child_idx + 1 < children.len()).then_some(child_idx + 1)
            } else {
                (child_idx > 0).then(|| child_idx - 1)
            };
            let Some(sibling_idx) = sibling else { continue };
            path.push(sibling_idx);
            Self::descend_first_leaf(&self.root, &mut path);
            self.focused = path;
            return;
        }
    }

    /// Extend `path` by descending through the first child of each Split
    /// until it points at a Leaf.
    fn descend_first_leaf(root: &Window, path: &mut LeafPath) {
        let mut node = root;
        for &i in path.iter() {
            node = match node {
                Window::Split { children, .. } => &children[i].1,
                Window::Leaf { .. } => return,
            };
        }
        while let Window::Split { children, .. } = node {
            path.push(0);
            node = &children[0].1;
        }
    }

    /// Move focus to the next leaf in tree order; wraps around.
    pub fn focus_next(&mut self) {
        let leaves = self.layout(Rect::default());
        if leaves.is_empty() {
            return;
        }
        let cur = leaves
            .iter()
            .position(|l| l.path == self.focused)
            .unwrap_or(0);
        let next = (cur + 1) % leaves.len();
        self.focused = leaves[next].path.clone();
    }

    /// Close the focused window. The sibling absorbs the split's space and
    /// focus moves into it. No-op on a single-leaf tree.
    pub fn close_focused(&mut self) {
        if self.focused.is_empty() {
            return;
        }
        let mut path = self.focused.clone();
        let leaf_idx = path.pop().unwrap();
        let parent_path = path;

        let Some(parent) = self.node_at_mut(&parent_path) else {
            return;
        };
        let Window::Split { children, .. } = parent else {
            return;
        };
        if leaf_idx >= children.len() {
            return;
        }
        children.remove(leaf_idx);
        // Collapse one-child splits — the lone survivor replaces the split.
        if children.len() == 1 {
            let (_, only) = children.remove(0);
            *parent = only;
        }

        // Re-establish focus on the first leaf at or under parent_path.
        self.focused = parent_path;
        loop {
            match self.node_at(&self.focused) {
                Some(Window::Leaf { .. }) | None => break,
                Some(Window::Split { .. }) => self.focused.push(0),
            }
        }
    }

    /// Visit every leaf's bufno in-place. Use after the buffer Vec has been
    /// mutated (e.g. a removal shifts subsequent indices down by one).
    pub fn for_each_leaf_mut(&mut self, mut f: impl FnMut(&mut usize)) {
        Self::walk_mut(&mut self.root, &mut f);
    }

    fn walk_mut(node: &mut Window, f: &mut impl FnMut(&mut usize)) {
        match node {
            Window::Leaf { bufno } => f(bufno),
            Window::Split { children, .. } => {
                for (_, child) in children {
                    Self::walk_mut(child, f);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn r(w: u16, h: u16) -> Rect {
        Rect::new(0, 0, w, h)
    }

    #[test]
    fn new_tree_is_single_leaf() {
        let t = WindowTree::new(3);
        assert_eq!(t.focused_bufno(), 3);
        let layout = t.layout(r(80, 24));
        assert_eq!(layout.len(), 1);
        assert_eq!(layout[0].bufno, 3);
    }

    #[test]
    fn split_creates_two_leaves_and_focuses_new() {
        let mut t = WindowTree::new(1);
        t.split(SplitDir::Horizontal, 2);
        let layout = t.layout(r(80, 24));
        assert_eq!(layout.len(), 2);
        assert_eq!(layout[0].bufno, 1);
        assert_eq!(layout[1].bufno, 2);
        assert_eq!(t.focused_bufno(), 2);
    }

    #[test]
    fn focus_next_cycles() {
        let mut t = WindowTree::new(1);
        t.split(SplitDir::Horizontal, 2); // focus on 2
        t.focus_next();
        assert_eq!(t.focused_bufno(), 1);
        t.focus_next();
        assert_eq!(t.focused_bufno(), 2);
    }

    #[test]
    fn close_focused_collapses_split() {
        let mut t = WindowTree::new(1);
        t.split(SplitDir::Vertical, 2); // focus on 2
        t.close_focused();
        let layout = t.layout(r(80, 24));
        assert_eq!(layout.len(), 1);
        assert_eq!(layout[0].bufno, 1);
        assert_eq!(t.focused_bufno(), 1);
    }

    #[test]
    fn close_focused_noop_on_single_leaf() {
        let mut t = WindowTree::new(5);
        t.close_focused();
        assert_eq!(t.focused_bufno(), 5);
    }

    #[test]
    fn nested_split_layouts() {
        let mut t = WindowTree::new(1);
        t.split(SplitDir::Horizontal, 2); // focus on 2
        t.split(SplitDir::Vertical, 3); // split 2 vertically, focus on 3
        let layout = t.layout(r(80, 24));
        assert_eq!(layout.len(), 3);
        // tree order: left half (bufno 1), then right-top (2), then right-bottom (3)
        assert_eq!(layout[0].bufno, 1);
        assert_eq!(layout[1].bufno, 2);
        assert_eq!(layout[2].bufno, 3);
    }

    #[test]
    fn focus_dir_moves_across_horizontal_split() {
        let mut t = WindowTree::new(1);
        t.split(SplitDir::Horizontal, 2); // focus on 2 (right)
        t.focus_dir(FocusDir::Left);
        assert_eq!(t.focused_bufno(), 1);
        t.focus_dir(FocusDir::Right);
        assert_eq!(t.focused_bufno(), 2);
    }

    #[test]
    fn focus_dir_moves_across_vertical_split() {
        let mut t = WindowTree::new(1);
        t.split(SplitDir::Vertical, 2); // focus on 2 (bottom)
        t.focus_dir(FocusDir::Up);
        assert_eq!(t.focused_bufno(), 1);
        t.focus_dir(FocusDir::Down);
        assert_eq!(t.focused_bufno(), 2);
    }

    #[test]
    fn focus_dir_noop_at_edge() {
        let mut t = WindowTree::new(1);
        t.split(SplitDir::Horizontal, 2); // focus on 2 (rightmost)
        t.focus_dir(FocusDir::Right);
        assert_eq!(t.focused_bufno(), 2); // unchanged
        t.focus_dir(FocusDir::Up);
        assert_eq!(t.focused_bufno(), 2); // no vertical axis available
    }

    #[test]
    fn focus_dir_skips_mismatched_split_axis() {
        // Layout (Horizontal split):
        //   [ 1 ] | [ Vertical: 2 over 3 ]
        // From 3, focus-left should jump out of the vertical split and into 1.
        let mut t = WindowTree::new(1);
        t.split(SplitDir::Horizontal, 2); // focus on 2
        t.split(SplitDir::Vertical, 3); // focus on 3, nested in the right half
        t.focus_dir(FocusDir::Left);
        assert_eq!(t.focused_bufno(), 1);
    }

    #[test]
    fn for_each_leaf_mut_reindexes() {
        let mut t = WindowTree::new(2);
        t.split(SplitDir::Horizontal, 3);
        // Simulate: bufno 1 was removed from the buffer Vec — all indices
        // ≥ 1 shift down by one.
        t.for_each_leaf_mut(|b| {
            if *b > 1 {
                *b -= 1;
            }
        });
        let layout = t.layout(r(10, 10));
        assert_eq!(layout[0].bufno, 1);
        assert_eq!(layout[1].bufno, 2);
    }
}