delta-gitu 0.1.15

An experimental fork of gitu (a git client inspired by Magit), published as a library for delta to embed
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
use std::borrow::Cow;

use crate::style::Style;
use unicode_segmentation::UnicodeSegmentation;

use crate::config::Config;
use crate::picker::PickerState;
use crate::ui::layout::opts;
use crate::ui::{DASHES, UiTree, layout_cursor, layout_span, repeat_chars};

const MAX_ITEMS_DISPLAY: usize = 10;

/// Layout the picker UI
pub(crate) fn layout_picker<'a>(
    layout: &mut UiTree<'a>,
    state: &'a PickerState,
    config: &Config,
    width: usize,
) {
    if state.is_one_row() {
        layout_one_row(layout, state, config);
        return;
    }

    // Separator line
    let separator_style = Style::from(&config.style.separator);
    repeat_chars(layout, width, DASHES, separator_style);

    if state.grid().is_some() {
        layout_grid(layout, state, config);
        return;
    }

    let prompt_style: Style = (&config.style.picker.prompt).into();
    let info_style: Style = (&config.style.picker.info).into();
    layout.row(opts(), |layout| {
        // A list that is not searched has no search to show.
        if state.assigns_keys() {
            let heading = format!(" {}", state.prompt_text);
            layout_span(layout, (heading.into(), prompt_style));
            return;
        }

        let status_text = format!(" {}/{}   ", state.filtered_count(), state.total_items());
        layout_span(layout, (status_text.into(), info_style));

        // Prompt with separator (like regular prompt)
        layout_span(layout, (state.prompt_text.as_ref().into(), prompt_style));
        layout_span(layout, (" › ".into(), prompt_style));
        let (before, at_cursor, after) = state.input_state.split_at_cursor();
        layout_span(layout, (before.into(), Style::new()));
        layout_cursor(layout, at_cursor);
        layout_span(layout, (after.into(), Style::new()));
    });

    // Calculate visible items range (scroll window)
    let cursor = state.cursor();
    let total_items = state.filtered_items().count();
    let visible_count = MAX_ITEMS_DISPLAY.min(total_items);
    let start = calculate_visible_range(cursor, total_items, MAX_ITEMS_DISPLAY);

    // Render items - always show MAX_ITEMS_DISPLAY rows for fixed height
    let mut rendered_count = 0;
    for (display_idx, (original_idx, item)) in state
        .filtered_items()
        .enumerate()
        .skip(start)
        .take(visible_count)
    {
        let is_selected = display_idx == cursor;
        let style = if is_selected {
            (&config.style.picker.selection_line).into()
        } else {
            Style::new()
        };

        layout.row(opts(), |layout| {
            // Selection indicator (cursor bar like status screen)
            if is_selected {
                let cursor_style: Style = (&config.style.cursor).into();
                let indicator = format!("{}", config.style.cursor.symbol);
                layout_span(layout, (indicator.into(), cursor_style));
            } else {
                layout_span(layout, (" ".into(), Style::new()));
            }

            // Render item text with fuzzy match highlighting
            if let Some(match_indices) = state.match_indices(original_idx) {
                render_highlighted_text(layout, &item.display, &match_indices, style, config);
            } else {
                layout_span(layout, (item.display.as_ref().into(), style));
            }
        });
        rendered_count += 1;
    }

    // Fill remaining rows with empty lines to maintain fixed height
    for _ in rendered_count..MAX_ITEMS_DISPLAY {
        layout.row(opts(), |layout| {
            layout_span(layout, (" ".into(), Style::new()));
        });
    }
}

/// The items in their columns side by side, each under its heading, leaving out
/// columns with none. The columns scroll together, to keep the cursor in view.
fn layout_grid<'a>(layout: &mut UiTree<'a>, state: &'a PickerState, config: &Config) {
    let Some(grid) = state.grid() else {
        return;
    };
    let heading_style: Style = (&config.style.picker.prompt).into();
    let columns: Vec<(usize, Vec<usize>)> = (0..grid.headings.len())
        .map(|column| (column, state.column_positions(column)))
        .filter(|(_, positions)| !positions.is_empty())
        .collect();
    let longest = columns
        .iter()
        .map(|(_, positions)| positions.len())
        .max()
        .unwrap_or(0);
    let cursor_row = columns
        .iter()
        .find_map(|(_, positions)| positions.iter().position(|&p| p == state.cursor()))
        .unwrap_or(0);
    let start = calculate_visible_range(cursor_row, longest, MAX_ITEMS_DISPLAY);
    let items: Vec<_> = state.filtered_items().map(|(_, item)| item).collect();

    layout.row(opts().gap(3), |layout| {
        for (column, positions) in &columns {
            layout.col(opts(), |layout| {
                layout.row(opts(), |layout| {
                    let heading = format!(" {}", grid.headings[*column]);
                    layout_span(layout, (heading.into(), heading_style));
                });
                for row in start..start + MAX_ITEMS_DISPLAY {
                    layout.row(opts(), |layout| match positions.get(row) {
                        Some(&position) => {
                            layout_item(layout, items[position], position == state.cursor(), config)
                        }
                        None => layout_span(layout, (" ".into(), Style::new())),
                    });
                }
            });
        }
    });
}

/// An item's row: the cursor's bar if it is selected, then its text.
fn layout_item<'a>(
    layout: &mut UiTree<'a>,
    item: &'a crate::picker::PickerItem,
    is_selected: bool,
    config: &Config,
) {
    if is_selected {
        let cursor_style: Style = (&config.style.cursor).into();
        let indicator = format!("{}", config.style.cursor.symbol);
        layout_span(layout, (indicator.into(), cursor_style));
        layout_span(
            layout,
            (
                item.display.as_ref().into(),
                (&config.style.picker.selection_line).into(),
            ),
        );
    } else {
        layout_span(layout, (" ".into(), Style::new()));
        layout_span(layout, (item.display.as_ref().into(), Style::new()));
    }
}

/// The selected item alone, its number, and any search typed in the list: no
/// more than that, so that the screen above stays in view. The number is the
/// digit that selects the item, so the first is 0; an item one row passes
/// over has none.
fn layout_one_row<'a>(layout: &mut UiTree<'a>, state: &'a PickerState, config: &Config) {
    let prompt_style: Style = (&config.style.picker.prompt).into();
    let info_style: Style = (&config.style.picker.info).into();
    let selection_style: Style = (&config.style.picker.selection_line).into();
    layout.row(opts(), |layout| {
        let (number, last) = state.one_row_number();
        let number = number.map_or("-".to_owned(), |n| n.to_string());
        layout_span(layout, (format!(" {number}/{last}  ").into(), info_style));
        layout_span(
            layout,
            (format!("{} ", state.prompt_text).into(), prompt_style),
        );
        if let Some(item) = state.selected() {
            layout_span(layout, (item.display.as_ref().into(), selection_style));
        }
        if !state.pattern().is_empty() {
            layout_span(
                layout,
                (format!("   › {}", state.pattern()).into(), info_style),
            );
        }
    });
}

/// Calculate the visible range start for scrolling based on cursor position
fn calculate_visible_range(cursor: usize, total: usize, max_items: usize) -> usize {
    if total <= max_items {
        return 0;
    }

    // Center the cursor in the visible window
    let half = max_items / 2;
    if cursor < half {
        0
    } else if cursor >= total - half {
        total - max_items
    } else {
        cursor - half
    }
}

/// Render text with specific characters highlighted (for fuzzy match visualization)
fn render_highlighted_text<'a>(
    layout: &mut UiTree<'a>,
    text: &'a str,
    highlight_indices: &[usize],
    base_style: Style,
    config: &Config,
) {
    let highlight_style: Style = (&config.style.picker.matched).into();

    let mut buffer = String::new();

    for (idx, grapheme) in text.graphemes(true).enumerate() {
        let should_highlight = highlight_indices.contains(&idx);

        if should_highlight {
            // Flush non-highlighted buffer
            if !buffer.is_empty() {
                layout_span(layout, (Cow::Owned(buffer.clone()), base_style));
                buffer.clear();
            }
            // Render highlighted character
            layout_span(layout, (Cow::Owned(grapheme.to_string()), highlight_style));
        } else {
            buffer.push_str(grapheme);
        }
    }

    // Flush remaining buffer
    if !buffer.is_empty() {
        layout_span(layout, (Cow::Owned(buffer), base_style));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::picker::{PickerData, PickerItem, PickerState};
    use crate::ui::layout::LayoutTree;
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use itertools::Itertools;
    use std::collections::BTreeMap;

    /// Create a default test config for picker tests
    fn test_config() -> Config {
        use crate::config::{GeneralConfig, PickerBindingsConfig, StyleConfig};

        Config {
            general: GeneralConfig::default(),
            style: StyleConfig::default(),
            bindings: BTreeMap::new().try_into().unwrap(),
            picker_bindings: PickerBindingsConfig::default().try_into().unwrap(),
        }
    }

    fn create_test_items() -> Vec<PickerItem> {
        vec![
            PickerItem::new("main", PickerData::Item("main".to_string())),
            PickerItem::new("develop", PickerData::Item("develop".to_string())),
            PickerItem::new("feature/test", PickerData::Item("feature/test".to_string())),
            PickerItem::new("feature/new", PickerData::Item("feature/new".to_string())),
            PickerItem::new("bugfix/123", PickerData::Item("bugfix/123".to_string())),
        ]
    }

    /// Render the picker layout to a string for testing purposes.
    /// Note: ASCII only — does not support Unicode beyond single-byte chars.
    fn render_to_string(
        computed: crate::ui::layout::Computed<'_, crate::ui::Span<'_>, Style>,
        width: usize,
        height: usize,
    ) -> String {
        let mut grid = vec![' '; height * width];

        for item in computed.iter() {
            let x0 = item.pos[0] as usize;
            let y0 = item.pos[1] as usize;
            let item_width = item.size[0] as usize;
            let text = match item.data {
                crate::ui::layout::Payload::Leaf(crate::ui::Span(cow, _)) => cow.as_ref(),
                crate::ui::layout::Payload::Container(_style) => "",
            };

            for (i, c) in text.chars().take(item_width).enumerate() {
                if y0 < height && x0 + i < width {
                    grid[y0 * width + (x0 + i)] = c;
                }
            }
        }

        grid.chunks(width)
            .map(|row| row.iter().collect::<String>().trim_end().to_string())
            .join("\n")
    }

    #[test]
    fn test_picker_empty_input() {
        let items = create_test_items();
        let state = PickerState::new("Select branch", items, false);
        let config = test_config();

        let mut layout = LayoutTree::new();
        layout.col(crate::ui::layout::opts(), |layout| {
            layout_picker(layout, &state, &config, 40);
        });
        insta::assert_snapshot!(render_to_string(layout.compute([40, 15]), 40, 15));
    }

    #[test]
    fn test_picker_with_filter() {
        let items = create_test_items();
        let mut state = PickerState::new("Select branch", items, false);

        // Type "fea" to filter
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty()));
        state.update_filter();

        let config = test_config();

        let mut layout = LayoutTree::new();
        layout.col(crate::ui::layout::opts(), |layout| {
            layout_picker(layout, &state, &config, 40);
        });
        insta::assert_snapshot!(render_to_string(layout.compute([40, 15]), 40, 15));
    }

    #[test]
    fn test_picker_cursor_movement() {
        let items = create_test_items();
        let mut state = PickerState::new("Select branch", items, false);

        // Move cursor to third item
        state.next();
        state.next();

        let config = test_config();

        let mut layout = LayoutTree::new();
        layout.col(crate::ui::layout::opts(), |layout| {
            layout_picker(layout, &state, &config, 40);
        });
        insta::assert_snapshot!(render_to_string(layout.compute([40, 15]), 40, 15));
    }

    #[test]
    fn test_picker_scroll_many_items() {
        // Create 20 items to test scrolling
        let items: Vec<_> = (0..20)
            .map(|i| {
                PickerItem::new(
                    format!("branch-{:02}", i),
                    PickerData::Item(format!("branch-{:02}", i)),
                )
            })
            .collect();

        let mut state = PickerState::new("Select branch", items, false);
        let config = test_config();

        // Move cursor to middle (position 10)
        for _ in 0..10 {
            state.next();
        }

        let mut layout = LayoutTree::new();
        layout.col(crate::ui::layout::opts(), |layout| {
            layout_picker(layout, &state, &config, 40);
        });
        insta::assert_snapshot!(render_to_string(layout.compute([40, 15]), 40, 15));
    }

    #[test]
    fn test_picker_scroll_near_end() {
        // Create 20 items to test scrolling near the end
        let items: Vec<_> = (0..20)
            .map(|i| {
                PickerItem::new(
                    format!("branch-{:02}", i),
                    PickerData::Item(format!("branch-{:02}", i)),
                )
            })
            .collect();

        let mut state = PickerState::new("Select branch", items, false);
        let config = test_config();

        // Move cursor near end (position 18)
        for _ in 0..18 {
            state.next();
        }

        let mut layout = LayoutTree::new();
        layout.col(crate::ui::layout::opts(), |layout| {
            layout_picker(layout, &state, &config, 40);
        });
        insta::assert_snapshot!(render_to_string(layout.compute([40, 15]), 40, 15));
    }

    #[test]
    fn test_picker_filtered_with_navigation() {
        let items = create_test_items();
        let mut state = PickerState::new("Select branch", items, false);

        // Filter to get feature branches
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty()));
        state.update_filter();

        // Navigate to second item
        state.next();

        let config = test_config();

        let mut layout = LayoutTree::new();
        layout.col(crate::ui::layout::opts(), |layout| {
            layout_picker(layout, &state, &config, 40);
        });
        insta::assert_snapshot!(render_to_string(layout.compute([40, 15]), 40, 15));
    }

    #[test]
    fn test_picker_with_custom_input() {
        let items = create_test_items();
        let mut state = PickerState::new("New branch", items, true);

        // Type a custom branch name
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('m'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::empty()));
        state.update_filter();

        let config = test_config();

        let mut layout = LayoutTree::new();
        layout.col(crate::ui::layout::opts(), |layout| {
            layout_picker(layout, &state, &config, 40);
        });
        insta::assert_snapshot!(render_to_string(layout.compute([40, 15]), 40, 15));
    }

    #[test]
    fn test_picker_no_matches() {
        let items = create_test_items();
        let mut state = PickerState::new("Select branch", items, false);

        // Type something that doesn't match
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::empty()));
        state.update_filter();

        let config = test_config();

        let mut layout = LayoutTree::new();
        layout.col(crate::ui::layout::opts(), |layout| {
            layout_picker(layout, &state, &config, 40);
        });
        insta::assert_snapshot!(render_to_string(layout.compute([40, 15]), 40, 15));
    }

    #[test]
    fn test_picker_narrow_width() {
        let items = create_test_items();
        let state = PickerState::new("Select", items, false);
        let config = test_config();

        let mut layout = LayoutTree::new();
        layout.col(crate::ui::layout::opts(), |layout| {
            layout_picker(layout, &state, &config, 20);
        });
        insta::assert_snapshot!(render_to_string(layout.compute([20, 15]), 20, 15));
    }
}