mathypad 0.1.10

A smart TUI calculator that understands units and makes complex calculations simple.
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
//! UI rendering functions

use crate::expression::parse_line_reference;
use crate::units::parse_unit;
use crate::{App, Mode};
use ratatui::{
    Frame,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph, Wrap},
};
use std::collections::HashMap;

/// Animate a color by interpolating its intensity based on opacity
fn animate_color(base_color: Color, opacity: f32) -> Color {
    match base_color {
        Color::Green => {
            // Fade from dark green to bright green
            let intensity = (opacity * 255.0) as u8;
            Color::Rgb(0, intensity, 0)
        }
        Color::Red => {
            let intensity = (opacity * 255.0) as u8;
            Color::Rgb(intensity, 0, 0)
        }
        Color::Blue => {
            let intensity = (opacity * 255.0) as u8;
            Color::Rgb(0, 0, intensity)
        }
        Color::Yellow => {
            let intensity = (opacity * 255.0) as u8;
            Color::Rgb(intensity, intensity, 0)
        }
        Color::Cyan => {
            let intensity = (opacity * 255.0) as u8;
            Color::Rgb(0, intensity, intensity)
        }
        Color::Magenta => {
            let intensity = (opacity * 255.0) as u8;
            Color::Rgb(intensity, 0, intensity)
        }
        _ => base_color, // For other colors, just return as-is
    }
}

/// Create a flash effect color that brightens based on opacity
fn create_flash_color(opacity: f32) -> Color {
    // Create a bright flash effect that fades from white to normal
    let intensity = (opacity * 255.0) as u8;
    Color::Rgb(255, 255, intensity.max(200)) // Bright white/yellow flash
}

/// Main UI layout and rendering
pub fn ui(f: &mut Frame, app: &App) {
    let text_percentage = app.separator_position;
    let results_percentage = 100 - app.separator_position;

    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(text_percentage),
            Constraint::Percentage(results_percentage),
        ])
        .split(f.area());

    render_text_area(f, app, chunks[0]);
    render_results_panel(f, app, chunks[1]);

    // Render separator visual feedback if hovering or dragging
    if app.is_dragging_separator || app.is_hovering_separator {
        render_separator_indicator(f, app, f.area());
    }

    // Render dialogs on top if needed
    if app.show_unsaved_dialog {
        render_unsaved_dialog(f, app, f.area());
    } else if app.show_save_as_dialog {
        render_save_as_dialog(f, app, f.area());
    }
}

/// Render the main text editing area
pub fn render_text_area(f: &mut Frame, app: &App, area: Rect) {
    let title = if app.has_unsaved_changes {
        "Mathypad * "
    } else {
        "Mathypad"
    };
    let block = match app.mode {
        Mode::Insert => Block::default().title(title).borders(Borders::ALL),
        Mode::Normal => Block::default()
            .title(title)
            .borders(Borders::ALL)
            .title_bottom(" NORMAL "),
    };

    let inner_area = block.inner(area);
    f.render_widget(block, area);

    let visible_height = inner_area.height as usize;
    let start_line = app.scroll_offset;
    let end_line = (start_line + visible_height).min(app.text_lines.len());

    let mut lines = Vec::new();
    for (i, line_text) in app.text_lines[start_line..end_line].iter().enumerate() {
        let line_num = start_line + i + 1;
        let line_num_str = format!("{:4} ", line_num);
        let line_index = start_line + i;

        let mut spans = vec![Span::styled(
            line_num_str,
            Style::default().fg(Color::DarkGray),
        )];

        // Check if this line has a copy flash animation for the text area (not result area)
        let line_style = if let Some(animation) = app.get_copy_flash_animation(line_index) {
            // Only flash if this was a text area copy (not result area)
            if line_index < app.copy_flash_is_result.len() && !app.copy_flash_is_result[line_index]
            {
                let opacity = animation.opacity();
                Style::default().bg(create_flash_color(opacity))
            } else {
                Style::default()
            }
        } else {
            Style::default()
        };

        if start_line + i == app.cursor_line {
            // Parse with cursor highlighting
            let mut colored_spans =
                parse_colors_with_cursor(line_text, app.cursor_col, &app.variables);
            // Apply flash background to all spans if flashing
            if line_style.bg.is_some() {
                for span in &mut colored_spans {
                    span.style = span.style.patch(line_style);
                }
            }
            spans.extend(colored_spans);
        } else {
            let mut colored_spans = parse_colors(line_text, &app.variables);
            // Apply flash background to all spans if flashing
            if line_style.bg.is_some() {
                for span in &mut colored_spans {
                    span.style = span.style.patch(line_style);
                }
            }
            spans.extend(colored_spans);
        }

        lines.push(Line::from(spans));
    }

    let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false });
    f.render_widget(paragraph, inner_area);
}

/// Render the results panel
pub fn render_results_panel(f: &mut Frame, app: &App, area: Rect) {
    let block = Block::default().title("Results").borders(Borders::ALL);

    let inner_area = block.inner(area);
    f.render_widget(block, area);

    let visible_height = inner_area.height as usize;
    let start_line = app.scroll_offset;
    let end_line = (start_line + visible_height).min(app.results.len());

    let mut lines = Vec::new();
    for (i, result) in app.results[start_line..end_line].iter().enumerate() {
        let line_num = start_line + i + 1;
        let line_num_str = format!("{:4} ", line_num);
        let line_index = start_line + i;

        let mut spans = vec![Span::styled(
            line_num_str,
            Style::default().fg(Color::DarkGray),
        )];

        // Check if this line has a copy flash animation for the results area (not text area)
        let flash_style = if let Some(animation) = app.get_copy_flash_animation(line_index) {
            // Only flash if this was a result area copy (not text area)
            if line_index < app.copy_flash_is_result.len() && app.copy_flash_is_result[line_index] {
                let opacity = animation.opacity();
                Some(Style::default().bg(create_flash_color(opacity)))
            } else {
                None
            }
        } else {
            None
        };

        if let Some(value) = result {
            // Get animation state for this line
            let color = if let Some(animation) = app.get_result_animation(line_index) {
                // Apply fade-in animation by adjusting color intensity
                let opacity = animation.opacity();
                animate_color(Color::Green, opacity)
            } else {
                Color::Green
            };

            let mut result_style = Style::default().fg(color);
            // Apply flash background if flashing
            if let Some(flash) = flash_style {
                result_style = result_style.patch(flash);
            }

            spans.push(Span::styled(value.clone(), result_style));
        }

        lines.push(Line::from(spans));
    }

    let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false });
    f.render_widget(paragraph, inner_area);
}

/// Parse text and return colored spans for syntax highlighting
pub fn parse_colors<'a>(text: &'a str, variables: &'a HashMap<String, String>) -> Vec<Span<'a>> {
    let mut spans = Vec::new();
    let mut current_pos = 0;
    let chars: Vec<char> = text.chars().collect();

    while current_pos < chars.len() {
        if chars[current_pos].is_ascii_alphabetic() {
            // Handle potential units, keywords, and line references first
            let start_pos = current_pos;

            while current_pos < chars.len()
                && (chars[current_pos].is_ascii_alphabetic()
                    || chars[current_pos].is_ascii_digit()
                    || chars[current_pos] == '/')
            {
                current_pos += 1;
            }

            let word_text: String = chars[start_pos..current_pos].iter().collect();

            // Check if it's a valid unit, keyword, line reference, or variable
            if parse_line_reference(&word_text).is_some() {
                spans.push(Span::styled(word_text, Style::default().fg(Color::Magenta)));
            } else if word_text.to_lowercase() == "to"
                || word_text.to_lowercase() == "in"
                || word_text.to_lowercase() == "of"
            {
                spans.push(Span::styled(word_text, Style::default().fg(Color::Yellow)));
            } else if parse_unit(&word_text).is_some() {
                spans.push(Span::styled(word_text, Style::default().fg(Color::Green)));
            } else if variables.contains_key(&word_text) {
                // Highlight variables that are defined
                spans.push(Span::styled(
                    word_text,
                    Style::default().fg(Color::LightCyan),
                ));
            } else {
                spans.push(Span::raw(word_text));
            }
        } else if chars[current_pos].is_ascii_digit() || chars[current_pos] == '.' {
            // Handle numbers
            let start_pos = current_pos;
            let mut has_digit = false;
            let mut has_dot = false;

            while current_pos < chars.len() {
                let ch = chars[current_pos];
                if ch.is_ascii_digit() {
                    has_digit = true;
                    current_pos += 1;
                } else if ch == '.' && !has_dot {
                    has_dot = true;
                    current_pos += 1;
                } else if ch == ',' {
                    current_pos += 1;
                } else {
                    break;
                }
            }

            if has_digit {
                let number_text: String = chars[start_pos..current_pos].iter().collect();
                spans.push(Span::styled(
                    number_text,
                    Style::default().fg(Color::LightBlue),
                ));
            } else {
                spans.push(Span::raw(chars[start_pos].to_string()));
                current_pos = start_pos + 1;
            }
        } else if chars[current_pos] == '%' {
            // Handle percentage symbol as a unit
            spans.push(Span::styled(
                "%".to_string(),
                Style::default().fg(Color::Green),
            ));
            current_pos += 1;
        } else if "+-*/()=".contains(chars[current_pos]) {
            // Handle operators (including assignment)
            spans.push(Span::styled(
                chars[current_pos].to_string(),
                Style::default().fg(Color::Cyan),
            ));
            current_pos += 1;
        } else {
            // Handle other characters
            spans.push(Span::raw(chars[current_pos].to_string()));
            current_pos += 1;
        }
    }

    spans
}

/// Parse text and return colored spans with cursor highlighting
pub fn parse_colors_with_cursor<'a>(
    text: &'a str,
    cursor_col: usize,
    variables: &'a HashMap<String, String>,
) -> Vec<Span<'a>> {
    let mut spans = Vec::new();
    let mut current_pos = 0;
    let chars: Vec<char> = text.chars().collect();
    let mut char_index = 0; // Track character position for cursor

    while current_pos < chars.len() {
        if chars[current_pos].is_ascii_alphabetic() {
            // Handle potential units, keywords, and line references first
            let start_pos = current_pos;
            let start_char_index = char_index;

            while current_pos < chars.len()
                && (chars[current_pos].is_ascii_alphabetic()
                    || chars[current_pos].is_ascii_digit()
                    || chars[current_pos] == '/')
            {
                current_pos += 1;
                char_index += 1;
            }

            let word_text: String = chars[start_pos..current_pos].iter().collect();

            // Determine the style for this word
            let style = if parse_line_reference(&word_text).is_some() {
                Style::default().fg(Color::Magenta)
            } else if word_text.to_lowercase() == "to"
                || word_text.to_lowercase() == "in"
                || word_text.to_lowercase() == "of"
            {
                Style::default().fg(Color::Yellow)
            } else if parse_unit(&word_text).is_some() {
                Style::default().fg(Color::Green)
            } else if variables.contains_key(&word_text) {
                Style::default().fg(Color::LightCyan)
            } else {
                Style::default()
            };

            // Check if cursor is within this word
            if cursor_col >= start_char_index && cursor_col < char_index {
                // Split the word to highlight the cursor character
                let cursor_offset = cursor_col - start_char_index;
                let word_chars: Vec<char> = word_text.chars().collect();

                if cursor_offset > 0 {
                    let before: String = word_chars[..cursor_offset].iter().collect();
                    spans.push(Span::styled(before, style));
                }

                let cursor_char = word_chars[cursor_offset];
                spans.push(Span::styled(
                    cursor_char.to_string(),
                    style.bg(Color::White).fg(Color::Black),
                ));

                if cursor_offset + 1 < word_chars.len() {
                    let after: String = word_chars[cursor_offset + 1..].iter().collect();
                    spans.push(Span::styled(after, style));
                }
            } else {
                spans.push(Span::styled(word_text, style));
            }
        } else if chars[current_pos].is_ascii_digit() || chars[current_pos] == '.' {
            // Handle numbers
            let start_pos = current_pos;
            let start_char_index = char_index;
            let mut has_digit = false;
            let mut has_dot = false;

            while current_pos < chars.len() {
                let ch = chars[current_pos];
                if ch.is_ascii_digit() {
                    has_digit = true;
                    current_pos += 1;
                    char_index += 1;
                } else if ch == '.' && !has_dot {
                    has_dot = true;
                    current_pos += 1;
                    char_index += 1;
                } else if ch == ',' {
                    current_pos += 1;
                    char_index += 1;
                } else {
                    break;
                }
            }

            if has_digit {
                let number_text: String = chars[start_pos..current_pos].iter().collect();
                let style = Style::default().fg(Color::LightBlue);

                // Check if cursor is within this number
                if cursor_col >= start_char_index && cursor_col < char_index {
                    let cursor_offset = cursor_col - start_char_index;
                    let number_chars: Vec<char> = number_text.chars().collect();

                    if cursor_offset > 0 {
                        let before: String = number_chars[..cursor_offset].iter().collect();
                        spans.push(Span::styled(before, style));
                    }

                    let cursor_char = number_chars[cursor_offset];
                    spans.push(Span::styled(
                        cursor_char.to_string(),
                        style.bg(Color::White).fg(Color::Black),
                    ));

                    if cursor_offset + 1 < number_chars.len() {
                        let after: String = number_chars[cursor_offset + 1..].iter().collect();
                        spans.push(Span::styled(after, style));
                    }
                } else {
                    spans.push(Span::styled(number_text, style));
                }
            } else {
                let ch = chars[start_pos];
                if cursor_col == char_index {
                    spans.push(Span::styled(
                        ch.to_string(),
                        Style::default().bg(Color::White).fg(Color::Black),
                    ));
                } else {
                    spans.push(Span::raw(ch.to_string()));
                }
                current_pos = start_pos + 1;
                char_index += 1;
            }
        } else {
            // Handle single characters (operators, punctuation, etc.)
            let ch = chars[current_pos];
            let style = if ch == '%' {
                Style::default().fg(Color::Green)
            } else if "+-*/()=".contains(ch) {
                Style::default().fg(Color::Cyan)
            } else {
                Style::default()
            };

            if cursor_col == char_index {
                spans.push(Span::styled(
                    ch.to_string(),
                    style.bg(Color::White).fg(Color::Black),
                ));
            } else {
                spans.push(Span::styled(ch.to_string(), style));
            }

            current_pos += 1;
            char_index += 1;
        }
    }

    // If cursor is at the end of the line, add a space with cursor background
    if cursor_col == char_index {
        spans.push(Span::styled(
            " ",
            Style::default().bg(Color::White).fg(Color::Black),
        ));
    }

    spans
}

/// Render the unsaved changes confirmation dialog
pub fn render_unsaved_dialog(f: &mut Frame, app: &App, area: Rect) {
    use ratatui::widgets::Clear;

    // Calculate dialog size and position (centered)
    let dialog_width = 60;
    let dialog_height = 8;
    let x = (area.width.saturating_sub(dialog_width)) / 2;
    let y = (area.height.saturating_sub(dialog_height)) / 2;

    let dialog_area = Rect {
        x: area.x + x,
        y: area.y + y,
        width: dialog_width,
        height: dialog_height,
    };

    // Clear the background for the dialog
    f.render_widget(Clear, dialog_area);

    // Create the dialog block
    let block = Block::default()
        .title(" Unsaved Changes ")
        .borders(Borders::ALL)
        .style(Style::default().bg(Color::DarkGray).fg(Color::White));

    // Create the dialog content
    let filename = app
        .file_path
        .as_ref()
        .and_then(|p| p.file_name())
        .and_then(|n| n.to_str())
        .unwrap_or("Untitled");

    let lines = vec![
        Line::from(vec![
            Span::styled(
                "You have unsaved changes in ",
                Style::default().fg(Color::White),
            ),
            Span::styled(filename, Style::default().fg(Color::Yellow)),
            Span::styled(".", Style::default().fg(Color::White)),
        ]),
        Line::from(""),
        Line::from(vec![
            Span::styled("  ", Style::default()),
            Span::styled("Ctrl+S", Style::default().fg(Color::Green)),
            Span::styled(" - Save and quit", Style::default().fg(Color::White)),
        ]),
        Line::from(vec![
            Span::styled("  ", Style::default()),
            Span::styled("Ctrl+C", Style::default().fg(Color::Red)),
            Span::styled(" - Quit without saving", Style::default().fg(Color::White)),
        ]),
        Line::from(vec![
            Span::styled("  ", Style::default()),
            Span::styled("Esc", Style::default().fg(Color::Cyan)),
            Span::styled("    - Cancel", Style::default().fg(Color::White)),
        ]),
    ];

    let paragraph = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false });

    f.render_widget(paragraph, dialog_area);
}

/// Render a visual indicator for the separator when dragging
pub fn render_separator_indicator(f: &mut Frame, app: &App, area: Rect) {
    // Calculate the layout split to get the exact separator position
    let text_percentage = app.separator_position;
    let results_percentage = 100 - app.separator_position;

    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(text_percentage),
            Constraint::Percentage(results_percentage),
        ])
        .split(area);

    // The separator should be at the boundary between the two panels
    // We want to draw it exactly where the new layout boundary will be
    let separator_x = chunks[0].x + chunks[0].width;

    // Calculate the inner area (excluding borders) to determine where to draw the line
    // Both panels have the same border structure, so we only need to calculate one
    let panel_block = Block::default().borders(Borders::ALL);
    let inner_area = panel_block.inner(chunks[0]);

    // Use the inner area to determine the vertical bounds for the separator line
    // Extend one character up and down to cover the border corners for a cleaner look
    let separator_start_y = inner_area.y.saturating_sub(1);
    let separator_end_y = (inner_area.y + inner_area.height + 1).min(area.y + area.height);

    // Only draw if the separator position is within the valid area
    if separator_x >= area.x && separator_x < area.x + area.width {
        // Draw the separator line only within the content area (respecting borders)
        for y_offset in 0..(separator_end_y - separator_start_y) {
            let separator_area = Rect {
                x: separator_x.saturating_sub(1), // Position it just before the boundary
                y: separator_start_y + y_offset,
                width: 1,
                height: 1,
            };

            // Use different visual styles for hovering vs dragging
            let (separator_char, color) = if app.is_dragging_separator {
                ("", Color::Yellow) // Bright yellow when actively dragging
            } else {
                ("", Color::LightCyan) // Subtle cyan when just hovering
            };

            let separator_widget = Paragraph::new(separator_char).style(Style::default().fg(color));
            f.render_widget(separator_widget, separator_area);
        }
    }
}

/// Render the save as dialog
pub fn render_save_as_dialog(f: &mut Frame, app: &App, area: Rect) {
    use ratatui::widgets::Clear;

    // Calculate dialog size and position (centered)
    let dialog_width = 60;
    let dialog_height = 6;
    let x = (area.width.saturating_sub(dialog_width)) / 2;
    let y = (area.height.saturating_sub(dialog_height)) / 2;

    let dialog_area = Rect {
        x: area.x + x,
        y: area.y + y,
        width: dialog_width,
        height: dialog_height,
    };

    // Clear the background for the dialog
    f.render_widget(Clear, dialog_area);

    // Create the dialog block
    let block = Block::default()
        .title(" Save As ")
        .borders(Borders::ALL)
        .style(Style::default().bg(Color::DarkGray).fg(Color::White));

    // Create the dialog content with text input
    let input_display = if app.save_as_input == ".pad" {
        "[filename].pad".to_string()
    } else {
        app.save_as_input.clone()
    };

    let lines = vec![
        Line::from(vec![
            Span::styled("Filename: ", Style::default().fg(Color::White)),
            Span::styled(
                input_display,
                if app.save_as_input == ".pad" {
                    Style::default().fg(Color::DarkGray)
                } else {
                    Style::default().fg(Color::Yellow).bg(Color::Blue)
                },
            ),
        ]),
        Line::from(""),
        Line::from(vec![
            Span::styled("Enter", Style::default().fg(Color::Green)),
            Span::styled(" - Save    ", Style::default().fg(Color::White)),
            Span::styled("Esc", Style::default().fg(Color::Red)),
            Span::styled(" - Cancel", Style::default().fg(Color::White)),
        ]),
    ];

    let paragraph = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false });

    f.render_widget(paragraph, dialog_area);
}