tui-canvas 0.7.5

Form/textarea for TUI
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
// src/form/render.rs
//! Canvas GUI rendering helpers.

use ratatui::{
    layout::{Alignment, Rect},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Paragraph, Wrap},
    Frame,
};

use crate::canvas::modes::HighlightState;
use crate::canvas::theme::{CanvasTheme, DefaultCanvasTheme};
use crate::data_provider::DataProvider;
use crate::editor::FormEditor;
use crate::gui_utils::{
    clip_inline_completion_with_indicator_padded, compute_h_scroll_with_padding, display_width,
    RIGHT_PAD,
};
use unicode_width::UnicodeWidthChar;

use std::cmp::{max, min};

#[derive(Debug, Clone, Copy)]
/// How to handle overflow when rendering a field's content.
pub enum OverflowMode {
    /// Show an indicator character at the left/right when text is truncated.
    /// Common default is '$'.
    Indicator(char),
    /// Wrap content into multiple visual lines.
    Wrap,
}

#[derive(Debug, Clone, Copy)]
/// Display options controlling canvas rendering behavior.
///
/// Override visual form widths with struct update syntax:
///
/// ```rust
/// # use canvas::{CanvasDisplayOptions, OverflowMode};
/// let opts = CanvasDisplayOptions {
///     max_label_width: 18,
///     max_input_width: Some(40),
///     ..Default::default()
/// };
/// ```
///
/// Override individual row widths with `row_input_width`:
///
/// ```rust
/// # use canvas::CanvasDisplayOptions;
/// let opts = CanvasDisplayOptions {
///     row_input_width: Some(|row, available| match row {
///         0 => 12.min(available),
///         1 => 40.min(available),
///         _ => available,
///     }),
///     ..Default::default()
/// };
/// ```
pub struct CanvasDisplayOptions {
    /// How to handle horizontal overflow for fields.
    pub overflow: OverflowMode,
    /// Maximum label column width, including the trailing space before the input.
    ///
    /// Change this by setting `CanvasDisplayOptions::max_label_width`.
    /// Labels wider than this are visually truncated with `...`.
    pub max_label_width: u16,
    /// Maximum visual width of the input column.
    ///
    /// Change this by setting `CanvasDisplayOptions::max_input_width`.
    /// `Some(width)` caps the rendered input width; `None` uses all remaining space.
    pub max_input_width: Option<u16>,
    /// Optional per-row input width override.
    ///
    /// Change this by setting `CanvasDisplayOptions::row_input_width`.
    /// The callback receives `(row_index, available_width)` and returns the visual
    /// input width for that row.
    pub row_input_width: Option<fn(usize, u16) -> u16>,
}

impl Default for CanvasDisplayOptions {
    fn default() -> Self {
        Self {
            overflow: OverflowMode::Indicator('$'),
            max_label_width: 24,
            max_input_width: Some(25),
            row_input_width: None,
        }
    }
}

impl CanvasDisplayOptions {
    fn input_width_for_row(self, row_index: usize, available_width: u16) -> u16 {
        let width = if let Some(row_input_width) = self.row_input_width {
            row_input_width(row_index, available_width)
        } else {
            self.max_input_width
                .map(|max_width| max_width.min(available_width))
                .unwrap_or(available_width)
        };

        width.min(available_width)
    }
}

/// Utility: clip a string to fit width, append indicator if overflow
fn clip_with_indicator_line<'a>(s: &'a str, width: u16, indicator: char) -> Line<'a> {
    if width == 0 {
        return Line::from("");
    }
    if display_width(s) <= width {
        return Line::from(Span::raw(s));
    }
    let budget = width.saturating_sub(1);
    let mut out = String::new();
    let mut used: u16 = 0;
    for ch in s.chars() {
        let w = UnicodeWidthChar::width(ch).unwrap_or(0) as u16;
        if used + w > budget {
            break;
        }
        out.push(ch);
        used = used.saturating_add(w);
    }
    Line::from(vec![Span::raw(out), Span::raw(indicator.to_string())])
}

fn clip_label_with_ellipsis(s: &str, width: u16) -> String {
    if width == 0 {
        return String::new();
    }
    if display_width(s) <= width {
        return s.to_string();
    }
    if width <= 3 {
        return ".".repeat(width as usize);
    }

    let budget = width - 3;
    let mut out = String::new();
    let mut used: u16 = 0;

    for ch in s.chars() {
        let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0) as u16;
        if used + ch_width > budget {
            break;
        }
        out.push(ch);
        used = used.saturating_add(ch_width);
    }

    out.push_str("...");
    out
}

fn form_label_width(fields: &[&str], max_label_width: u16, area_width: u16) -> u16 {
    if area_width == 0 {
        return 0;
    }

    let longest = fields
        .iter()
        .map(|field| display_width(field))
        .max()
        .unwrap_or(0)
        .saturating_add(1);

    longest.min(max_label_width).min(area_width)
}

fn render_active_line_with_indicator<T: CanvasTheme>(
    typed_text: &str,
    completion: Option<&str>,
    width: u16,
    indicator: char,
    cursor_chars: usize,
    theme: &T,
) -> (Line<'static>, u16, u16) {
    if width == 0 {
        return (Line::from(""), 0, 0);
    }

    // Cursor display column
    let mut cursor_cols: u16 = 0;
    for (i, ch) in typed_text.chars().enumerate() {
        if i >= cursor_chars {
            break;
        }
        cursor_cols = cursor_cols.saturating_add(UnicodeWidthChar::width(ch).unwrap_or(0) as u16);
    }

    let (h_scroll, left_cols) = compute_h_scroll_with_padding(cursor_cols, width);

    (
        clip_inline_completion_with_indicator_padded(
            typed_text,
            completion,
            width,
            indicator,
            h_scroll,
            Style::default().fg(theme.fg()),
            Style::default().fg(theme.suggestion_gray()),
        ),
        h_scroll,
        left_cols,
    )
}

/// Render the canvas into the provided frame using default display options.
///
/// Returns the rectangle of the active input field if present.
pub fn render_canvas<T: CanvasTheme, D: DataProvider>(
    f: &mut Frame,
    area: Rect,
    editor: &FormEditor<D>,
    theme: &T,
) -> Option<Rect> {
    let opts = CanvasDisplayOptions::default();
    render_canvas_with_options(f, area, editor, theme, opts)
}

/// Render the canvas into the provided frame with explicit display options.
///
/// This is the more configurable entrypoint for rendering and is useful for
/// tests or when callers need to override overflow handling.
pub fn render_canvas_with_options<T: CanvasTheme, D: DataProvider>(
    f: &mut Frame,
    area: Rect,
    editor: &FormEditor<D>,
    theme: &T,
    opts: CanvasDisplayOptions,
) -> Option<Rect> {
    let highlight_state = convert_selection_to_highlight(editor.ui_state().selection_state());

    #[cfg(feature = "suggestions")]
    let active_completion = if editor.ui_state().is_suggestions_active()
        && editor.ui_state().suggestions.active_field == Some(editor.ui_state().current_field())
    {
        editor.ui_state().suggestions.completion_text.clone()
    } else {
        None
    };
    #[cfg(not(feature = "suggestions"))]
    let active_completion: Option<String> = None;

    render_canvas_with_highlight_and_options(
        f,
        area,
        editor,
        theme,
        &highlight_state,
        active_completion,
        opts,
    )
}

fn render_canvas_with_highlight_and_options<T: CanvasTheme, D: DataProvider>(
    f: &mut Frame,
    area: Rect,
    editor: &FormEditor<D>,
    theme: &T,
    highlight_state: &HighlightState,
    active_completion: Option<String>,
    opts: CanvasDisplayOptions,
) -> Option<Rect> {
    let ui_state = editor.ui_state();
    let data_provider = editor.data_provider();

    let field_count = data_provider.field_count();
    let mut fields: Vec<&str> = Vec::with_capacity(field_count);
    let mut inputs: Vec<String> = Vec::with_capacity(field_count);

    for i in 0..field_count {
        fields.push(data_provider.field_name(i));
        #[cfg(feature = "validation")]
        {
            inputs.push(editor.display_text_for_field(i));
        }
        #[cfg(not(feature = "validation"))]
        {
            inputs.push(data_provider.field_value(i).to_string());
        }
    }

    let current_field_idx = ui_state.current_field();
    let is_edit_mode = matches!(ui_state.mode(), crate::canvas::modes::AppMode::Ins);

    render_canvas_fields_with_options(
        f,
        area,
        &fields,
        &current_field_idx,
        &inputs,
        theme,
        is_edit_mode,
        highlight_state,
        editor.display_cursor_position(),
        false,
        #[cfg(feature = "validation")]
        |field_idx| editor.display_text_for_field(field_idx),
        #[cfg(not(feature = "validation"))]
        |field_idx| data_provider.field_value(field_idx).to_string(),
        #[cfg(feature = "validation")]
        |field_idx| {
            editor
                .ui_state()
                .validation_state()
                .get_field_config(field_idx)
                .map(|cfg| cfg.custom_formatter.is_some() || cfg.display_mask.is_some())
                .unwrap_or(false)
        },
        #[cfg(not(feature = "validation"))]
        |_field_idx| false,
        active_completion,
        opts,
    )
}

fn convert_selection_to_highlight(
    selection: &crate::canvas::state::SelectionState,
) -> HighlightState {
    use crate::canvas::state::SelectionState;

    match selection {
        SelectionState::None => HighlightState::Off,
        SelectionState::Characterwise { anchor } => {
            HighlightState::Characterwise { anchor: *anchor }
        }
        SelectionState::Linewise { anchor_field } => HighlightState::Linewise {
            anchor_line: *anchor_field,
        },
    }
}

/// Core canvas field rendering with options
fn render_canvas_fields_with_options<T: CanvasTheme, F1, F2>(
    f: &mut Frame,
    area: Rect,
    fields: &[&str],
    current_field_idx: &usize,
    inputs: &[String],
    theme: &T,
    is_edit_mode: bool,
    highlight_state: &HighlightState,
    current_cursor_pos: usize,
    has_unsaved_changes: bool,
    get_display_value: F1,
    has_display_override: F2,
    active_completion: Option<String>,
    opts: CanvasDisplayOptions,
) -> Option<Rect>
where
    F1: Fn(usize) -> String,
    F2: Fn(usize) -> bool,
{
    let label_width = form_label_width(fields, opts.max_label_width, area.width);
    let available_input_width = area.width.saturating_sub(label_width);

    render_field_labels(f, area, label_width, fields, theme);

    let mut active_field_input_rect = None;

    for i in 0..inputs.len() {
        let is_active = i == *current_field_idx;
        let typed_text = get_display_value(i);
        let input_row = Rect {
            x: area.x + label_width,
            y: area.y + i as u16,
            width: opts.input_width_for_row(i, available_input_width),
            height: 1,
        };
        let inner_width = input_row.width;

        let mut h_scroll_for_cursor: u16 = 0;
        let mut left_offset_for_cursor: u16 = 0;

        let line = match highlight_state {
            HighlightState::Characterwise { .. } | HighlightState::Linewise { .. } => {
                apply_highlighting(
                    &typed_text,
                    i,
                    current_field_idx,
                    current_cursor_pos,
                    highlight_state,
                    theme,
                    is_active,
                )
            }

            HighlightState::Off => match opts.overflow {
                OverflowMode::Indicator(ind) => {
                    if is_active {
                        let (l, hs, left_cols) = render_active_line_with_indicator(
                            &typed_text,
                            active_completion.as_deref(),
                            inner_width,
                            ind,
                            current_cursor_pos,
                            theme,
                        );
                        h_scroll_for_cursor = hs;
                        left_offset_for_cursor = left_cols;
                        l
                    } else if display_width(&typed_text) <= inner_width {
                        Line::from(Span::raw(typed_text.clone()))
                    } else {
                        clip_with_indicator_line(&typed_text, inner_width, ind)
                    }
                }

                OverflowMode::Wrap => {
                    if is_active {
                        let mut spans: Vec<Span> = Vec::new();
                        spans.push(Span::styled(
                            typed_text.clone(),
                            Style::default().fg(theme.fg()),
                        ));
                        if let Some(completion) = &active_completion {
                            if !completion.is_empty() {
                                spans.push(Span::styled(
                                    completion.clone(),
                                    Style::default().fg(theme.suggestion_gray()),
                                ));
                            }
                        }
                        Line::from(spans)
                    } else {
                        Line::from(Span::raw(typed_text.clone()))
                    }
                }
            },
        };

        let mut p = Paragraph::new(line).alignment(Alignment::Left);

        if matches!(opts.overflow, OverflowMode::Wrap) {
            p = p.wrap(Wrap { trim: false });
        }

        f.render_widget(p, input_row);

        if is_active {
            active_field_input_rect = Some(input_row);
            set_cursor_position_scrolled(
                f,
                input_row,
                &typed_text,
                current_cursor_pos,
                has_display_override(i),
                h_scroll_for_cursor,
                left_offset_for_cursor,
            );
        }
    }

    active_field_input_rect
}

/// Render field labels
fn render_field_labels<T: CanvasTheme>(
    f: &mut Frame,
    area: Rect,
    label_width: u16,
    fields: &[&str],
    theme: &T,
) {
    if label_width == 0 {
        return;
    }

    let label_text_width = label_width.saturating_sub(1);

    for (i, field) in fields.iter().enumerate() {
        let clipped_label = clip_label_with_ellipsis(field, label_text_width);
        let label = Paragraph::new(Line::from(Span::styled(
            clipped_label,
            Style::default().fg(theme.fg()),
        )));
        f.render_widget(
            label,
            Rect {
                x: area.x,
                y: area.y + i as u16,
                width: label_text_width,
                height: 1,
            },
        );
    }
}

/// Apply highlighting based on highlight state
fn apply_highlighting<'a, T: CanvasTheme>(
    text: &'a str,
    field_index: usize,
    current_field_idx: &usize,
    current_cursor_pos: usize,
    highlight_state: &HighlightState,
    theme: &T,
    is_active: bool,
) -> Line<'a> {
    let text_len = text.chars().count();

    match highlight_state {
        HighlightState::Off => Line::from(Span::styled(text, Style::default().fg(theme.fg()))),
        HighlightState::Characterwise { anchor } => apply_characterwise_highlighting(
            text,
            text_len,
            field_index,
            current_field_idx,
            current_cursor_pos,
            anchor,
            theme,
            is_active,
        ),
        HighlightState::Linewise { anchor_line } => apply_linewise_highlighting(
            text,
            field_index,
            current_field_idx,
            anchor_line,
            theme,
            is_active,
        ),
    }
}

/// Apply characterwise highlighting.
fn apply_characterwise_highlighting<'a, T: CanvasTheme>(
    text: &'a str,
    text_len: usize,
    field_index: usize,
    current_field_idx: &usize,
    current_cursor_pos: usize,
    anchor: &(usize, usize),
    theme: &T,
    _is_active: bool,
) -> Line<'a> {
    let (anchor_field, anchor_char) = *anchor;
    let start_field = min(anchor_field, *current_field_idx);
    let end_field = max(anchor_field, *current_field_idx);

    let highlight_style = Style::default()
        .fg(theme.highlight())
        .bg(theme.highlight_bg())
        .add_modifier(Modifier::BOLD);

    let normal_style = Style::default().fg(theme.fg());

    if field_index >= start_field && field_index <= end_field {
        if start_field == end_field {
            let (start_char, end_char) = if anchor_field == *current_field_idx {
                (
                    min(anchor_char, current_cursor_pos),
                    max(anchor_char, current_cursor_pos),
                )
            } else if anchor_field < *current_field_idx {
                (anchor_char, current_cursor_pos)
            } else {
                (current_cursor_pos, anchor_char)
            };

            let clamped_start = start_char.min(text_len);
            let clamped_end = end_char.min(text_len);

            let before: String = text.chars().take(clamped_start).collect();
            let highlighted: String = text
                .chars()
                .skip(clamped_start)
                .take(clamped_end.saturating_sub(clamped_start) + 1)
                .collect();
            let after: String = text.chars().skip(clamped_end + 1).collect();

            Line::from(vec![
                Span::styled(before, normal_style),
                Span::styled(highlighted, highlight_style),
                Span::styled(after, normal_style),
            ])
        } else if field_index == anchor_field {
            if anchor_field < *current_field_idx {
                let clamped_start = anchor_char.min(text_len);
                let before: String = text.chars().take(clamped_start).collect();
                let highlighted: String = text.chars().skip(clamped_start).collect();

                Line::from(vec![
                    Span::styled(before, normal_style),
                    Span::styled(highlighted, highlight_style),
                ])
            } else {
                let clamped_end = anchor_char.min(text_len);
                let highlighted: String = text.chars().take(clamped_end + 1).collect();
                let after: String = text.chars().skip(clamped_end + 1).collect();

                Line::from(vec![
                    Span::styled(highlighted, highlight_style),
                    Span::styled(after, normal_style),
                ])
            }
        } else if field_index == *current_field_idx {
            if anchor_field < *current_field_idx {
                let clamped_end = current_cursor_pos.min(text_len);
                let highlighted: String = text.chars().take(clamped_end + 1).collect();
                let after: String = text.chars().skip(clamped_end + 1).collect();

                Line::from(vec![
                    Span::styled(highlighted, highlight_style),
                    Span::styled(after, normal_style),
                ])
            } else {
                let clamped_start = current_cursor_pos.min(text_len);
                let before: String = text.chars().take(clamped_start).collect();
                let highlighted: String = text.chars().skip(clamped_start).collect();

                Line::from(vec![
                    Span::styled(before, normal_style),
                    Span::styled(highlighted, highlight_style),
                ])
            }
        } else {
            Line::from(Span::styled(text, highlight_style))
        }
    } else {
        Line::from(Span::styled(text, normal_style))
    }
}

/// Apply linewise highlighting.
fn apply_linewise_highlighting<'a, T: CanvasTheme>(
    text: &'a str,
    field_index: usize,
    current_field_idx: &usize,
    anchor_line: &usize,
    theme: &T,
    _is_active: bool,
) -> Line<'a> {
    let start_field = min(*anchor_line, *current_field_idx);
    let end_field = max(*anchor_line, *current_field_idx);

    let highlight_style = Style::default()
        .fg(theme.highlight())
        .bg(theme.highlight_bg())
        .add_modifier(Modifier::BOLD);

    let normal_style = Style::default().fg(theme.fg());

    if field_index >= start_field && field_index <= end_field {
        Line::from(Span::styled(text, highlight_style))
    } else {
        Line::from(Span::styled(text, normal_style))
    }
}

/// Set cursor position (x clamp only; no Y offset with wrap in this version)
fn set_cursor_position_scrolled(
    f: &mut Frame,
    field_rect: Rect,
    text: &str,
    current_cursor_pos: usize,
    _has_display_override: bool,
    h_scroll: u16,
    left_offset: u16,
) {
    let mut cols: u16 = 0;
    for (i, ch) in text.chars().enumerate() {
        if i >= current_cursor_pos {
            break;
        }
        cols = cols.saturating_add(UnicodeWidthChar::width(ch).unwrap_or(0) as u16);
    }

    let mut visible_x = cols.saturating_sub(h_scroll).saturating_add(left_offset);

    let limit = field_rect.width.saturating_sub(1 + RIGHT_PAD);
    if visible_x > limit {
        visible_x = limit;
    }

    let cursor_x = field_rect.x.saturating_add(visible_x);
    let cursor_y = field_rect.y;
    f.set_cursor_position((cursor_x, cursor_y));
}

pub fn render_canvas_default<D: DataProvider>(
    f: &mut Frame,
    area: Rect,
    editor: &FormEditor<D>,
) -> Option<Rect> {
    let theme = DefaultCanvasTheme;
    render_canvas(f, area, editor, &theme)
}