tuile 0.2.0

Textual-grade widgets, design system, animation and app runtime on top of ratatui
Documentation
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! Resizable split pane with a divider, horizontal or vertical. Drag the divider to resize,
//! double-click to reset, or call `state.resize_by(delta)` from key handlers.
//!
//! ```no_run
//! use tuile::prelude::*;
//! # let area = Rect::new(0, 0, 80, 24);
//! # let mut buf = Buffer::empty(area);
//! let mut state = SplitState::new(SplitSize::Ratio(0.3), 10, 10);
//! let (l, r) = SplitPane::new().direction(Direction::Horizontal).render_split(area, &mut buf, &mut state);
//! ```

use std::time::Instant;

use crossterm::event::{KeyEvent, MouseEvent};
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::{Direction, Rect};

use crate::core::{Hit, HitBox, Outcome, is_left_drag, is_left_up, mouse_pos};
use crate::draw::{fill, put_cell, st};
use crate::theme::{self, Theme};

/// Initial size of the first pane.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SplitSize {
    /// Fixed cells.
    Cells(u16),
    /// Ratio of total size (clamped to 0..=1).
    Ratio(f32),
}

impl Default for SplitSize {
    fn default() -> Self {
        SplitSize::Ratio(0.5)
    }
}

/// Divider style.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SplitDivider {
    /// Single line (`│`/`─`).
    #[default]
    Line,
    /// Thick (`┃`/`━`).
    Thick,
    /// Dotted (`┊`/`┄`).
    Dotted,
    /// No divider (zero-width).
    Hidden,
}

/// State for a split pane: current position, drag state, cached layout.
#[derive(Clone, Debug, Default)]
pub struct SplitState {
    /// The *initial* size spec (preserved for reset).
    pub initial: SplitSize,
    /// Current size of the first pane in cells.
    pub pos: u16,
    /// Minimum size of the first pane.
    pub min_first: u16,
    /// Minimum size of the second pane.
    pub min_second: u16,
    /// Divider HitBox.
    pub hit: HitBox,
    /// True while dragging.
    pub dragging: bool,
    /// Cached layout (first, divider, second).
    pub cached: (Rect, Rect, Rect),
    /// Last click time for double-click reset detection.
    last_click: Option<Instant>,
    /// Collapsed state: 0 = expanded, 1 = first collapsed, 2 = second collapsed.
    collapsed: u8,
}

impl SplitState {
    pub fn new(initial: SplitSize, min_first: u16, min_second: u16) -> Self {
        Self {
            initial,
            pos: 0,
            min_first,
            min_second,
            ..Default::default()
        }
    }

    /// Adjust position by `delta` cells, clamped to the minimum sizes.
    pub fn resize_by(&mut self, delta: i32) {
        let (first, div, second) = self.cached;
        // panes side by side share their y/height → horizontal split
        let horizontal = first.y == second.y && first.height == second.height;
        let (total, divider_w) = if horizontal {
            (first.width + div.width + second.width, div.width)
        } else {
            (first.height + div.height + second.height, div.height)
        };
        let max_pos = total.saturating_sub(self.min_second + divider_w);
        self.pos = (self.pos as i32 + delta)
            .clamp(self.min_first as i32, max_pos.max(self.min_first) as i32)
            as u16;
    }

    /// Collapse the first pane (hide it, second pane takes full area).
    pub fn collapse_first(&mut self) {
        self.collapsed = 1;
    }

    /// Collapse the second pane.
    pub fn collapse_second(&mut self) {
        self.collapsed = 2;
    }

    /// Restore to expanded state.
    pub fn restore(&mut self) {
        self.collapsed = 0;
    }

    /// Returns the cached (first, second) pane rects. Call after `render_split`.
    pub fn rects(&self) -> (Rect, Rect) {
        (self.cached.0, self.cached.2)
    }

    /// Reset to initial size.
    fn reset(&mut self, total: u16, divider_w: u16) {
        self.pos = match self.initial {
            SplitSize::Cells(c) => c,
            SplitSize::Ratio(r) => {
                (total.saturating_sub(divider_w) as f32 * r.clamp(0.0, 1.0)) as u16
            }
        };
    }
}

impl crate::core::Interactive for SplitState {
    fn handle_key(&mut self, _k: KeyEvent) -> Outcome {
        Outcome::Ignored
    }

    fn handle_mouse(&mut self, m: MouseEvent) -> Outcome {
        let h = self.hit.mouse(&m);
        let mut out = Outcome::Ignored;

        if h == Hit::Press {
            self.dragging = true;
            let now = Instant::now();
            if let Some(last) = self.last_click
                && now.duration_since(last).as_millis() < 400
            {
                // Double-click: reset
                let total = self.cached.0.width.max(self.cached.0.height);
                let divider_w = if self.cached.1.width > 0 || self.cached.1.height > 0 {
                    1
                } else {
                    0
                };
                self.reset(total, divider_w);
                out = Outcome::Changed;
            }
            self.last_click = Some(now);
        } else if is_left_up(&m) && self.dragging {
            self.dragging = false;
            out = Outcome::Consumed;
        } else if is_left_drag(&m) && self.dragging {
            // Drag: the divider follows the pointer along the split axis
            let pos = mouse_pos(&m);
            let (first, divider, second) = self.cached;
            let horizontal = first.y == second.y && first.height == second.height;
            let (total, divider_w, raw) = if horizontal {
                (
                    first.width + divider.width + second.width,
                    divider.width,
                    pos.x.saturating_sub(first.x),
                )
            } else {
                (
                    first.height + divider.height + second.height,
                    divider.height,
                    pos.y.saturating_sub(first.y),
                )
            };
            let max_pos = total.saturating_sub(self.min_second + divider_w);
            self.pos = raw.clamp(self.min_first.min(max_pos), max_pos);
            out = Outcome::Consumed;
        } else if h == Hit::HoverChanged {
            out = Outcome::Consumed;
        }

        out
    }
}

/// Resizable split pane builder.
#[derive(Clone, Debug)]
pub struct SplitPane {
    direction: Direction,
    /// `None` = keep whatever the state was constructed with.
    initial: Option<SplitSize>,
    min_first: Option<u16>,
    min_second: Option<u16>,
    divider: SplitDivider,
    focused: bool,
    theme: Option<Theme>,
}

impl SplitPane {
    pub fn new() -> Self {
        Self {
            direction: Direction::Horizontal,
            initial: None,
            min_first: None,
            min_second: None,
            divider: SplitDivider::default(),
            focused: false,
            theme: None,
        }
    }

    pub fn direction(mut self, d: Direction) -> Self {
        self.direction = d;
        self
    }

    /// Initial size of the first pane (overrides the one given to `SplitState::new`).
    pub fn initial(mut self, s: SplitSize) -> Self {
        self.initial = Some(s);
        self
    }

    pub fn min_first(mut self, m: u16) -> Self {
        self.min_first = Some(m);
        self
    }

    pub fn min_second(mut self, m: u16) -> Self {
        self.min_second = Some(m);
        self
    }

    pub fn divider(mut self, d: SplitDivider) -> Self {
        self.divider = d;
        self
    }

    pub fn focused(mut self, f: bool) -> Self {
        self.focused = f;
        self
    }

    pub fn theme(mut self, t: &Theme) -> Self {
        self.theme = Some(*t);
        self
    }

    /// Render the split and return (first_rect, second_rect).
    pub fn render_split(
        self,
        area: Rect,
        buf: &mut Buffer,
        state: &mut SplitState,
    ) -> (Rect, Rect) {
        let th = self.theme.unwrap_or_else(theme::current);

        // Builder overrides win; the state keeps its own config otherwise. A changed initial
        // (or the very first render) resets the position.
        if let Some(m) = self.min_first {
            state.min_first = m;
        }
        if let Some(m) = self.min_second {
            state.min_second = m;
        }
        let initial_changed = self.initial.is_some_and(|i| i != state.initial);
        if state.pos == 0 || initial_changed {
            if let Some(i) = self.initial {
                state.initial = i;
            }
            let divider_w = if self.divider == SplitDivider::Hidden {
                0
            } else {
                1
            };
            let total = if self.direction == Direction::Horizontal {
                area.width
            } else {
                area.height
            };
            state.reset(total, divider_w);
        }

        let divider_w = if self.divider == SplitDivider::Hidden {
            0
        } else {
            1
        };
        let is_horz = self.direction == Direction::Horizontal;
        let total = if is_horz { area.width } else { area.height };
        let max_pos = total.saturating_sub(state.min_second + divider_w);
        // when the area is smaller than both minimums, the first pane just takes what it can
        let pos = state
            .pos
            .clamp(state.min_first.min(max_pos), max_pos)
            .min(total);
        state.pos = pos;

        // Handle collapsed state
        if state.collapsed == 1 {
            // First collapsed
            state.cached = (Rect::default(), Rect::default(), area);
            state.hit.set_area(Rect::default());
            return (Rect::default(), area);
        } else if state.collapsed == 2 {
            // Second collapsed
            state.cached = (area, Rect::default(), Rect::default());
            state.hit.set_area(Rect::default());
            return (area, Rect::default());
        }

        let (first, divider, second) = if is_horz {
            let f = Rect { width: pos, ..area };
            let d = Rect {
                x: area.x + pos,
                width: divider_w,
                ..area
            };
            let s = Rect {
                x: area.x + pos + divider_w,
                width: total.saturating_sub(pos + divider_w),
                ..area
            };
            (f, d, s)
        } else {
            let f = Rect {
                height: pos,
                ..area
            };
            let d = Rect {
                y: area.y + pos,
                height: divider_w,
                ..area
            };
            let s = Rect {
                y: area.y + pos + divider_w,
                height: total.saturating_sub(pos + divider_w),
                ..area
            };
            (f, d, s)
        };

        state.cached = (first, divider, second);
        state.hit.set_area(divider);

        // Draw divider
        if divider_w > 0 {
            let (sym, grip) = match self.divider {
                SplitDivider::Line => {
                    if is_horz {
                        ("│", "┃")
                    } else {
                        ("─", "━")
                    }
                }
                SplitDivider::Thick => {
                    if is_horz {
                        ("┃", "┃")
                    } else {
                        ("━", "━")
                    }
                }
                SplitDivider::Dotted => {
                    if is_horz {
                        ("┊", "┃")
                    } else {
                        ("┄", "━")
                    }
                }
                SplitDivider::Hidden => ("", ""),
            };

            let color = if state.hit.hover || state.dragging {
                th.primary
            } else {
                th.text_disabled
            };
            fill(buf, divider, th.background);

            if is_horz {
                for y in divider.y..divider.bottom() {
                    let mid = divider.y + divider.height / 2;
                    let use_grip = (y as i16 - mid as i16).abs() <= 1;
                    put_cell(
                        buf,
                        divider.x,
                        y,
                        if use_grip { grip } else { sym },
                        st(color, th.background),
                    );
                }
            } else {
                for x in divider.x..divider.right() {
                    let mid = divider.x + divider.width / 2;
                    let use_grip = (x as i16 - mid as i16).abs() <= 1;
                    put_cell(
                        buf,
                        x,
                        divider.y,
                        if use_grip { grip } else { sym },
                        st(color, th.background),
                    );
                }
            }
        }

        (first, second)
    }
}

impl Default for SplitPane {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui_core::buffer::Buffer;
    use ratatui_core::layout::Direction;

    #[test]
    fn split_horizontal_ratio() {
        let mut state = SplitState::new(SplitSize::Ratio(0.3), 5, 5);
        let mut buf = Buffer::empty(Rect::new(0, 0, 100, 20));
        let area = buf.area;
        let (l, r) = SplitPane::new()
            .direction(Direction::Horizontal)
            .render_split(area, &mut buf, &mut state);
        // 100 cells total, divider 1, so 99 available. 0.3 * 99 = 29.7 ~= 29
        assert_eq!(l.width, 29);
        assert_eq!(r.width, 100 - 29 - 1);
    }

    #[test]
    fn split_vertical_cells() {
        let mut state = SplitState::new(SplitSize::Cells(10), 2, 2);
        let mut buf = Buffer::empty(Rect::new(0, 0, 40, 30));
        let area = buf.area;
        let (t, b) = SplitPane::new()
            .direction(Direction::Vertical)
            .render_split(area, &mut buf, &mut state);
        assert_eq!(t.height, 10);
        assert_eq!(b.height, 30 - 10 - 1);
    }

    #[test]
    fn split_clamped_to_min() {
        let mut state = SplitState::new(SplitSize::Cells(3), 10, 10);
        let mut buf = Buffer::empty(Rect::new(0, 0, 50, 20));
        let area = buf.area;
        let (l, _r) = SplitPane::new()
            .direction(Direction::Horizontal)
            .min_first(10)
            .min_second(10)
            .render_split(area, &mut buf, &mut state);
        // pos=3 is below min_first=10, so clamped to 10
        assert_eq!(l.width, 10);
    }

    #[test]
    fn split_resize_by() {
        let mut state = SplitState::new(SplitSize::Cells(20), 5, 5);
        let mut buf = Buffer::empty(Rect::new(0, 0, 60, 20));
        let area = buf.area;
        SplitPane::new().render_split(area, &mut buf, &mut state);
        state.resize_by(10);
        assert_eq!(state.pos, 30);
        state.resize_by(-100); // Should clamp to min_first
        assert_eq!(state.pos, 5);
    }

    #[test]
    fn split_collapse() {
        let mut state = SplitState::new(SplitSize::Ratio(0.5), 0, 0);
        let mut buf = Buffer::empty(Rect::new(0, 0, 40, 20));
        let area = buf.area;
        state.collapse_first();
        let (l, r) = SplitPane::new().render_split(area, &mut buf, &mut state);
        assert_eq!(l.width, 0);
        assert_eq!(r.width, 40);

        state.restore();
        let (l2, r2) = SplitPane::new().render_split(area, &mut buf, &mut state);
        assert!(l2.width > 0 && r2.width > 0);
    }
}