tui-canvas 0.8.10

Form/textarea/input 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
// examples/computed_fields.rs - COMPLETE WORKING VERSION
//! Demonstrates computed fields with the canvas library - Invoice Calculator Example
//!
//! This example REQUIRES the `computed` feature to compile.
//!
//! Run with:
//! cargo run --example computed_fields --features "gui,computed"

#[cfg(not(feature = "computed"))]
compile_error!(
    "This example requires the 'computed' feature. \
     Run with: cargo run --example computed_fields --features \"gui,computed\""
);

use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyModifiers},
    execute,
    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ratatui::{
    Frame, Terminal,
    backend::{Backend, CrosstermBackend},
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph, Wrap},
};
use std::io;

use tui_canvas::{
    AppMode, DataProvider, TextFormState,
    computed::{ComputedContext, ComputedProvider},
    render_canvas_default,
};

/// Invoice data with computed fields
struct InvoiceData {
    fields: Vec<(String, String)>,
    computed_indices: std::collections::HashSet<usize>,
}

impl InvoiceData {
    fn new() -> Self {
        let mut computed_indices = std::collections::HashSet::new();

        // Mark computed fields (read-only, calculated)
        computed_indices.insert(4); // Subtotal
        computed_indices.insert(5); // Tax Amount
        computed_indices.insert(6); // Total

        Self {
            fields: vec![
                ("📦 Product Name".to_string(), "".to_string()),
                ("🔢 Quantity".to_string(), "".to_string()),
                ("💰 Unit Price ($)".to_string(), "".to_string()),
                ("📊 Tax Rate (%)".to_string(), "".to_string()),
                ("➕ Subtotal ($)".to_string(), "".to_string()), // COMPUTED
                ("🧾 Tax Amount ($)".to_string(), "".to_string()), // COMPUTED
                ("💳 Total ($)".to_string(), "".to_string()),    // COMPUTED
                ("📝 Notes".to_string(), "".to_string()),
            ],
            computed_indices,
        }
    }
}

impl DataProvider for InvoiceData {
    fn field_count(&self) -> usize {
        self.fields.len()
    }

    fn field_name(&self, index: usize) -> &str {
        &self.fields[index].0
    }

    fn field_value(&self, index: usize) -> &str {
        &self.fields[index].1
    }

    fn set_field_value(&mut self, index: usize, value: String) {
        self.fields[index].1 = value;
    }

    fn supports_suggestions(&self, _field_index: usize) -> bool {
        false
    }

    fn display_value(&self, _index: usize) -> Option<&str> {
        None
    }

    /// Mark computed fields
    fn is_computed_field(&self, field_index: usize) -> bool {
        self.computed_indices.contains(&field_index)
    }

    /// Get computed field values
    fn computed_field_value(&self, field_index: usize) -> Option<String> {
        if self.computed_indices.contains(&field_index) {
            Some(self.fields[field_index].1.clone())
        } else {
            None
        }
    }
}

/// Invoice calculator - computes totals based on input fields
struct InvoiceCalculator;

impl ComputedProvider for InvoiceCalculator {
    fn compute_field(&mut self, context: ComputedContext) -> String {
        // Helper to parse field values safely
        let parse_field = |index: usize| -> f64 {
            let value = context.field_values[index].trim();
            if value.is_empty() {
                0.0
            } else {
                value.parse().unwrap_or(0.0)
            }
        };

        match context.target_field {
            4 => {
                // Subtotal = Quantity × Unit Price
                let qty = parse_field(1);
                let price = parse_field(2);
                let subtotal = qty * price;

                if qty == 0.0 || price == 0.0 {
                    "".to_string() // Show empty if no meaningful calculation
                } else {
                    format!("{subtotal:.2}")
                }
            }
            5 => {
                // Tax Amount = Subtotal × (Tax Rate / 100)
                let qty = parse_field(1);
                let price = parse_field(2);
                let tax_rate = parse_field(3);
                let subtotal = qty * price;
                let tax_amount = subtotal * (tax_rate / 100.0);

                if subtotal == 0.0 || tax_rate == 0.0 {
                    "".to_string()
                } else {
                    format!("{tax_amount:.2}")
                }
            }
            6 => {
                // Total = Subtotal + Tax Amount
                let qty = parse_field(1);
                let price = parse_field(2);
                let tax_rate = parse_field(3);
                let subtotal = qty * price;

                if subtotal == 0.0 {
                    "".to_string()
                } else {
                    let tax_amount = subtotal * (tax_rate / 100.0);
                    let total = subtotal + tax_amount;
                    format!("{total:.2}")
                }
            }
            _ => "".to_string(),
        }
    }

    fn handles_field(&self, field_index: usize) -> bool {
        matches!(field_index, 4..=6) // Subtotal, Tax Amount, Total
    }

    fn field_dependencies(&self, field_index: usize) -> Vec<usize> {
        match field_index {
            4 => vec![1, 2],    // Subtotal depends on Quantity, Unit Price
            5 => vec![1, 2, 3], // Tax Amount depends on Quantity, Unit Price, Tax Rate
            6 => vec![1, 2, 3], // Total depends on Quantity, Unit Price, Tax Rate
            _ => vec![],
        }
    }
}

/// Editor with computed fields
struct ComputedFieldsEditor<D: DataProvider> {
    editor: TextFormState<D>,
    calculator: InvoiceCalculator,
    debug_message: String,
    last_computed_values: Vec<String>,
}

impl<D: DataProvider> ComputedFieldsEditor<D> {
    fn new(data_provider: D) -> Self {
        let mut editor = TextFormState::new(data_provider);
        editor.set_computed_provider(InvoiceCalculator);

        let calculator = InvoiceCalculator;
        let last_computed_values = vec!["".to_string(); 8];

        Self {
            editor,
            calculator,
            debug_message: "💰 Invoice Calculator - Start typing in fields to see calculations!"
                .to_string(),
            last_computed_values,
        }
    }

    fn is_computed_field(&self, field_index: usize) -> bool {
        self.editor.ui_state().is_computed_field(field_index)
    }

    fn update_computed_fields(&mut self) {
        self.editor.recompute_all_fields(&mut self.calculator);

        for i in [4, 5, 6] {
            // Computed field indices
            let computed_value = self.editor.effective_field_value(i);
            self.editor
                .data_provider_mut()
                .set_field_value(i, computed_value.clone());
        }

        let mut changed = false;
        let mut has_calculations = false;

        for i in [4, 5, 6] {
            let new_value = self.editor.effective_field_value(i);
            if new_value != self.last_computed_values[i] {
                changed = true;
                self.last_computed_values[i] = new_value.clone();
            }
            if !new_value.is_empty() {
                has_calculations = true;
            }
        }

        if changed {
            if has_calculations {
                let subtotal = &self.last_computed_values[4];
                let tax = &self.last_computed_values[5];
                let total = &self.last_computed_values[6];

                let mut parts = Vec::new();
                if !subtotal.is_empty() {
                    parts.push(format!("Subtotal=${subtotal}"));
                }
                if !tax.is_empty() {
                    parts.push(format!("Tax=${tax}"));
                }
                if !total.is_empty() {
                    parts.push(format!("Total=${total}"));
                }

                if !parts.is_empty() {
                    self.debug_message = format!("🧮 Calculated: {}", parts.join(", "));
                } else {
                    self.debug_message =
                        "💰 Enter Quantity and Unit Price to see calculations".to_string();
                }
            } else {
                self.debug_message =
                    "💰 Enter Quantity and Unit Price to see calculations".to_string();
            }
        }
    }

    fn insert_char(&mut self, ch: char) -> anyhow::Result<()> {
        let current_field = self.editor.current_field();
        let result = self.editor.insert_char(ch);

        if result.is_ok() && matches!(current_field, 1..=3) {
            self.editor
                .on_field_changed(&mut self.calculator, current_field);
            self.update_computed_fields();
        }

        result
    }

    fn delete_backward(&mut self) -> anyhow::Result<()> {
        let current_field = self.editor.current_field();
        let result = self.editor.delete_backward();

        if result.is_ok() && matches!(current_field, 1..=3) {
            self.editor
                .on_field_changed(&mut self.calculator, current_field);
            self.update_computed_fields();
        }

        result
    }

    fn delete_forward(&mut self) -> anyhow::Result<()> {
        let current_field = self.editor.current_field();
        let result = self.editor.delete_forward();

        if result.is_ok() && matches!(current_field, 1..=3) {
            self.editor
                .on_field_changed(&mut self.calculator, current_field);
            self.update_computed_fields();
        }

        result
    }

    fn next_field(&mut self) {
        let old_field = self.editor.current_field();
        let _ = self.editor.next_field();
        let new_field = self.editor.current_field();

        if old_field != new_field {
            let field_name = self.editor.data_provider().field_name(new_field);
            let field_type = if self.is_computed_field(new_field) {
                "computed (read-only)"
            } else {
                "editable"
            };
            self.debug_message = format!("{field_name} - {field_type} field");
        }
    }

    fn prev_field(&mut self) {
        let old_field = self.editor.current_field();
        let _ = self.editor.prev_field();
        let new_field = self.editor.current_field();

        if old_field != new_field {
            let field_name = self.editor.data_provider().field_name(new_field);
            let field_type = if self.is_computed_field(new_field) {
                "computed (read-only)"
            } else {
                "editable"
            };
            self.debug_message = format!("{field_name} - {field_type} field");
        }
    }

    fn enter_edit_mode(&mut self) {
        let current = self.editor.current_field();

        // Double protection: check both ways
        if self.editor.data_provider().is_computed_field(current) || self.is_computed_field(current)
        {
            let field_name = self.editor.data_provider().field_name(current);
            self.debug_message = format!(
                "🚫 {field_name} is computed (read-only) - Press Tab to move to editable fields"
            );
            return;
        }

        self.editor.enter_edit_mode();
        let field_name = self.editor.data_provider().field_name(current);
        self.debug_message = format!("✏️ Editing {field_name} - Type to see calculations update");
    }

    fn enter_append_mode(&mut self) {
        let current = self.editor.current_field();

        if self.editor.data_provider().is_computed_field(current) || self.is_computed_field(current)
        {
            let field_name = self.editor.data_provider().field_name(current);
            self.debug_message = format!(
                "🚫 {field_name} is computed (read-only) - Press Tab to move to editable fields"
            );
            return;
        }

        self.editor.enter_append_mode();
        let field_name = self.editor.data_provider().field_name(current);
        self.debug_message = format!("✏️ Appending to {field_name} - Type to see calculations");
    }

    fn exit_edit_mode(&mut self) {
        let current_field = self.editor.current_field();
        self.editor.exit_edit_mode();

        if matches!(current_field, 1..=3) {
            self.editor
                .on_field_changed(&mut self.calculator, current_field);
            self.update_computed_fields();
        }

        self.debug_message = "🔒 Normal mode - Press 'i' to edit fields".to_string();
    }

    // Delegate methods
    fn current_field(&self) -> usize {
        self.editor.current_field()
    }
    fn cursor_position(&self) -> usize {
        self.editor.cursor_position()
    }
    fn mode(&self) -> AppMode {
        self.editor.mode()
    }
    fn current_text(&self) -> &str {
        let field_index = self.editor.current_field();
        self.editor.data_provider().field_value(field_index)
    }
    fn data_provider(&self) -> &D {
        self.editor.data_provider()
    }
    fn ui_state(&self) -> &tui_canvas::EditorState {
        self.editor.ui_state()
    }
    fn move_left(&mut self) {
        self.editor.move_left();
    }
    fn move_right(&mut self) {
        self.editor.move_right();
    }
    fn move_up(&mut self) {
        let _ = self.editor.move_up();
    }
    fn move_down(&mut self) {
        let _ = self.editor.move_down();
    }
}

fn handle_key_press(
    key: KeyCode,
    modifiers: KeyModifiers,
    editor: &mut ComputedFieldsEditor<InvoiceData>,
) -> anyhow::Result<bool> {
    let mode = editor.mode();

    if (key == KeyCode::Char('q') && modifiers.contains(KeyModifiers::CONTROL))
        || (key == KeyCode::Char('c') && modifiers.contains(KeyModifiers::CONTROL))
        || key == KeyCode::F(10)
    {
        return Ok(false);
    }

    match (mode, key, modifiers) {
        (AppMode::Nor, KeyCode::Char('i'), _) => {
            editor.enter_edit_mode();
        }
        (AppMode::Nor, KeyCode::Char('a'), _) => {
            editor.enter_append_mode();
        }
        (AppMode::Nor, KeyCode::Char('A'), _) => {
            editor.editor.move_line_end();
            editor.enter_edit_mode();
        }
        (_, KeyCode::Esc, _) => {
            if mode == AppMode::Ins {
                editor.exit_edit_mode();
            }
        }

        // Movement
        (AppMode::Nor, KeyCode::Char('h'), _) | (AppMode::Nor, KeyCode::Left, _) => {
            editor.move_left();
        }
        (AppMode::Nor, KeyCode::Char('l'), _) | (AppMode::Nor, KeyCode::Right, _) => {
            editor.move_right();
        }
        (AppMode::Nor, KeyCode::Char('j'), _) | (AppMode::Nor, KeyCode::Down, _) => {
            editor.move_down();
        }
        (AppMode::Nor, KeyCode::Char('k'), _) | (AppMode::Nor, KeyCode::Up, _) => {
            editor.move_up();
        }

        // Edit mode movement
        (AppMode::Ins, KeyCode::Left, _) => {
            editor.move_left();
        }
        (AppMode::Ins, KeyCode::Right, _) => {
            editor.move_right();
        }
        (AppMode::Ins, KeyCode::Up, _) => {
            editor.move_up();
        }
        (AppMode::Ins, KeyCode::Down, _) => {
            editor.move_down();
        }

        // Navigation
        (_, KeyCode::Tab, _) => {
            editor.next_field();
        }
        (_, KeyCode::BackTab, _) => {
            editor.prev_field();
        }

        // Editing
        (AppMode::Ins, KeyCode::Char(c), m) if !m.contains(KeyModifiers::CONTROL) => {
            editor.insert_char(c)?;
        }
        (AppMode::Ins, KeyCode::Backspace, _) => {
            editor.delete_backward()?;
        }
        (AppMode::Ins, KeyCode::Delete, _) => {
            editor.delete_forward()?;
        }

        // Debug info
        (AppMode::Nor, KeyCode::Char('?'), _) => {
            let current = editor.current_field();
            let field_name = editor.data_provider().field_name(current);
            let field_type = if editor.is_computed_field(current) {
                "COMPUTED (read-only)"
            } else {
                "EDITABLE"
            };
            editor.debug_message = format!(
                "{} - {} - Position {} - Mode: {:?}",
                field_name,
                field_type,
                editor.cursor_position(),
                mode
            );
        }

        _ => {}
    }

    Ok(true)
}

fn run_app<B: Backend<Error = io::Error>>(
    terminal: &mut Terminal<B>,
    mut editor: ComputedFieldsEditor<InvoiceData>,
) -> io::Result<()> {
    editor.update_computed_fields(); // Initial computation

    loop {
        terminal.draw(|f| ui(f, &editor))?;

        if let Event::Key(key) = event::read()? {
            match handle_key_press(key.code, key.modifiers, &mut editor) {
                Ok(should_continue) => {
                    if !should_continue {
                        break;
                    }
                }
                Err(e) => {
                    editor.debug_message = format!("Error: {e}");
                }
            }
        }
    }

    Ok(())
}

fn ui(f: &mut Frame, editor: &ComputedFieldsEditor<InvoiceData>) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(8), Constraint::Length(10)])
        .split(f.area());

    render_enhanced_canvas(f, chunks[0], editor);
    render_computed_status(f, chunks[1], editor);
}

fn render_enhanced_canvas(f: &mut Frame, area: Rect, editor: &ComputedFieldsEditor<InvoiceData>) {
    render_canvas_default(f, area, &editor.editor);
}

fn render_computed_status(f: &mut Frame, area: Rect, editor: &ComputedFieldsEditor<InvoiceData>) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(3), Constraint::Length(7)])
        .split(area);

    let mode_text = match editor.mode() {
        AppMode::Ins => "INSERT",
        AppMode::Nor => "NORMAL",
        _ => "OTHER",
    };

    let current = editor.current_field();
    let field_status = if editor.is_computed_field(current) {
        "📊 COMPUTED FIELD (read-only)"
    } else {
        "✏️ EDITABLE FIELD"
    };

    let status_text = format!(
        "-- {} -- {} | {}",
        mode_text, field_status, editor.debug_message
    );

    let status = Paragraph::new(Line::from(Span::raw(status_text))).block(
        Block::default()
            .borders(Borders::ALL)
            .title("💰 Invoice Calculator"),
    );

    f.render_widget(status, chunks[0]);

    let help_text = match editor.mode() {
        AppMode::Nor => {
            "💰 COMPUTED FIELDS DEMO: Real-time invoice calculations!\n\
             🔢 EDITABLE: Product, Quantity, Unit Price, Tax Rate, Notes\n\
             📊 COMPUTED: Subtotal, Tax Amount, Total (calculated automatically)\n\
             \n\
             🚀 START: Press 'i' to edit Quantity, type '5', Tab to Unit Price, type '19.99'\n\
             Watch Subtotal and Total appear! Add Tax Rate to see tax calculations.\n\
             Navigation: Tab/Shift+Tab skips computed fields automatically"
        }
        AppMode::Ins => {
            "✏️ EDIT MODE: Type numbers to see calculations appear!\n\
             \n\
             💡 EXAMPLE: Type '5' in Quantity, then Tab to Unit Price and type '19.99'\n\
             • Subtotal appears: $99.95\n\
             • Total appears: $99.95\n\
             • Add Tax Rate (like '10') to see tax: $9.99, Total: $109.94\n\
             \n\
             Esc=normal, Tab=next field (auto-skips computed fields)"
        }
        _ => "💰 Invoice Calculator with Computed Fields",
    };

    let help_style = if editor.is_computed_field(editor.current_field()) {
        Style::default()
            .fg(Color::Yellow)
            .add_modifier(Modifier::ITALIC)
    } else {
        Style::default().fg(Color::Gray)
    };

    let help = Paragraph::new(help_text)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title("🚀 Try It Now!"),
        )
        .style(help_style)
        .wrap(Wrap { trim: true });

    f.render_widget(help, chunks[1]);
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("💰 Canvas Computed Fields Demo - Invoice Calculator");
    println!("✅ computed feature: ENABLED");
    println!("🚀 QUICK TEST:");
    println!("   1. Press 'i' to edit Quantity");
    println!("   2. Type '5' and press Tab");
    println!("   3. Type '19.99' in Unit Price");
    println!("   4. Watch Subtotal ($99.95) and Total ($99.95) appear!");
    println!();

    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let data = InvoiceData::new();
    let editor = ComputedFieldsEditor::new(data);

    let res = run_app(&mut terminal, editor);

    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;

    if let Err(err) = res {
        println!("{err:?}");
    }

    println!("💰 Demo completed! Computed fields should have updated in real-time!");
    Ok(())
}