tui-lipan 0.2.0

Opinionated, component-based TUI framework for Rust - declarative components, reconciliation, layout engine, focus, overlays, and rich widgets 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
mod layout;
mod node;
mod reconcile;

pub(crate) use layout::measure_splitter;
pub(crate) use node::SplitterNode;
pub(crate) use reconcile::{SplitterReconcile, reconcile_splitter};

use std::sync::Arc;

use crate::callback::Callback;
use crate::core::element::{Element, ElementKind};
use crate::style::{Length, Style};
use crate::widgets::Orientation;

/// Where a [`Splitter`] places its drag handles relative to pane borders.
///
/// This is independent of whether neighboring [`Frame`](crate::widgets::Frame)s
/// merge their borders (`Frame::join_frame`). Border merging is a purely visual
/// choice owned by the frames; the handle mode only decides where the splitter's
/// drag target lives and how thick it is.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SplitterHandleMode {
    /// Reserve a gutter between panes and draw the handle glyph there.
    #[default]
    Gutter,
    /// Drop the gutter and ride the pane border seam: the border cells between
    /// panes become the drag target.
    ///
    /// Thickness follows the borders actually present:
    /// - neighbors that merge their borders share one wall → a 1-cell handle,
    /// - neighbors that keep separate borders expose two adjacent walls → a
    ///   2-cell handle so both are grabbed together,
    /// - borderless neighbors fall back to a synthetic 1-cell handle on the seam.
    Border,
}

/// Emitted by splitter resize callbacks with normalized pane weights.
#[derive(Clone, Debug)]
pub struct SplitterResizeEvent {
    /// Matches [`Splitter::split_id`] when set.
    pub split_id: Option<Arc<str>>,
    /// Normalized pane weights (sum ≈ 1).
    pub weights: Vec<f32>,
}

/// A resizable splitter container with draggable handles.
#[derive(Clone)]
pub struct Splitter {
    pub(crate) orientation: Orientation,
    pub(crate) children: Vec<Element>,
    pub(crate) weights: Vec<f32>,
    pub(crate) weights_nonce: u32,
    pub(crate) split_id: Option<Arc<str>>,
    pub(crate) on_resize_live: Option<Callback<SplitterResizeEvent>>,
    pub(crate) on_resize: Option<Callback<SplitterResizeEvent>>,
    pub(crate) min_size: u16,
    pub(crate) handle_size: u16,
    pub(crate) handle_mode: SplitterHandleMode,
    pub(crate) handle_symbol: char,
    pub(crate) handle_style: Style,
    pub(crate) handle_hover_style: Style,
    pub(crate) handle_active_style: Style,
    pub(crate) width: Length,
    pub(crate) height: Length,
}

impl Splitter {
    /// Create a splitter with a specific handle orientation.
    pub fn new(orientation: Orientation) -> Self {
        match orientation {
            Orientation::Horizontal => Self::horizontal(),
            Orientation::Vertical => Self::vertical(),
        }
    }

    /// Create a horizontal splitter (handles are horizontal; panes stacked vertically).
    pub fn horizontal() -> Self {
        Self {
            orientation: Orientation::Horizontal,
            children: Vec::new(),
            weights: Vec::new(),
            weights_nonce: 0,
            split_id: None,
            on_resize_live: None,
            on_resize: None,
            min_size: 3,
            handle_size: 1,
            handle_mode: SplitterHandleMode::Gutter,
            handle_symbol: '',
            handle_style: Style::default(),
            handle_hover_style: Style::default(),
            handle_active_style: Style::default(),
            width: Length::Flex(1),
            height: Length::Flex(1),
        }
    }

    /// Create a vertical splitter (handles are vertical; panes laid out horizontally).
    pub fn vertical() -> Self {
        Self {
            orientation: Orientation::Vertical,
            children: Vec::new(),
            weights: Vec::new(),
            weights_nonce: 0,
            split_id: None,
            on_resize_live: None,
            on_resize: None,
            min_size: 3,
            handle_size: 1,
            handle_mode: SplitterHandleMode::Gutter,
            handle_symbol: '',
            handle_style: Style::default(),
            handle_hover_style: Style::default(),
            handle_active_style: Style::default(),
            width: Length::Flex(1),
            height: Length::Flex(1),
        }
    }

    /// Add a child pane.
    pub fn child(mut self, child: impl Into<Element>) -> Self {
        self.children.push(child.into());
        self
    }

    /// Set handle orientation.
    pub fn orientation(mut self, orientation: Orientation) -> Self {
        if self.orientation != orientation {
            self.orientation = orientation;
            self.handle_symbol = match orientation {
                Orientation::Horizontal => '',
                Orientation::Vertical => '',
            };
        }
        self
    }

    /// Replace all children, discarding anything already added with
    /// [`child`](Self::child). Call `child` repeatedly to append instead.
    pub fn children<I>(mut self, children: I) -> Self
    where
        I: IntoIterator<Item = Element>,
    {
        self.children = children.into_iter().collect();
        self
    }

    /// Set pane weights (length must match number of panes).
    pub fn weights(mut self, weights: impl Into<Vec<f32>>) -> Self {
        self.weights = weights.into();
        self
    }

    /// Bump when pane weights should override the last reconciled split.
    pub fn weights_nonce(mut self, nonce: u32) -> Self {
        self.weights_nonce = nonce;
        self
    }

    /// Optional id included in [`SplitterResizeEvent`] after a drag.
    pub fn split_id(mut self, id: impl Into<Arc<str>>) -> Self {
        self.split_id = Some(id.into());
        self
    }

    /// Called while a drag resize changes pane weights.
    pub fn on_resize_live(mut self, cb: Callback<SplitterResizeEvent>) -> Self {
        self.on_resize_live = Some(cb);
        self
    }

    /// Called when a drag resize finishes with the final normalized pane weights.
    pub fn on_resize(mut self, cb: Callback<SplitterResizeEvent>) -> Self {
        self.on_resize = Some(cb);
        self
    }

    /// Set minimum size per pane (in cells).
    pub fn min_size(mut self, min_size: u16) -> Self {
        self.min_size = min_size;
        self
    }

    /// Set handle thickness (in cells).
    pub fn handle_size(mut self, size: u16) -> Self {
        self.handle_size = size.max(1);
        self
    }

    /// Set how handles are placed relative to pane borders.
    ///
    /// [`SplitterHandleMode::Gutter`] (default) reserves a gutter and draws the
    /// handle glyph there. [`SplitterHandleMode::Border`] drops the gutter and
    /// rides the pane border seam, hit-testing the border cells between panes as
    /// a single handle. This is orthogonal to whether the neighboring frames
    /// merge their borders (`Frame::join_frame`): separate borders are grabbed
    /// together as a 2-cell handle, a merged border as a 1-cell handle.
    pub fn handle_mode(mut self, mode: SplitterHandleMode) -> Self {
        self.handle_mode = mode;
        self
    }

    /// Set handle symbol.
    pub fn handle_symbol(mut self, symbol: char) -> Self {
        self.handle_symbol = symbol;
        self
    }

    /// Set handle style.
    pub fn handle_style(mut self, style: Style) -> Self {
        self.handle_style = style;
        self
    }

    /// Set handle hover style.
    pub fn handle_hover_style(mut self, style: Style) -> Self {
        self.handle_hover_style = style;
        self
    }

    /// Set handle active style (while dragging).
    pub fn handle_active_style(mut self, style: Style) -> Self {
        self.handle_active_style = style;
        self
    }

    /// Override requested width.
    pub fn width(mut self, width: Length) -> Self {
        self.width = width;
        self
    }

    /// Override requested height.
    pub fn height(mut self, height: Length) -> Self {
        self.height = height;
        self
    }
}

impl From<Splitter> for Element {
    fn from(value: Splitter) -> Self {
        Element::new(ElementKind::Splitter(value))
    }
}

impl crate::layout::hash::LayoutHash for Splitter {
    fn layout_hash(
        &self,
        hasher: &mut impl std::hash::Hasher,
        recurse: &dyn Fn(&Element) -> Option<u64>,
    ) -> Option<()> {
        use std::hash::Hash;
        self.width.hash(hasher);
        self.height.hash(hasher);
        self.orientation.hash(hasher);
        self.min_size.hash(hasher);
        self.handle_size.hash(hasher);
        self.handle_mode.hash(hasher);
        self.handle_symbol.hash(hasher);
        self.weights.len().hash(hasher);
        for weight in &self.weights {
            weight.to_bits().hash(hasher);
        }
        self.weights_nonce.hash(hasher);

        let needs_content =
            matches!(self.width, Length::Auto) || matches!(self.height, Length::Auto);
        if needs_content {
            crate::layout::hash::hash_children(&self.children, hasher, recurse)?;
        }
        Some(())
    }
}

impl Default for Splitter {
    fn default() -> Self {
        Self::horizontal()
    }
}

pub(crate) fn resolve_weights(explicit: &[f32], previous: &[f32], len: usize) -> Vec<f32> {
    let mut weights = if previous.len() == len && !previous.is_empty() {
        previous.to_vec()
    } else if explicit.len() == len && !explicit.is_empty() {
        explicit.to_vec()
    } else {
        vec![1.0; len]
    };

    for weight in &mut weights {
        if *weight < 0.0 {
            *weight = 0.0;
        }
    }

    let sum: f32 = weights.iter().sum();
    if sum <= f32::EPSILON {
        return vec![1.0; len];
    }

    for weight in &mut weights {
        *weight /= sum;
    }

    weights
}

pub(crate) fn sizes_from_weights(weights: &[f32], available: u16, min_size: u16) -> Vec<u16> {
    let count = weights.len();
    if count == 0 {
        return Vec::new();
    }
    if available == 0 {
        return vec![0; count];
    }

    let total_weight: f32 = weights.iter().sum();
    let total_weight = if total_weight <= f32::EPSILON {
        count as f32
    } else {
        total_weight
    };

    let mut sizes = Vec::with_capacity(count);
    let mut fractions = Vec::with_capacity(count);
    for weight in weights {
        let exact = (available as f32) * (*weight / total_weight);
        let floored = exact.floor();
        sizes.push(floored as u16);
        fractions.push(exact - floored);
    }

    // Largest-remainder apportionment: each leftover column goes to the pane
    // with the biggest dropped fraction, ties resolving to the lower index.
    //
    // Handing them out in plain index order instead would park a column on the
    // leftmost pane that a later pane actually earned. Because a drag round
    // trips through sizes -> weights -> sizes every frame, that misplacement
    // reappears each tick and a pane the drag never touched visibly bounces by
    // a column. Largest remainder makes the round trip exact, so panes only
    // move when the drag moves them.
    let mut order: Vec<usize> = (0..count).collect();
    order.sort_by(|a, b| {
        fractions[*b]
            .partial_cmp(&fractions[*a])
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(a.cmp(b))
    });

    let used: u16 = sizes.iter().sum();
    let mut remaining = available.saturating_sub(used) as usize;
    let mut idx = 0usize;
    while remaining > 0 {
        let target = order[idx % count];
        sizes[target] = sizes[target].saturating_add(1);
        remaining -= 1;
        idx += 1;
    }

    if min_size == 0 {
        return sizes;
    }

    let required = min_size.saturating_mul(count as u16);
    if available < required {
        return sizes;
    }

    loop {
        let mut updated = false;
        for idx in 0..count {
            if sizes[idx] < min_size {
                let deficit = min_size - sizes[idx];
                sizes[idx] = min_size;
                let mut remaining = deficit;
                for size in sizes.iter_mut().take(count) {
                    if remaining == 0 {
                        break;
                    }
                    if *size > min_size {
                        let take = (*size - min_size).min(remaining);
                        *size = size.saturating_sub(take);
                        remaining = remaining.saturating_sub(take);
                    }
                }
                updated = true;
                break;
            }
        }
        if !updated {
            break;
        }
    }

    sizes
}

pub(crate) fn sizes_to_weights(sizes: &[u16]) -> Vec<f32> {
    let total: u16 = sizes.iter().sum();
    if total == 0 {
        return vec![1.0; sizes.len()];
    }
    sizes
        .iter()
        .map(|size| (*size as f32) / (total as f32))
        .collect()
}

#[cfg(test)]
mod size_tests {
    use super::{sizes_from_weights, sizes_to_weights};

    /// A drag stores exact column counts, publishes them as weights, and the
    /// next layout turns them back into columns. That round trip has to be the
    /// identity, or panes drift by a column every frame while dragging.
    #[test]
    fn sizes_survive_a_round_trip_through_weights() {
        let cases: &[&[u16]] = &[
            &[39, 39, 79],
            &[40, 38, 79],
            &[1, 1, 155],
            &[52, 52, 53],
            &[10, 20, 30, 40],
            &[7, 11, 13, 17, 19],
            &[100, 1, 1],
            &[3, 3],
        ];

        for sizes in cases {
            let available: u16 = sizes.iter().sum();
            let weights = sizes_to_weights(sizes);
            let restored = sizes_from_weights(&weights, available, 0);
            assert_eq!(
                restored, *sizes,
                "round trip changed {sizes:?} (available {available})"
            );
        }
    }

    /// The leftover column belongs to the pane that earned it, not to pane 0.
    #[test]
    fn leftover_columns_follow_the_largest_fraction() {
        // Exact shares are 3.33, 3.33, 3.33 -> one leftover column, and with
        // equal fractions the lowest index wins.
        assert_eq!(sizes_from_weights(&[1.0, 1.0, 1.0], 10, 0), vec![4, 3, 3]);

        // Exact shares are 1.0, 4.0, 5.0 - nothing is dropped, so nothing moves.
        assert_eq!(sizes_from_weights(&[0.1, 0.4, 0.5], 10, 0), vec![1, 4, 5]);

        // Exact shares are 0.9, 4.5, 4.6: floors 0, 4, 4 leave two columns for
        // the two largest fractions (.9 and .6), not for the first two panes.
        assert_eq!(
            sizes_from_weights(&[0.09, 0.45, 0.46], 10, 0),
            vec![1, 4, 5]
        );
    }

    #[test]
    fn sizes_always_fill_the_available_space() {
        for available in [1u16, 7, 13, 80, 157, 999] {
            for weights in [
                vec![1.0, 1.0, 2.0],
                vec![0.3333, 0.3333, 0.3334],
                vec![0.01, 0.98, 0.01],
            ] {
                let sizes = sizes_from_weights(&weights, available, 0);
                assert_eq!(
                    sizes.iter().sum::<u16>(),
                    available,
                    "weights {weights:?} at {available} left a gap"
                );
            }
        }
    }
}