Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b2f021509 | ||
|
|
5f1bdfefca | ||
|
|
3273a43e20 | ||
|
|
61e439a1d4 | ||
|
|
03808a8b3b | ||
|
|
57aa0ed8e3 | ||
|
|
5efee3f044 | ||
|
|
6588f310f2 | ||
|
|
25b54afff4 | ||
|
|
b9a7f9a03f | ||
|
|
e36324af6f | ||
|
|
60cb45dcca |
@@ -29,12 +29,26 @@ regex = { workspace = true, optional = true }
|
|||||||
tokio-test = "0.4.4"
|
tokio-test = "0.4.4"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = []
|
default = ["textmode-vim"]
|
||||||
gui = ["ratatui", "crossterm"]
|
gui = ["ratatui", "crossterm"]
|
||||||
suggestions = ["tokio"]
|
suggestions = ["tokio"]
|
||||||
cursor-style = ["crossterm"]
|
cursor-style = ["crossterm"]
|
||||||
validation = ["regex"]
|
validation = ["regex"]
|
||||||
computed = []
|
computed = []
|
||||||
|
textarea = ["gui"]
|
||||||
|
|
||||||
|
# text modes (mutually exclusive; default to vim)
|
||||||
|
textmode-vim = []
|
||||||
|
textmode-normal = []
|
||||||
|
|
||||||
|
all-nontextmodes = [
|
||||||
|
"gui",
|
||||||
|
"suggestions",
|
||||||
|
"cursor-style",
|
||||||
|
"validation",
|
||||||
|
"computed",
|
||||||
|
"textarea"
|
||||||
|
]
|
||||||
|
|
||||||
[[example]]
|
[[example]]
|
||||||
name = "suggestions"
|
name = "suggestions"
|
||||||
@@ -74,3 +88,13 @@ required-features = ["gui", "validation", "cursor-style"]
|
|||||||
[[example]]
|
[[example]]
|
||||||
name = "computed_fields"
|
name = "computed_fields"
|
||||||
required-features = ["gui", "computed"]
|
required-features = ["gui", "computed"]
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
name = "textarea_vim"
|
||||||
|
required-features = ["gui", "cursor-style", "textarea", "textmode-vim"]
|
||||||
|
path = "examples/textarea_vim.rs"
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
name = "textarea_normal"
|
||||||
|
required-features = ["gui", "cursor-style", "textarea", "textmode-normal"]
|
||||||
|
path = "examples/textarea_normal.rs"
|
||||||
|
|||||||
16
canvas/aider.md
Normal file
16
canvas/aider.md
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
# Aider Instructions
|
||||||
|
|
||||||
|
## General Rules
|
||||||
|
- Only modify files that I explicitly add with `/add`.
|
||||||
|
- If a prompt mentions multiple files, **ignore all files except the ones I have added**.
|
||||||
|
- Do not create, edit, or delete any files unless they are explicitly added.
|
||||||
|
- Keep all other files exactly as they are, even if the prompt suggests changes.
|
||||||
|
- Never move logic into or out of files that are not explicitly added.
|
||||||
|
- If a prompt suggests changes to multiple files, apply **only the subset of changes** that belong to the added file(s).
|
||||||
|
- If a change requires touching other files, ignore them, if they were not manually added.
|
||||||
|
|
||||||
|
## Coding Style
|
||||||
|
- Follow Rust 2021 edition idioms.
|
||||||
|
- No logic in `mod.rs` files (only exports/routing).
|
||||||
|
- Always update or create tests **only if the test file is explicitly added**.
|
||||||
|
- Do not think, only apply changes from the prompt
|
||||||
397
canvas/examples/textarea_normal.rs
Normal file
397
canvas/examples/textarea_normal.rs
Normal file
@@ -0,0 +1,397 @@
|
|||||||
|
// examples/textarea_normal.rs
|
||||||
|
//! Demonstrates automatic cursor management with the textarea widget
|
||||||
|
//!
|
||||||
|
//! This example REQUIRES the `cursor-style` and `textarea` features to compile,
|
||||||
|
//! and is adapted for `textmode-normal` (always editing, no vim modes).
|
||||||
|
//!
|
||||||
|
//! Run with:
|
||||||
|
//! cargo run --example canvas_textarea_cursor_auto_normal --features "gui,cursor-style,textarea,textmode-normal"
|
||||||
|
|
||||||
|
#[cfg(not(feature = "cursor-style"))]
|
||||||
|
compile_error!(
|
||||||
|
"This example requires the 'cursor-style' feature. \
|
||||||
|
Run with: cargo run --example canvas_textarea_cursor_auto_normal --features \"gui,cursor-style,textarea,textmode-normal\""
|
||||||
|
);
|
||||||
|
|
||||||
|
#[cfg(not(feature = "textarea"))]
|
||||||
|
compile_error!(
|
||||||
|
"This example requires the 'textarea' feature. \
|
||||||
|
Run with: cargo run --example canvas_textarea_cursor_auto_normal --features \"gui,cursor-style,textarea,textmode-normal\""
|
||||||
|
);
|
||||||
|
|
||||||
|
use std::io;
|
||||||
|
use crossterm::{
|
||||||
|
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEvent, KeyModifiers},
|
||||||
|
execute,
|
||||||
|
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
|
||||||
|
};
|
||||||
|
use ratatui::{
|
||||||
|
backend::{Backend, CrosstermBackend},
|
||||||
|
layout::{Constraint, Direction, Layout},
|
||||||
|
style::{Color, Style},
|
||||||
|
text::{Line, Span},
|
||||||
|
widgets::{Block, Borders, Paragraph},
|
||||||
|
Frame, Terminal,
|
||||||
|
};
|
||||||
|
|
||||||
|
use canvas::{
|
||||||
|
canvas::{modes::AppMode, CursorManager},
|
||||||
|
textarea::{TextArea, TextAreaState},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// TextArea demo adapted for NORMALMODE (always editing)
|
||||||
|
struct AutoCursorTextArea {
|
||||||
|
textarea: TextAreaState,
|
||||||
|
has_unsaved_changes: bool,
|
||||||
|
debug_message: String,
|
||||||
|
command_buffer: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AutoCursorTextArea {
|
||||||
|
fn new() -> Self {
|
||||||
|
let initial_text = "🎯 Automatic Cursor Management Demo (NORMALMODE)\n\
|
||||||
|
Welcome to the textarea cursor demo!\n\
|
||||||
|
\n\
|
||||||
|
This demo runs in NORMALMODE:\n\
|
||||||
|
• Always editing (no insert/normal toggle)\n\
|
||||||
|
• Cursor is always underscore _\n\
|
||||||
|
\n\
|
||||||
|
Navigation commands:\n\
|
||||||
|
• hjkl or arrow keys: move cursor\n\
|
||||||
|
• w/b/e/W/B/E: word movements\n\
|
||||||
|
• 0/$: line start/end\n\
|
||||||
|
• g/gG: first/last line\n\
|
||||||
|
\n\
|
||||||
|
Editing commands:\n\
|
||||||
|
• x/X: delete characters\n\
|
||||||
|
\n\
|
||||||
|
Press ? for help, Ctrl+Q to quit.";
|
||||||
|
|
||||||
|
let mut textarea = TextAreaState::from_text(initial_text);
|
||||||
|
textarea.set_placeholder("Start typing...");
|
||||||
|
|
||||||
|
Self {
|
||||||
|
textarea,
|
||||||
|
has_unsaved_changes: false,
|
||||||
|
debug_message: "🎯 NORMALMODE Demo - always editing".to_string(),
|
||||||
|
command_buffer: String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_textarea_input(&mut self, key: KeyEvent) {
|
||||||
|
self.textarea.input(key);
|
||||||
|
self.has_unsaved_changes = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_left(&mut self) {
|
||||||
|
self.textarea.move_left();
|
||||||
|
self.debug_message = "← left".to_string();
|
||||||
|
}
|
||||||
|
fn move_right(&mut self) {
|
||||||
|
self.textarea.move_right();
|
||||||
|
self.debug_message = "→ right".to_string();
|
||||||
|
}
|
||||||
|
fn move_up(&mut self) {
|
||||||
|
self.textarea.move_up();
|
||||||
|
self.debug_message = "↑ up".to_string();
|
||||||
|
}
|
||||||
|
fn move_down(&mut self) {
|
||||||
|
self.textarea.move_down();
|
||||||
|
self.debug_message = "↓ down".to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_word_next(&mut self) {
|
||||||
|
self.textarea.move_word_next();
|
||||||
|
self.debug_message = "w: next word".to_string();
|
||||||
|
}
|
||||||
|
fn move_word_prev(&mut self) {
|
||||||
|
self.textarea.move_word_prev();
|
||||||
|
self.debug_message = "b: previous word".to_string();
|
||||||
|
}
|
||||||
|
fn move_word_end(&mut self) {
|
||||||
|
self.textarea.move_word_end();
|
||||||
|
self.debug_message = "e: word end".to_string();
|
||||||
|
}
|
||||||
|
fn move_word_end_prev(&mut self) {
|
||||||
|
self.textarea.move_word_end_prev();
|
||||||
|
self.debug_message = "ge: previous word end".to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_line_start(&mut self) {
|
||||||
|
self.textarea.move_line_start();
|
||||||
|
self.debug_message = "0: line start".to_string();
|
||||||
|
}
|
||||||
|
fn move_line_end(&mut self) {
|
||||||
|
self.textarea.move_line_end();
|
||||||
|
self.debug_message = "$: line end".to_string();
|
||||||
|
}
|
||||||
|
fn move_first_line(&mut self) {
|
||||||
|
self.textarea.move_first_line();
|
||||||
|
self.debug_message = "gg: first line".to_string();
|
||||||
|
}
|
||||||
|
fn move_last_line(&mut self) {
|
||||||
|
self.textarea.move_last_line();
|
||||||
|
self.debug_message = "G: last line".to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn delete_char_forward(&mut self) {
|
||||||
|
if let Ok(_) = self.textarea.delete_forward() {
|
||||||
|
self.has_unsaved_changes = true;
|
||||||
|
self.debug_message = "x: deleted character".to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn delete_char_backward(&mut self) {
|
||||||
|
if let Ok(_) = self.textarea.delete_backward() {
|
||||||
|
self.has_unsaved_changes = true;
|
||||||
|
self.debug_message = "X: deleted character backward".to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clear_command_buffer(&mut self) {
|
||||||
|
self.command_buffer.clear();
|
||||||
|
}
|
||||||
|
fn add_to_command_buffer(&mut self, ch: char) {
|
||||||
|
self.command_buffer.push(ch);
|
||||||
|
}
|
||||||
|
fn get_command_buffer(&self) -> &str {
|
||||||
|
&self.command_buffer
|
||||||
|
}
|
||||||
|
fn has_pending_command(&self) -> bool {
|
||||||
|
!self.command_buffer.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn debug_message(&self) -> &str {
|
||||||
|
&self.debug_message
|
||||||
|
}
|
||||||
|
fn set_debug_message(&mut self, msg: String) {
|
||||||
|
self.debug_message = msg;
|
||||||
|
}
|
||||||
|
fn has_unsaved_changes(&self) -> bool {
|
||||||
|
self.has_unsaved_changes
|
||||||
|
}
|
||||||
|
fn get_cursor_info(&self) -> String {
|
||||||
|
format!(
|
||||||
|
"Line {}, Col {}",
|
||||||
|
self.textarea.current_field() + 1,
|
||||||
|
self.textarea.cursor_position() + 1
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// === BIG WORD MOVEMENTS ===
|
||||||
|
|
||||||
|
fn move_big_word_next(&mut self) {
|
||||||
|
self.textarea.move_big_word_next();
|
||||||
|
self.debug_message = "W: next WORD".to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_big_word_prev(&mut self) {
|
||||||
|
self.textarea.move_big_word_prev();
|
||||||
|
self.debug_message = "B: previous WORD".to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_big_word_end(&mut self) {
|
||||||
|
self.textarea.move_big_word_end();
|
||||||
|
self.debug_message = "E: WORD end".to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_big_word_end_prev(&mut self) {
|
||||||
|
self.textarea.move_big_word_end_prev();
|
||||||
|
self.debug_message = "gE: previous WORD end".to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handle key press in NORMALMODE (always editing, casual editor style)
|
||||||
|
fn handle_key_press(
|
||||||
|
key_event: KeyEvent,
|
||||||
|
editor: &mut AutoCursorTextArea,
|
||||||
|
) -> anyhow::Result<bool> {
|
||||||
|
let KeyEvent {
|
||||||
|
code: key,
|
||||||
|
modifiers,
|
||||||
|
..
|
||||||
|
} = key_event;
|
||||||
|
|
||||||
|
// Quit
|
||||||
|
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 (key, modifiers) {
|
||||||
|
// Movement
|
||||||
|
(KeyCode::Left, _) => editor.move_left(),
|
||||||
|
(KeyCode::Right, _) => editor.move_right(),
|
||||||
|
(KeyCode::Up, _) => editor.move_up(),
|
||||||
|
(KeyCode::Down, _) => editor.move_down(),
|
||||||
|
|
||||||
|
// Word movement (Ctrl+Arrows)
|
||||||
|
(KeyCode::Left, m) if m.contains(KeyModifiers::CONTROL) => editor.move_word_prev(),
|
||||||
|
(KeyCode::Right, m) if m.contains(KeyModifiers::CONTROL) => editor.move_word_next(),
|
||||||
|
(KeyCode::Right, m) if m.contains(KeyModifiers::CONTROL | KeyModifiers::SHIFT) => {
|
||||||
|
editor.move_word_end()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Line/document movement
|
||||||
|
(KeyCode::Home, _) => editor.move_line_start(),
|
||||||
|
(KeyCode::End, _) => editor.move_line_end(),
|
||||||
|
(KeyCode::Home, m) if m.contains(KeyModifiers::CONTROL) => editor.move_first_line(),
|
||||||
|
(KeyCode::End, m) if m.contains(KeyModifiers::CONTROL) => editor.move_last_line(),
|
||||||
|
|
||||||
|
// Delete
|
||||||
|
(KeyCode::Delete, _) => editor.delete_char_forward(),
|
||||||
|
(KeyCode::Backspace, _) => editor.delete_char_backward(),
|
||||||
|
|
||||||
|
(KeyCode::F(1), _) => {
|
||||||
|
// Switch to indicator mode
|
||||||
|
editor.textarea.use_overflow_indicator('$');
|
||||||
|
editor.set_debug_message("Overflow: indicator '$' (wrap OFF)".to_string());
|
||||||
|
}
|
||||||
|
(KeyCode::F(2), _) => {
|
||||||
|
// Switch to wrap mode
|
||||||
|
editor.textarea.use_wrap();
|
||||||
|
editor.set_debug_message("Overflow: wrap ON".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
(KeyCode::F(3), _) => {
|
||||||
|
editor.textarea.set_wrap_indent_cols(3);
|
||||||
|
editor.set_debug_message("Wrap indent: 3 columns".to_string());
|
||||||
|
}
|
||||||
|
(KeyCode::F(4), _) => {
|
||||||
|
editor.textarea.set_wrap_indent_cols(0);
|
||||||
|
editor.set_debug_message("Wrap indent: 0 columns".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debug/info
|
||||||
|
(KeyCode::Char('?'), _) => {
|
||||||
|
editor.set_debug_message(format!(
|
||||||
|
"{}, Mode: NORMALMODE (casual editor, underscore cursor)",
|
||||||
|
editor.get_cursor_info()
|
||||||
|
));
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default: treat as text input
|
||||||
|
_ => editor.handle_textarea_input(key_event),
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_app<B: Backend>(terminal: &mut Terminal<B>, mut editor: AutoCursorTextArea) -> io::Result<()> {
|
||||||
|
loop {
|
||||||
|
terminal.draw(|f| ui(f, &mut editor))?;
|
||||||
|
|
||||||
|
if let Event::Key(key) = event::read()? {
|
||||||
|
match handle_key_press(key, &mut editor) {
|
||||||
|
Ok(should_continue) => {
|
||||||
|
if !should_continue {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
editor.set_debug_message(format!("Error: {}", e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ui(f: &mut Frame, editor: &mut AutoCursorTextArea) {
|
||||||
|
let chunks = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints([Constraint::Min(8), Constraint::Length(8)])
|
||||||
|
.split(f.area());
|
||||||
|
|
||||||
|
render_textarea(f, chunks[0], editor);
|
||||||
|
render_status_and_help(f, chunks[1], editor);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_textarea(f: &mut Frame, area: ratatui::layout::Rect, editor: &mut AutoCursorTextArea) {
|
||||||
|
let block = Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.title("🎯 Textarea with NORMALMODE (always editing)");
|
||||||
|
|
||||||
|
let textarea_widget = TextArea::default().block(block.clone());
|
||||||
|
f.render_stateful_widget(textarea_widget, area, &mut editor.textarea);
|
||||||
|
|
||||||
|
let (cx, cy) = editor.textarea.cursor(area, Some(&block));
|
||||||
|
f.set_cursor_position((cx, cy));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_status_and_help(f: &mut Frame, area: ratatui::layout::Rect, editor: &AutoCursorTextArea) {
|
||||||
|
let chunks = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints([Constraint::Length(3), Constraint::Length(5)])
|
||||||
|
.split(area);
|
||||||
|
|
||||||
|
let status_text = if editor.has_pending_command() {
|
||||||
|
format!(
|
||||||
|
"-- NORMALMODE (underscore cursor) -- {} [{}]",
|
||||||
|
editor.debug_message(),
|
||||||
|
editor.get_command_buffer()
|
||||||
|
)
|
||||||
|
} else if editor.has_unsaved_changes() {
|
||||||
|
format!(
|
||||||
|
"-- NORMALMODE (underscore cursor) -- [Modified] {} | {}",
|
||||||
|
editor.debug_message(),
|
||||||
|
editor.get_cursor_info()
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"-- NORMALMODE (underscore cursor) -- {} | {}",
|
||||||
|
editor.debug_message(),
|
||||||
|
editor.get_cursor_info()
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
let status = Paragraph::new(Line::from(Span::raw(status_text)))
|
||||||
|
.block(Block::default().borders(Borders::ALL).title("🎯 Cursor Status"));
|
||||||
|
|
||||||
|
f.render_widget(status, chunks[0]);
|
||||||
|
|
||||||
|
let help_text = "🎯 NORMALMODE (always editing)\n\
|
||||||
|
hjkl/arrows=move, w/b/e=words, W/B/E=WORDS, 0/$=line, g/G=first/last\n\
|
||||||
|
x/X=delete, typing inserts text\n\
|
||||||
|
?=info, Ctrl+Q=quit";
|
||||||
|
|
||||||
|
let help = Paragraph::new(help_text)
|
||||||
|
.block(Block::default().borders(Borders::ALL).title("🚀 Help"))
|
||||||
|
.style(Style::default().fg(Color::Gray));
|
||||||
|
|
||||||
|
f.render_widget(help, chunks[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
println!("🎯 Canvas Textarea Cursor Auto Demo (NORMALMODE)");
|
||||||
|
println!("✅ cursor-style feature: ENABLED");
|
||||||
|
println!("✅ textarea feature: ENABLED");
|
||||||
|
println!("✅ textmode-normal feature: ENABLED");
|
||||||
|
println!("🚀 Always editing, underscore cursor active");
|
||||||
|
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 editor = AutoCursorTextArea::new();
|
||||||
|
|
||||||
|
let res = run_app(&mut terminal, editor);
|
||||||
|
|
||||||
|
CursorManager::reset()?;
|
||||||
|
|
||||||
|
disable_raw_mode()?;
|
||||||
|
execute!(terminal.backend_mut(), LeaveAlternateScreen, DisableMouseCapture)?;
|
||||||
|
terminal.show_cursor()?;
|
||||||
|
|
||||||
|
if let Err(err) = res {
|
||||||
|
println!("{:?}", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("🎯 Cursor automatically reset to default!");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
653
canvas/examples/textarea_vim.rs
Normal file
653
canvas/examples/textarea_vim.rs
Normal file
@@ -0,0 +1,653 @@
|
|||||||
|
// examples/textarea_vim.rs
|
||||||
|
//! Demonstrates automatic cursor management with the textarea widget
|
||||||
|
//!
|
||||||
|
//! This example REQUIRES the `cursor-style` and `textarea` features to compile.
|
||||||
|
//!
|
||||||
|
//! Run with:
|
||||||
|
//! cargo run --example canvas_textarea_cursor_auto --features "gui,cursor-style,textarea"
|
||||||
|
|
||||||
|
// REQUIRE cursor-style and textarea features
|
||||||
|
#[cfg(not(feature = "cursor-style"))]
|
||||||
|
compile_error!(
|
||||||
|
"This example requires the 'cursor-style' feature. \
|
||||||
|
Run with: cargo run --example canvas_textarea_cursor_auto --features \"gui,cursor-style,textarea\""
|
||||||
|
);
|
||||||
|
|
||||||
|
#[cfg(not(feature = "textarea"))]
|
||||||
|
compile_error!(
|
||||||
|
"This example requires the 'textarea' feature. \
|
||||||
|
Run with: cargo run --example canvas_textarea_cursor_auto --features \"gui,cursor-style,textarea\""
|
||||||
|
);
|
||||||
|
|
||||||
|
use std::io;
|
||||||
|
use crossterm::{
|
||||||
|
event::{
|
||||||
|
self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEvent, KeyModifiers,
|
||||||
|
},
|
||||||
|
execute,
|
||||||
|
terminal::{
|
||||||
|
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use ratatui::{
|
||||||
|
backend::{Backend, CrosstermBackend},
|
||||||
|
layout::{Constraint, Direction, Layout},
|
||||||
|
style::{Color, Style},
|
||||||
|
text::{Line, Span},
|
||||||
|
widgets::{Block, Borders, Paragraph},
|
||||||
|
Frame, Terminal,
|
||||||
|
};
|
||||||
|
|
||||||
|
use canvas::{
|
||||||
|
canvas::{
|
||||||
|
modes::AppMode,
|
||||||
|
CursorManager, // This import only exists when cursor-style feature is enabled
|
||||||
|
},
|
||||||
|
textarea::{TextArea, TextAreaState},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Enhanced TextArea that demonstrates automatic cursor management
|
||||||
|
/// Now uses direct FormEditor method calls via Deref!
|
||||||
|
struct AutoCursorTextArea {
|
||||||
|
textarea: TextAreaState,
|
||||||
|
has_unsaved_changes: bool,
|
||||||
|
debug_message: String,
|
||||||
|
command_buffer: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AutoCursorTextArea {
|
||||||
|
fn new() -> Self {
|
||||||
|
let initial_text = "🎯 Automatic Cursor Management Demo\n\
|
||||||
|
Welcome to the textarea cursor demo!\n\
|
||||||
|
\n\
|
||||||
|
Try different modes:\n\
|
||||||
|
• Normal mode: Block cursor █\n\
|
||||||
|
• Insert mode: Bar cursor |\n\
|
||||||
|
\n\
|
||||||
|
Navigation commands:\n\
|
||||||
|
• hjkl or arrow keys: move cursor\n\
|
||||||
|
• i/a/A/o/O: enter insert mode\n\
|
||||||
|
• w/b/e/W/B/E: word movements\n\
|
||||||
|
• Esc: return to normal mode\n\
|
||||||
|
\n\
|
||||||
|
Watch how the terminal cursor changes automatically!\n\
|
||||||
|
This text can be edited when in insert mode.\n\
|
||||||
|
\n\
|
||||||
|
Press ? for help, F1/F2 for manual cursor control demo.";
|
||||||
|
|
||||||
|
let mut textarea = TextAreaState::from_text(initial_text);
|
||||||
|
textarea.set_placeholder("Start typing...");
|
||||||
|
textarea.use_wrap();
|
||||||
|
|
||||||
|
Self {
|
||||||
|
textarea,
|
||||||
|
has_unsaved_changes: false,
|
||||||
|
debug_message: "🎯 Automatic Cursor Demo - cursor-style feature enabled!".to_string(),
|
||||||
|
command_buffer: String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// === MODE TRANSITIONS WITH AUTOMATIC CURSOR MANAGEMENT ===
|
||||||
|
|
||||||
|
fn enter_insert_mode(&mut self) -> std::io::Result<()> {
|
||||||
|
self.textarea.enter_edit_mode(); // 🎯 Direct FormEditor method call via Deref!
|
||||||
|
CursorManager::update_for_mode(AppMode::Edit)?; // 🎯 Automatic: cursor becomes bar |
|
||||||
|
self.debug_message = "✏️ INSERT MODE - Cursor: Steady Bar |".to_string();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn enter_append_mode(&mut self) -> std::io::Result<()> {
|
||||||
|
self.textarea.enter_append_mode(); // 🎯 Direct FormEditor method call!
|
||||||
|
CursorManager::update_for_mode(AppMode::Edit)?;
|
||||||
|
self.debug_message = "✏️ INSERT (append) - Cursor: Steady Bar |".to_string();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exit_to_normal_mode(&mut self) -> std::io::Result<()> {
|
||||||
|
self.textarea.exit_edit_mode(); // 🎯 Direct FormEditor method call!
|
||||||
|
CursorManager::update_for_mode(AppMode::ReadOnly)?; // 🎯 Automatic: cursor becomes steady block
|
||||||
|
self.debug_message = "🔒 NORMAL MODE - Cursor: Steady Block █".to_string();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// === MANUAL CURSOR OVERRIDE DEMONSTRATION ===
|
||||||
|
|
||||||
|
fn demo_manual_cursor_control(&mut self) -> std::io::Result<()> {
|
||||||
|
// Users can still manually control cursor if needed
|
||||||
|
CursorManager::update_for_mode(AppMode::Command)?;
|
||||||
|
self.debug_message = "🔧 Manual override: Command cursor _".to_string();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn restore_automatic_cursor(&mut self) -> std::io::Result<()> {
|
||||||
|
// Restore automatic cursor based on current mode
|
||||||
|
CursorManager::update_for_mode(self.textarea.mode())?; // 🎯 Direct method call!
|
||||||
|
self.debug_message = "🎯 Restored automatic cursor management".to_string();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// === TEXTAREA OPERATIONS ===
|
||||||
|
|
||||||
|
fn handle_textarea_input(&mut self, key: KeyEvent) {
|
||||||
|
self.textarea.input(key);
|
||||||
|
self.has_unsaved_changes = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// === MOVEMENT OPERATIONS (using direct FormEditor methods!) ===
|
||||||
|
|
||||||
|
fn move_left(&mut self) {
|
||||||
|
self.textarea.move_left(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("← left");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_right(&mut self) {
|
||||||
|
self.textarea.move_right(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("→ right");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_up(&mut self) {
|
||||||
|
self.textarea.move_up(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("↑ up");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_down(&mut self) {
|
||||||
|
self.textarea.move_down(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("↓ down");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_word_next(&mut self) {
|
||||||
|
self.textarea.move_word_next(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("w: next word");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_word_prev(&mut self) {
|
||||||
|
self.textarea.move_word_prev(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("b: previous word");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_word_end(&mut self) {
|
||||||
|
self.textarea.move_word_end(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("e: word end");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_word_end_prev(&mut self) {
|
||||||
|
self.textarea.move_word_end_prev(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("ge: previous word end");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_line_start(&mut self) {
|
||||||
|
self.textarea.move_line_start(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("0: line start");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_line_end(&mut self) {
|
||||||
|
self.textarea.move_line_end(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("$: line end");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_first_line(&mut self) {
|
||||||
|
self.textarea.move_first_line(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("gg: first line");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_last_line(&mut self) {
|
||||||
|
self.textarea.move_last_line(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("G: last line");
|
||||||
|
}
|
||||||
|
|
||||||
|
// === BIG WORD MOVEMENTS ===
|
||||||
|
|
||||||
|
fn move_big_word_next(&mut self) {
|
||||||
|
self.textarea.move_big_word_next(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("W: next WORD");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_big_word_prev(&mut self) {
|
||||||
|
self.textarea.move_big_word_prev(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("B: previous WORD");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_big_word_end(&mut self) {
|
||||||
|
self.textarea.move_big_word_end(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("E: WORD end");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_big_word_end_prev(&mut self) {
|
||||||
|
self.textarea.move_big_word_end_prev(); // 🎯 Direct FormEditor method call!
|
||||||
|
self.update_debug_for_movement("gE: previous WORD end");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_debug_for_movement(&mut self, action: &str) {
|
||||||
|
self.debug_message = action.to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
// === DELETE OPERATIONS ===
|
||||||
|
|
||||||
|
fn delete_char_forward(&mut self) {
|
||||||
|
if let Ok(_) = self.textarea.delete_forward() { // 🎯 Direct FormEditor method call!
|
||||||
|
self.has_unsaved_changes = true;
|
||||||
|
self.debug_message = "x: deleted character".to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn delete_char_backward(&mut self) {
|
||||||
|
if let Ok(_) = self.textarea.delete_backward() { // 🎯 Direct FormEditor method call!
|
||||||
|
self.has_unsaved_changes = true;
|
||||||
|
self.debug_message = "X: deleted character backward".to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// === VIM-STYLE EDITING ===
|
||||||
|
|
||||||
|
fn open_line_below(&mut self) -> anyhow::Result<()> {
|
||||||
|
let result = self.textarea.open_line_below(); // 🎯 Textarea-specific override!
|
||||||
|
if result.is_ok() {
|
||||||
|
CursorManager::update_for_mode(AppMode::Edit)?;
|
||||||
|
self.debug_message = "✏️ INSERT (open line below) - Cursor: Steady Bar |".to_string();
|
||||||
|
self.has_unsaved_changes = true;
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open_line_above(&mut self) -> anyhow::Result<()> {
|
||||||
|
let result = self.textarea.open_line_above(); // 🎯 Textarea-specific override!
|
||||||
|
if result.is_ok() {
|
||||||
|
CursorManager::update_for_mode(AppMode::Edit)?;
|
||||||
|
self.debug_message = "✏️ INSERT (open line above) - Cursor: Steady Bar |".to_string();
|
||||||
|
self.has_unsaved_changes = true;
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
// === COMMAND BUFFER HANDLING ===
|
||||||
|
|
||||||
|
fn clear_command_buffer(&mut self) {
|
||||||
|
self.command_buffer.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_to_command_buffer(&mut self, ch: char) {
|
||||||
|
self.command_buffer.push(ch);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_command_buffer(&self) -> &str {
|
||||||
|
&self.command_buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_pending_command(&self) -> bool {
|
||||||
|
!self.command_buffer.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
// === GETTERS ===
|
||||||
|
|
||||||
|
fn mode(&self) -> AppMode {
|
||||||
|
self.textarea.mode() // 🎯 Direct FormEditor method call!
|
||||||
|
}
|
||||||
|
|
||||||
|
fn debug_message(&self) -> &str {
|
||||||
|
&self.debug_message
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_unsaved_changes(&self) -> bool {
|
||||||
|
self.has_unsaved_changes
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_debug_message(&mut self, msg: String) {
|
||||||
|
self.debug_message = msg;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_cursor_info(&self) -> String {
|
||||||
|
format!(
|
||||||
|
"Line {}, Col {}",
|
||||||
|
self.textarea.current_field() + 1, // 🎯 Direct FormEditor method call!
|
||||||
|
self.textarea.cursor_position() + 1 // 🎯 Direct FormEditor method call!
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handle key press with automatic cursor management
|
||||||
|
fn handle_key_press(
|
||||||
|
key_event: KeyEvent,
|
||||||
|
editor: &mut AutoCursorTextArea,
|
||||||
|
) -> anyhow::Result<bool> {
|
||||||
|
let KeyEvent { code: key, modifiers, .. } = key_event;
|
||||||
|
let mode = editor.mode();
|
||||||
|
|
||||||
|
// Quit handling
|
||||||
|
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) {
|
||||||
|
// === MODE TRANSITIONS WITH AUTOMATIC CURSOR MANAGEMENT ===
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('i'), _) => {
|
||||||
|
editor.enter_insert_mode()?;
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('a'), _) => {
|
||||||
|
editor.enter_append_mode()?;
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('A'), _) => {
|
||||||
|
editor.move_line_end();
|
||||||
|
editor.enter_insert_mode()?;
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Vim o/O commands
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('o'), _) => {
|
||||||
|
if let Err(e) = editor.open_line_below() {
|
||||||
|
editor.set_debug_message(format!("Error opening line below: {}", e));
|
||||||
|
}
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('O'), _) => {
|
||||||
|
if let Err(e) = editor.open_line_above() {
|
||||||
|
editor.set_debug_message(format!("Error opening line above: {}", e));
|
||||||
|
}
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Escape: Exit any mode back to normal
|
||||||
|
(AppMode::Edit, KeyCode::Esc, _) => {
|
||||||
|
editor.exit_to_normal_mode()?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// === INSERT MODE: Pass to textarea ===
|
||||||
|
(AppMode::Edit, _, _) => {
|
||||||
|
editor.handle_textarea_input(key_event);
|
||||||
|
}
|
||||||
|
|
||||||
|
// === CURSOR MANAGEMENT DEMONSTRATION ===
|
||||||
|
(AppMode::ReadOnly, KeyCode::F(1), _) => {
|
||||||
|
editor.demo_manual_cursor_control()?;
|
||||||
|
}
|
||||||
|
(AppMode::ReadOnly, KeyCode::F(2), _) => {
|
||||||
|
editor.restore_automatic_cursor()?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// === MOVEMENT: VIM-STYLE NAVIGATION (Normal mode) ===
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('h'), _)
|
||||||
|
| (AppMode::ReadOnly, KeyCode::Left, _) => {
|
||||||
|
editor.move_left();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('l'), _)
|
||||||
|
| (AppMode::ReadOnly, KeyCode::Right, _) => {
|
||||||
|
editor.move_right();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('j'), _)
|
||||||
|
| (AppMode::ReadOnly, KeyCode::Down, _) => {
|
||||||
|
editor.move_down();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('k'), _)
|
||||||
|
| (AppMode::ReadOnly, KeyCode::Up, _) => {
|
||||||
|
editor.move_up();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Word movement
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('w'), _) => {
|
||||||
|
editor.move_word_next();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('b'), _) => {
|
||||||
|
editor.move_word_prev();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('e'), _) => {
|
||||||
|
if editor.get_command_buffer() == "g" {
|
||||||
|
editor.move_word_end_prev();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
} else {
|
||||||
|
editor.move_word_end();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Big word movement (vim W/B/E commands)
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('W'), _) => {
|
||||||
|
editor.move_big_word_next();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('B'), _) => {
|
||||||
|
editor.move_big_word_prev();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('E'), _) => {
|
||||||
|
if editor.get_command_buffer() == "g" {
|
||||||
|
editor.move_big_word_end_prev();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
} else {
|
||||||
|
editor.move_big_word_end();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Line movement
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('0'), _)
|
||||||
|
| (AppMode::ReadOnly, KeyCode::Home, _) => {
|
||||||
|
editor.move_line_start();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('$'), _)
|
||||||
|
| (AppMode::ReadOnly, KeyCode::End, _) => {
|
||||||
|
editor.move_line_end();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Document movement with command buffer
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('g'), _) => {
|
||||||
|
if editor.get_command_buffer() == "g" {
|
||||||
|
editor.move_first_line();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
} else {
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
editor.add_to_command_buffer('g');
|
||||||
|
editor.set_debug_message("g".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('G'), _) => {
|
||||||
|
editor.move_last_line();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
// === DELETE OPERATIONS (Normal mode) ===
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('x'), _) => {
|
||||||
|
editor.delete_char_forward();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('X'), _) => {
|
||||||
|
editor.delete_char_backward();
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
// === DEBUG/INFO COMMANDS ===
|
||||||
|
(AppMode::ReadOnly, KeyCode::Char('?'), _) => {
|
||||||
|
editor.set_debug_message(format!(
|
||||||
|
"{}, Mode: {:?} - Cursor managed automatically!",
|
||||||
|
editor.get_cursor_info(),
|
||||||
|
mode
|
||||||
|
));
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
_ => {
|
||||||
|
if editor.has_pending_command() {
|
||||||
|
editor.clear_command_buffer();
|
||||||
|
editor.set_debug_message("Invalid command sequence".to_string());
|
||||||
|
} else {
|
||||||
|
editor.set_debug_message(format!(
|
||||||
|
"Unhandled: {:?} + {:?} in {:?} mode",
|
||||||
|
key, modifiers, mode
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_app<B: Backend>(
|
||||||
|
terminal: &mut Terminal<B>,
|
||||||
|
mut editor: AutoCursorTextArea,
|
||||||
|
) -> io::Result<()> {
|
||||||
|
loop {
|
||||||
|
terminal.draw(|f| ui(f, &mut editor))?;
|
||||||
|
|
||||||
|
if let Event::Key(key) = event::read()? {
|
||||||
|
match handle_key_press(key, &mut editor) {
|
||||||
|
Ok(should_continue) => {
|
||||||
|
if !should_continue {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
editor.set_debug_message(format!("Error: {}", e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ui(f: &mut Frame, editor: &mut AutoCursorTextArea) {
|
||||||
|
let chunks = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints([Constraint::Min(8), Constraint::Length(8)])
|
||||||
|
.split(f.area());
|
||||||
|
|
||||||
|
render_textarea(f, chunks[0], editor);
|
||||||
|
render_status_and_help(f, chunks[1], editor);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_textarea(
|
||||||
|
f: &mut Frame,
|
||||||
|
area: ratatui::layout::Rect,
|
||||||
|
editor: &mut AutoCursorTextArea,
|
||||||
|
) {
|
||||||
|
let block = Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.title("🎯 Textarea with Automatic Cursor Management");
|
||||||
|
|
||||||
|
let textarea_widget = TextArea::default().block(block.clone());
|
||||||
|
|
||||||
|
f.render_stateful_widget(textarea_widget, area, &mut editor.textarea);
|
||||||
|
|
||||||
|
// Set cursor position for terminal cursor
|
||||||
|
// Always show cursor - CursorManager handles the style (block/bar/blinking)
|
||||||
|
let (cx, cy) = editor.textarea.cursor(area, Some(&block));
|
||||||
|
f.set_cursor_position((cx, cy));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_status_and_help(
|
||||||
|
f: &mut Frame,
|
||||||
|
area: ratatui::layout::Rect,
|
||||||
|
editor: &AutoCursorTextArea,
|
||||||
|
) {
|
||||||
|
let chunks = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints([Constraint::Length(3), Constraint::Length(5)])
|
||||||
|
.split(area);
|
||||||
|
|
||||||
|
// Status bar with cursor information
|
||||||
|
let mode_text = match editor.mode() {
|
||||||
|
AppMode::Edit => "INSERT | (bar cursor)",
|
||||||
|
AppMode::ReadOnly => "NORMAL █ (block cursor)",
|
||||||
|
AppMode::Highlight => "VISUAL █ (blinking block)",
|
||||||
|
_ => "NORMAL █ (block cursor)",
|
||||||
|
};
|
||||||
|
|
||||||
|
let status_text = if editor.has_pending_command() {
|
||||||
|
format!("-- {} -- {} [{}]", mode_text, editor.debug_message(), editor.get_command_buffer())
|
||||||
|
} else if editor.has_unsaved_changes() {
|
||||||
|
format!("-- {} -- [Modified] {} | {}", mode_text, editor.debug_message(), editor.get_cursor_info())
|
||||||
|
} else {
|
||||||
|
format!("-- {} -- {} | {}", mode_text, editor.debug_message(), editor.get_cursor_info())
|
||||||
|
};
|
||||||
|
|
||||||
|
let status = Paragraph::new(Line::from(Span::raw(status_text)))
|
||||||
|
.block(Block::default().borders(Borders::ALL).title("🎯 Automatic Cursor Status"));
|
||||||
|
|
||||||
|
f.render_widget(status, chunks[0]);
|
||||||
|
|
||||||
|
// Help text
|
||||||
|
let help_text = match editor.mode() {
|
||||||
|
AppMode::ReadOnly => {
|
||||||
|
if editor.has_pending_command() {
|
||||||
|
match editor.get_command_buffer() {
|
||||||
|
"g" => "Press 'g' again for first line, or any other key to cancel",
|
||||||
|
_ => "Pending command... (Esc to cancel)"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
"🎯 CURSOR-STYLE DEMO: Normal █ | Insert | \n\
|
||||||
|
Normal: hjkl/arrows=move, w/b/e=words, W/B/E=WORDS, 0/$=line, g/G=first/last\n\
|
||||||
|
i/a/A/o/O=insert, x/X=delete, ?=info\n\
|
||||||
|
F1=demo manual cursor, F2=restore automatic, Ctrl+Q=quit"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AppMode::Edit => {
|
||||||
|
"🎯 INSERT MODE - Cursor: | (bar)\n\
|
||||||
|
Type to edit text, arrows=move, Enter=new line\n\
|
||||||
|
Esc=normal mode"
|
||||||
|
}
|
||||||
|
AppMode::Highlight => {
|
||||||
|
"🎯 VISUAL MODE - Cursor: █ (blinking block)\n\
|
||||||
|
hjkl/arrows=extend selection\n\
|
||||||
|
Esc=normal mode"
|
||||||
|
}
|
||||||
|
_ => "🎯 Watch the cursor change automatically!"
|
||||||
|
};
|
||||||
|
|
||||||
|
let help = Paragraph::new(help_text)
|
||||||
|
.block(Block::default().borders(Borders::ALL).title("🚀 Automatic Cursor Management"))
|
||||||
|
.style(Style::default().fg(Color::Gray));
|
||||||
|
|
||||||
|
f.render_widget(help, chunks[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
// Print feature status
|
||||||
|
println!("🎯 Canvas Textarea Cursor Auto Demo");
|
||||||
|
println!("✅ cursor-style feature: ENABLED");
|
||||||
|
println!("✅ textarea feature: ENABLED");
|
||||||
|
println!("🚀 Automatic cursor management: ACTIVE");
|
||||||
|
println!("📖 Watch your terminal cursor change based on mode!");
|
||||||
|
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 mut editor = AutoCursorTextArea::new();
|
||||||
|
|
||||||
|
// Initialize with normal mode - library automatically sets block cursor
|
||||||
|
editor.exit_to_normal_mode()?;
|
||||||
|
|
||||||
|
let res = run_app(&mut terminal, editor);
|
||||||
|
|
||||||
|
// Reset cursor on exit
|
||||||
|
CursorManager::reset()?;
|
||||||
|
|
||||||
|
disable_raw_mode()?;
|
||||||
|
execute!(
|
||||||
|
terminal.backend_mut(),
|
||||||
|
LeaveAlternateScreen,
|
||||||
|
DisableMouseCapture
|
||||||
|
)?;
|
||||||
|
terminal.show_cursor()?;
|
||||||
|
|
||||||
|
if let Err(err) = res {
|
||||||
|
println!("{:?}", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("🎯 Cursor automatically reset to default!");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
// src/canvas/actions/types.rs
|
// src/canvas/actions/types.rs
|
||||||
|
|
||||||
/// All available canvas actions
|
/// All available canvas actions
|
||||||
|
#[non_exhaustive]
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub enum CanvasAction {
|
pub enum CanvasAction {
|
||||||
// Movement actions
|
// Movement actions
|
||||||
@@ -42,6 +43,7 @@ pub enum CanvasAction {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Result type for canvas actions
|
/// Result type for canvas actions
|
||||||
|
#[non_exhaustive]
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub enum ActionResult {
|
pub enum ActionResult {
|
||||||
Success,
|
Success,
|
||||||
|
|||||||
@@ -15,15 +15,26 @@ impl CursorManager {
|
|||||||
/// Update cursor style based on current mode
|
/// Update cursor style based on current mode
|
||||||
#[cfg(feature = "cursor-style")]
|
#[cfg(feature = "cursor-style")]
|
||||||
pub fn update_for_mode(mode: AppMode) -> io::Result<()> {
|
pub fn update_for_mode(mode: AppMode) -> io::Result<()> {
|
||||||
let style = match mode {
|
// NORMALMODE: force underscore for every mode
|
||||||
AppMode::Edit => SetCursorStyle::SteadyBar, // Thin line for insert
|
#[cfg(feature = "textmode-normal")]
|
||||||
AppMode::ReadOnly => SetCursorStyle::SteadyBlock, // Block for normal
|
{
|
||||||
AppMode::Highlight => SetCursorStyle::BlinkingBlock, // Blinking for visual
|
let style = SetCursorStyle::SteadyBar;
|
||||||
AppMode::General => SetCursorStyle::SteadyBlock, // Block for general
|
return execute!(io::stdout(), style);
|
||||||
AppMode::Command => SetCursorStyle::SteadyUnderScore, // Underscore for command
|
}
|
||||||
};
|
|
||||||
|
// Default (not normal): original mapping
|
||||||
execute!(io::stdout(), style)
|
#[cfg(not(feature = "textmode-normal"))]
|
||||||
|
{
|
||||||
|
let style = match mode {
|
||||||
|
AppMode::Edit => SetCursorStyle::SteadyBar, // Thin line for insert
|
||||||
|
AppMode::ReadOnly => SetCursorStyle::SteadyBlock, // Block for normal
|
||||||
|
AppMode::Highlight => SetCursorStyle::BlinkingBlock, // Blinking for visual
|
||||||
|
AppMode::General => SetCursorStyle::SteadyBlock, // Block for general
|
||||||
|
AppMode::Command => SetCursorStyle::SteadyUnderScore, // Underscore for command
|
||||||
|
};
|
||||||
|
|
||||||
|
return execute!(io::stdout(), style);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// No-op when cursor-style feature is disabled
|
/// No-op when cursor-style feature is disabled
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use ratatui::{
|
|||||||
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
||||||
style::{Modifier, Style},
|
style::{Modifier, Style},
|
||||||
text::{Line, Span},
|
text::{Line, Span},
|
||||||
widgets::{Block, Borders, BorderType, Paragraph},
|
widgets::{Block, Borders, BorderType, Paragraph, Wrap},
|
||||||
Frame,
|
Frame,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -20,8 +20,177 @@ use unicode_width::UnicodeWidthChar;
|
|||||||
#[cfg(feature = "gui")]
|
#[cfg(feature = "gui")]
|
||||||
use std::cmp::{max, min};
|
use std::cmp::{max, min};
|
||||||
|
|
||||||
/// Render ONLY the canvas form fields - no suggestions rendering here
|
#[cfg(feature = "gui")]
|
||||||
/// Updated to work with FormEditor instead of CanvasState trait
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub enum OverflowMode {
|
||||||
|
Indicator(char), // default '$'
|
||||||
|
Wrap,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct CanvasDisplayOptions {
|
||||||
|
pub overflow: OverflowMode,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
impl Default for CanvasDisplayOptions {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
overflow: OverflowMode::Indicator('$'),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Utility: measure display width of a string
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
fn display_width(s: &str) -> u16 {
|
||||||
|
s.chars()
|
||||||
|
.map(|c| UnicodeWidthChar::width(c).unwrap_or(0) as u16)
|
||||||
|
.sum()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Utility: clip a string to fit width, append indicator if overflow
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
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())])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
const RIGHT_PAD: u16 = 3;
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
fn slice_by_display_cols(s: &str, start_cols: u16, max_cols: u16) -> String {
|
||||||
|
if max_cols == 0 {
|
||||||
|
return String::new();
|
||||||
|
}
|
||||||
|
let mut cols: u16 = 0;
|
||||||
|
let mut out = String::new();
|
||||||
|
let mut taken: u16 = 0;
|
||||||
|
let mut started = false;
|
||||||
|
|
||||||
|
for ch in s.chars() {
|
||||||
|
let w = UnicodeWidthChar::width(ch).unwrap_or(0) as u16;
|
||||||
|
let next = cols.saturating_add(w);
|
||||||
|
|
||||||
|
if !started {
|
||||||
|
if next <= start_cols {
|
||||||
|
cols = next;
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
started = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if taken.saturating_add(w) > max_cols {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
out.push(ch);
|
||||||
|
taken = taken.saturating_add(w);
|
||||||
|
cols = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
fn compute_h_scroll_with_padding(cursor_cols: u16, width: u16) -> (u16, u16) {
|
||||||
|
let mut h = 0u16;
|
||||||
|
for _ in 0..2 {
|
||||||
|
let left_cols = if h > 0 { 1 } else { 0 };
|
||||||
|
let max_x_visible = width.saturating_sub(1 + RIGHT_PAD + left_cols);
|
||||||
|
let needed = cursor_cols.saturating_sub(max_x_visible);
|
||||||
|
if needed <= h {
|
||||||
|
return (h, left_cols);
|
||||||
|
}
|
||||||
|
h = needed;
|
||||||
|
}
|
||||||
|
let left_cols = if h > 0 { 1 } else { 0 };
|
||||||
|
(h, left_cols)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
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);
|
||||||
|
|
||||||
|
let total_cols = display_width(typed_text);
|
||||||
|
let content_budget = width.saturating_sub(left_cols);
|
||||||
|
let show_right = total_cols.saturating_sub(h_scroll) > content_budget;
|
||||||
|
let right_cols: u16 = if show_right { 1 } else { 0 };
|
||||||
|
|
||||||
|
let visible_cols = width.saturating_sub(left_cols + right_cols);
|
||||||
|
let visible_typed = slice_by_display_cols(typed_text, h_scroll, visible_cols);
|
||||||
|
|
||||||
|
let used_typed_cols = display_width(&visible_typed);
|
||||||
|
let mut remaining_cols = visible_cols.saturating_sub(used_typed_cols);
|
||||||
|
let mut visible_completion = String::new();
|
||||||
|
|
||||||
|
if let Some(comp) = completion {
|
||||||
|
if !comp.is_empty() && remaining_cols > 0 {
|
||||||
|
visible_completion = slice_by_display_cols(comp, 0, remaining_cols);
|
||||||
|
remaining_cols = remaining_cols.saturating_sub(display_width(&visible_completion));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut spans: Vec<Span> = Vec::with_capacity(3);
|
||||||
|
if left_cols == 1 {
|
||||||
|
spans.push(Span::raw(indicator.to_string()));
|
||||||
|
}
|
||||||
|
spans.push(Span::styled(
|
||||||
|
visible_typed,
|
||||||
|
Style::default().fg(theme.fg()),
|
||||||
|
));
|
||||||
|
if !visible_completion.is_empty() {
|
||||||
|
spans.push(Span::styled(
|
||||||
|
visible_completion,
|
||||||
|
Style::default().fg(theme.suggestion_gray()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if show_right {
|
||||||
|
spans.push(Span::raw(indicator.to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
(Line::from(spans), h_scroll, left_cols)
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(feature = "gui")]
|
#[cfg(feature = "gui")]
|
||||||
pub fn render_canvas<T: CanvasTheme, D: DataProvider>(
|
pub fn render_canvas<T: CanvasTheme, D: DataProvider>(
|
||||||
f: &mut Frame,
|
f: &mut Frame,
|
||||||
@@ -29,32 +198,63 @@ pub fn render_canvas<T: CanvasTheme, D: DataProvider>(
|
|||||||
editor: &FormEditor<D>,
|
editor: &FormEditor<D>,
|
||||||
theme: &T,
|
theme: &T,
|
||||||
) -> Option<Rect> {
|
) -> Option<Rect> {
|
||||||
// Convert SelectionState to HighlightState
|
let opts = CanvasDisplayOptions::default();
|
||||||
let highlight_state = convert_selection_to_highlight(editor.ui_state().selection_state());
|
render_canvas_with_options(f, area, editor, theme, opts)
|
||||||
render_canvas_with_highlight(f, area, editor, theme, &highlight_state)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Render canvas with explicit highlight state (for advanced use)
|
|
||||||
#[cfg(feature = "gui")]
|
#[cfg(feature = "gui")]
|
||||||
pub fn render_canvas_with_highlight<T: CanvasTheme, D: DataProvider>(
|
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,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
fn render_canvas_with_highlight_and_options<T: CanvasTheme, D: DataProvider>(
|
||||||
f: &mut Frame,
|
f: &mut Frame,
|
||||||
area: Rect,
|
area: Rect,
|
||||||
editor: &FormEditor<D>,
|
editor: &FormEditor<D>,
|
||||||
theme: &T,
|
theme: &T,
|
||||||
highlight_state: &HighlightState,
|
highlight_state: &HighlightState,
|
||||||
|
active_completion: Option<String>,
|
||||||
|
opts: CanvasDisplayOptions,
|
||||||
) -> Option<Rect> {
|
) -> Option<Rect> {
|
||||||
let ui_state = editor.ui_state();
|
let ui_state = editor.ui_state();
|
||||||
let data_provider = editor.data_provider();
|
let data_provider = editor.data_provider();
|
||||||
|
|
||||||
// Build field information
|
|
||||||
let field_count = data_provider.field_count();
|
let field_count = data_provider.field_count();
|
||||||
let mut fields: Vec<&str> = Vec::with_capacity(field_count);
|
let mut fields: Vec<&str> = Vec::with_capacity(field_count);
|
||||||
let mut inputs: Vec<String> = Vec::with_capacity(field_count);
|
let mut inputs: Vec<String> = Vec::with_capacity(field_count);
|
||||||
|
|
||||||
for i in 0..field_count {
|
for i in 0..field_count {
|
||||||
fields.push(data_provider.field_name(i));
|
fields.push(data_provider.field_name(i));
|
||||||
|
|
||||||
// Use editor-provided effective display text per field (Feature 4/mask aware)
|
|
||||||
#[cfg(feature = "validation")]
|
#[cfg(feature = "validation")]
|
||||||
{
|
{
|
||||||
inputs.push(editor.display_text_for_field(i));
|
inputs.push(editor.display_text_for_field(i));
|
||||||
@@ -68,20 +268,7 @@ pub fn render_canvas_with_highlight<T: CanvasTheme, D: DataProvider>(
|
|||||||
let current_field_idx = ui_state.current_field();
|
let current_field_idx = ui_state.current_field();
|
||||||
let is_edit_mode = matches!(ui_state.mode(), crate::canvas::modes::AppMode::Edit);
|
let is_edit_mode = matches!(ui_state.mode(), crate::canvas::modes::AppMode::Edit);
|
||||||
|
|
||||||
// Precompute completion for active field
|
render_canvas_fields_with_options(
|
||||||
#[cfg(feature = "suggestions")]
|
|
||||||
let active_completion = if ui_state.is_suggestions_active()
|
|
||||||
&& ui_state.suggestions.active_field == Some(current_field_idx)
|
|
||||||
{
|
|
||||||
ui_state.suggestions.completion_text.clone()
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
#[cfg(not(feature = "suggestions"))]
|
|
||||||
let active_completion: Option<String> = None;
|
|
||||||
|
|
||||||
render_canvas_fields(
|
|
||||||
f,
|
f,
|
||||||
area,
|
area,
|
||||||
&fields,
|
&fields,
|
||||||
@@ -90,52 +277,50 @@ pub fn render_canvas_with_highlight<T: CanvasTheme, D: DataProvider>(
|
|||||||
theme,
|
theme,
|
||||||
is_edit_mode,
|
is_edit_mode,
|
||||||
highlight_state,
|
highlight_state,
|
||||||
editor.display_cursor_position(), // Use display cursor position for masks
|
editor.display_cursor_position(),
|
||||||
false, // TODO: track unsaved changes in editor
|
false,
|
||||||
// Closures for getting display values and overrides
|
|
||||||
#[cfg(feature = "validation")]
|
#[cfg(feature = "validation")]
|
||||||
|field_idx| editor.display_text_for_field(field_idx),
|
|field_idx| editor.display_text_for_field(field_idx),
|
||||||
#[cfg(not(feature = "validation"))]
|
#[cfg(not(feature = "validation"))]
|
||||||
|field_idx| data_provider.field_value(field_idx).to_string(),
|
|field_idx| data_provider.field_value(field_idx).to_string(),
|
||||||
// Closure for checking display overrides
|
|
||||||
#[cfg(feature = "validation")]
|
#[cfg(feature = "validation")]
|
||||||
|field_idx| {
|
|field_idx| {
|
||||||
editor.ui_state().validation_state().get_field_config(field_idx)
|
editor
|
||||||
.map(|cfg| {
|
.ui_state()
|
||||||
let has_formatter = cfg.custom_formatter.is_some();
|
.validation_state()
|
||||||
let has_mask = cfg.display_mask.is_some();
|
.get_field_config(field_idx)
|
||||||
has_formatter || has_mask
|
.map(|cfg| cfg.custom_formatter.is_some() || cfg.display_mask.is_some())
|
||||||
})
|
|
||||||
.unwrap_or(false)
|
.unwrap_or(false)
|
||||||
},
|
},
|
||||||
#[cfg(not(feature = "validation"))]
|
#[cfg(not(feature = "validation"))]
|
||||||
|_field_idx| false,
|
|_field_idx| false,
|
||||||
// Closure for providing completion
|
active_completion,
|
||||||
|field_idx| {
|
opts,
|
||||||
if field_idx == current_field_idx {
|
|
||||||
active_completion.clone()
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convert SelectionState to HighlightState for rendering
|
|
||||||
#[cfg(feature = "gui")]
|
#[cfg(feature = "gui")]
|
||||||
fn convert_selection_to_highlight(selection: &crate::canvas::state::SelectionState) -> HighlightState {
|
fn convert_selection_to_highlight(
|
||||||
|
selection: &crate::canvas::state::SelectionState,
|
||||||
|
) -> HighlightState {
|
||||||
use crate::canvas::state::SelectionState;
|
use crate::canvas::state::SelectionState;
|
||||||
|
|
||||||
match selection {
|
match selection {
|
||||||
SelectionState::None => HighlightState::Off,
|
SelectionState::None => HighlightState::Off,
|
||||||
SelectionState::Characterwise { anchor } => HighlightState::Characterwise { anchor: *anchor },
|
SelectionState::Characterwise { anchor } => {
|
||||||
SelectionState::Linewise { anchor_field } => HighlightState::Linewise { anchor_line: *anchor_field },
|
HighlightState::Characterwise { anchor: *anchor }
|
||||||
|
}
|
||||||
|
SelectionState::Linewise { anchor_field } => {
|
||||||
|
HighlightState::Linewise {
|
||||||
|
anchor_line: *anchor_field,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Core canvas field rendering
|
/// Core canvas field rendering with options
|
||||||
#[cfg(feature = "gui")]
|
#[cfg(feature = "gui")]
|
||||||
fn render_canvas_fields<T: CanvasTheme, F1, F2, F3>(
|
fn render_canvas_fields_with_options<T: CanvasTheme, F1, F2>(
|
||||||
f: &mut Frame,
|
f: &mut Frame,
|
||||||
area: Rect,
|
area: Rect,
|
||||||
fields: &[&str],
|
fields: &[&str],
|
||||||
@@ -148,20 +333,18 @@ fn render_canvas_fields<T: CanvasTheme, F1, F2, F3>(
|
|||||||
has_unsaved_changes: bool,
|
has_unsaved_changes: bool,
|
||||||
get_display_value: F1,
|
get_display_value: F1,
|
||||||
has_display_override: F2,
|
has_display_override: F2,
|
||||||
get_completion: F3,
|
active_completion: Option<String>,
|
||||||
|
opts: CanvasDisplayOptions,
|
||||||
) -> Option<Rect>
|
) -> Option<Rect>
|
||||||
where
|
where
|
||||||
F1: Fn(usize) -> String,
|
F1: Fn(usize) -> String,
|
||||||
F2: Fn(usize) -> bool,
|
F2: Fn(usize) -> bool,
|
||||||
F3: Fn(usize) -> Option<String>,
|
|
||||||
{
|
{
|
||||||
// Create layout
|
|
||||||
let columns = Layout::default()
|
let columns = Layout::default()
|
||||||
.direction(Direction::Horizontal)
|
.direction(Direction::Horizontal)
|
||||||
.constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
|
.constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
|
||||||
.split(area);
|
.split(area);
|
||||||
|
|
||||||
// Border style based on state
|
|
||||||
let border_style = if has_unsaved_changes {
|
let border_style = if has_unsaved_changes {
|
||||||
Style::default().fg(theme.warning())
|
Style::default().fg(theme.warning())
|
||||||
} else if is_edit_mode {
|
} else if is_edit_mode {
|
||||||
@@ -170,7 +353,6 @@ where
|
|||||||
Style::default().fg(theme.secondary())
|
Style::default().fg(theme.secondary())
|
||||||
};
|
};
|
||||||
|
|
||||||
// Input container
|
|
||||||
let input_container = Block::default()
|
let input_container = Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.border_type(BorderType::Rounded)
|
.border_type(BorderType::Rounded)
|
||||||
@@ -186,29 +368,111 @@ where
|
|||||||
|
|
||||||
f.render_widget(&input_container, input_block);
|
f.render_widget(&input_container, input_block);
|
||||||
|
|
||||||
// Input area layout
|
|
||||||
let input_area = input_container.inner(input_block);
|
let input_area = input_container.inner(input_block);
|
||||||
|
|
||||||
let input_rows = Layout::default()
|
let input_rows = Layout::default()
|
||||||
.direction(Direction::Vertical)
|
.direction(Direction::Vertical)
|
||||||
.constraints(vec![Constraint::Length(1); fields.len()])
|
.constraints(vec![Constraint::Length(1); fields.len()])
|
||||||
.split(input_area);
|
.split(input_area);
|
||||||
|
|
||||||
// Render field labels
|
|
||||||
render_field_labels(f, columns[0], input_block, fields, theme);
|
render_field_labels(f, columns[0], input_block, fields, theme);
|
||||||
|
|
||||||
// Render field values and return active field rect
|
let mut active_field_input_rect = None;
|
||||||
render_field_values(
|
|
||||||
f,
|
for i in 0..inputs.len() {
|
||||||
input_rows.to_vec(),
|
let is_active = i == *current_field_idx;
|
||||||
inputs,
|
let typed_text = get_display_value(i);
|
||||||
current_field_idx,
|
let inner_width = input_rows[i].width;
|
||||||
theme,
|
|
||||||
highlight_state,
|
// ---- BEGIN MODIFIED SECTION ----
|
||||||
current_cursor_pos,
|
let mut h_scroll_for_cursor: u16 = 0;
|
||||||
get_display_value,
|
let mut left_offset_for_cursor: u16 = 0;
|
||||||
has_display_override,
|
|
||||||
get_completion,
|
let line = match highlight_state {
|
||||||
)
|
// Selection highlighting active: always use highlighting, even for the active field
|
||||||
|
HighlightState::Characterwise { .. } | HighlightState::Linewise { .. } => {
|
||||||
|
apply_highlighting(
|
||||||
|
&typed_text,
|
||||||
|
i,
|
||||||
|
current_field_idx,
|
||||||
|
current_cursor_pos,
|
||||||
|
highlight_state,
|
||||||
|
theme,
|
||||||
|
is_active,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// No selection highlighting
|
||||||
|
HighlightState::Off => match opts.overflow {
|
||||||
|
// Indicator mode: special-case the active field to preserve h-scroll + indicators
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wrap mode: keep active completion for active line
|
||||||
|
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()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
// ---- END MODIFIED SECTION ----
|
||||||
|
|
||||||
|
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_rows[i]);
|
||||||
|
|
||||||
|
if is_active {
|
||||||
|
active_field_input_rect = Some(input_rows[i]);
|
||||||
|
set_cursor_position_scrolled(
|
||||||
|
f,
|
||||||
|
input_rows[i],
|
||||||
|
&typed_text,
|
||||||
|
current_cursor_pos,
|
||||||
|
has_display_override(i),
|
||||||
|
h_scroll_for_cursor,
|
||||||
|
left_offset_for_cursor,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
active_field_input_rect
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Render field labels
|
/// Render field labels
|
||||||
@@ -237,73 +501,6 @@ fn render_field_labels<T: CanvasTheme>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Render field values with highlighting
|
|
||||||
#[cfg(feature = "gui")]
|
|
||||||
fn render_field_values<T: CanvasTheme, F1, F2, F3>(
|
|
||||||
f: &mut Frame,
|
|
||||||
input_rows: Vec<Rect>,
|
|
||||||
inputs: &[String],
|
|
||||||
current_field_idx: &usize,
|
|
||||||
theme: &T,
|
|
||||||
highlight_state: &HighlightState,
|
|
||||||
current_cursor_pos: usize,
|
|
||||||
get_display_value: F1,
|
|
||||||
has_display_override: F2,
|
|
||||||
get_completion: F3,
|
|
||||||
) -> Option<Rect>
|
|
||||||
where
|
|
||||||
F1: Fn(usize) -> String,
|
|
||||||
F2: Fn(usize) -> bool,
|
|
||||||
F3: Fn(usize) -> Option<String>,
|
|
||||||
{
|
|
||||||
let mut active_field_input_rect = None;
|
|
||||||
|
|
||||||
// FIX: Iterate over indices only since we never use the input values directly
|
|
||||||
for i in 0..inputs.len() {
|
|
||||||
let is_active = i == *current_field_idx;
|
|
||||||
let typed_text = get_display_value(i);
|
|
||||||
|
|
||||||
let line = if is_active {
|
|
||||||
// Compose typed + gray completion for the active field
|
|
||||||
let normal_style = Style::default().fg(theme.fg());
|
|
||||||
let gray_style = Style::default().fg(theme.suggestion_gray());
|
|
||||||
|
|
||||||
let mut spans: Vec<Span> = Vec::new();
|
|
||||||
spans.push(Span::styled(typed_text.clone(), normal_style));
|
|
||||||
|
|
||||||
if let Some(completion) = get_completion(i) {
|
|
||||||
if !completion.is_empty() {
|
|
||||||
spans.push(Span::styled(completion, gray_style));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Line::from(spans)
|
|
||||||
} else {
|
|
||||||
// Non-active fields: keep existing highlighting logic
|
|
||||||
apply_highlighting(
|
|
||||||
&typed_text,
|
|
||||||
i,
|
|
||||||
current_field_idx,
|
|
||||||
current_cursor_pos,
|
|
||||||
highlight_state,
|
|
||||||
theme,
|
|
||||||
is_active,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
|
|
||||||
let input_display = Paragraph::new(line).alignment(Alignment::Left);
|
|
||||||
f.render_widget(input_display, input_rows[i]);
|
|
||||||
|
|
||||||
// Set cursor for active field at end of typed text (not after completion)
|
|
||||||
if is_active {
|
|
||||||
active_field_input_rect = Some(input_rows[i]);
|
|
||||||
set_cursor_position(f, input_rows[i], &typed_text, current_cursor_pos, has_display_override(i));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
active_field_input_rect
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Apply highlighting based on highlight state
|
/// Apply highlighting based on highlight state
|
||||||
#[cfg(feature = "gui")]
|
#[cfg(feature = "gui")]
|
||||||
fn apply_highlighting<'a, T: CanvasTheme>(
|
fn apply_highlighting<'a, T: CanvasTheme>(
|
||||||
@@ -319,21 +516,34 @@ fn apply_highlighting<'a, T: CanvasTheme>(
|
|||||||
|
|
||||||
match highlight_state {
|
match highlight_state {
|
||||||
HighlightState::Off => {
|
HighlightState::Off => {
|
||||||
Line::from(Span::styled(
|
Line::from(Span::styled(text, Style::default().fg(theme.fg())))
|
||||||
text,
|
|
||||||
Style::default().fg(theme.fg())
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
HighlightState::Characterwise { anchor } => {
|
HighlightState::Characterwise { anchor } => {
|
||||||
apply_characterwise_highlighting(text, text_len, field_index, current_field_idx, current_cursor_pos, anchor, theme, is_active)
|
apply_characterwise_highlighting(
|
||||||
|
text,
|
||||||
|
text_len,
|
||||||
|
field_index,
|
||||||
|
current_field_idx,
|
||||||
|
current_cursor_pos,
|
||||||
|
anchor,
|
||||||
|
theme,
|
||||||
|
is_active,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
HighlightState::Linewise { anchor_line } => {
|
HighlightState::Linewise { anchor_line } => {
|
||||||
apply_linewise_highlighting(text, field_index, current_field_idx, anchor_line, theme, is_active)
|
apply_linewise_highlighting(
|
||||||
|
text,
|
||||||
|
field_index,
|
||||||
|
current_field_idx,
|
||||||
|
anchor_line,
|
||||||
|
theme,
|
||||||
|
is_active,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Apply characterwise highlighting - PROPER VIM-LIKE VERSION
|
/// Apply characterwise highlighting (unchanged)
|
||||||
#[cfg(feature = "gui")]
|
#[cfg(feature = "gui")]
|
||||||
fn apply_characterwise_highlighting<'a, T: CanvasTheme>(
|
fn apply_characterwise_highlighting<'a, T: CanvasTheme>(
|
||||||
text: &'a str,
|
text: &'a str,
|
||||||
@@ -349,21 +559,20 @@ fn apply_characterwise_highlighting<'a, T: CanvasTheme>(
|
|||||||
let start_field = min(anchor_field, *current_field_idx);
|
let start_field = min(anchor_field, *current_field_idx);
|
||||||
let end_field = max(anchor_field, *current_field_idx);
|
let end_field = max(anchor_field, *current_field_idx);
|
||||||
|
|
||||||
// Vim-like styling:
|
|
||||||
// - Selected text: contrasting color + background (like vim visual selection)
|
|
||||||
// - All other text: normal color (no special colors for active fields, etc.)
|
|
||||||
let highlight_style = Style::default()
|
let highlight_style = Style::default()
|
||||||
.fg(theme.highlight()) // ✅ Contrasting text color for selected text
|
.fg(theme.highlight())
|
||||||
.bg(theme.highlight_bg()) // ✅ Background for selected text
|
.bg(theme.highlight_bg())
|
||||||
.add_modifier(Modifier::BOLD);
|
.add_modifier(Modifier::BOLD);
|
||||||
|
|
||||||
let normal_style = Style::default().fg(theme.fg()); // ✅ Normal text color everywhere else
|
let normal_style = Style::default().fg(theme.fg());
|
||||||
|
|
||||||
if field_index >= start_field && field_index <= end_field {
|
if field_index >= start_field && field_index <= end_field {
|
||||||
if start_field == end_field {
|
if start_field == end_field {
|
||||||
// Single field selection
|
|
||||||
let (start_char, end_char) = if anchor_field == *current_field_idx {
|
let (start_char, end_char) = if anchor_field == *current_field_idx {
|
||||||
(min(anchor_char, current_cursor_pos), max(anchor_char, current_cursor_pos))
|
(
|
||||||
|
min(anchor_char, current_cursor_pos),
|
||||||
|
max(anchor_char, current_cursor_pos),
|
||||||
|
)
|
||||||
} else if anchor_field < *current_field_idx {
|
} else if anchor_field < *current_field_idx {
|
||||||
(anchor_char, current_cursor_pos)
|
(anchor_char, current_cursor_pos)
|
||||||
} else {
|
} else {
|
||||||
@@ -374,19 +583,19 @@ fn apply_characterwise_highlighting<'a, T: CanvasTheme>(
|
|||||||
let clamped_end = end_char.min(text_len);
|
let clamped_end = end_char.min(text_len);
|
||||||
|
|
||||||
let before: String = text.chars().take(clamped_start).collect();
|
let before: String = text.chars().take(clamped_start).collect();
|
||||||
let highlighted: String = text.chars()
|
let highlighted: String = text
|
||||||
|
.chars()
|
||||||
.skip(clamped_start)
|
.skip(clamped_start)
|
||||||
.take(clamped_end.saturating_sub(clamped_start) + 1)
|
.take(clamped_end.saturating_sub(clamped_start) + 1)
|
||||||
.collect();
|
.collect();
|
||||||
let after: String = text.chars().skip(clamped_end + 1).collect();
|
let after: String = text.chars().skip(clamped_end + 1).collect();
|
||||||
|
|
||||||
Line::from(vec![
|
Line::from(vec![
|
||||||
Span::styled(before, normal_style), // Normal text color
|
Span::styled(before, normal_style),
|
||||||
Span::styled(highlighted, highlight_style), // Contrasting color + background
|
Span::styled(highlighted, highlight_style),
|
||||||
Span::styled(after, normal_style), // Normal text color
|
Span::styled(after, normal_style),
|
||||||
])
|
])
|
||||||
} else {
|
} else {
|
||||||
// Multi-field selection
|
|
||||||
if field_index == anchor_field {
|
if field_index == anchor_field {
|
||||||
if anchor_field < *current_field_idx {
|
if anchor_field < *current_field_idx {
|
||||||
let clamped_start = anchor_char.min(text_len);
|
let clamped_start = anchor_char.min(text_len);
|
||||||
@@ -428,17 +637,15 @@ fn apply_characterwise_highlighting<'a, T: CanvasTheme>(
|
|||||||
])
|
])
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Middle field: highlight entire field
|
|
||||||
Line::from(Span::styled(text, highlight_style))
|
Line::from(Span::styled(text, highlight_style))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Outside selection: always normal text color (no special active field color)
|
|
||||||
Line::from(Span::styled(text, normal_style))
|
Line::from(Span::styled(text, normal_style))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Apply linewise highlighting - PROPER VIM-LIKE VERSION
|
/// Apply linewise highlighting (unchanged)
|
||||||
#[cfg(feature = "gui")]
|
#[cfg(feature = "gui")]
|
||||||
fn apply_linewise_highlighting<'a, T: CanvasTheme>(
|
fn apply_linewise_highlighting<'a, T: CanvasTheme>(
|
||||||
text: &'a str,
|
text: &'a str,
|
||||||
@@ -451,35 +658,31 @@ fn apply_linewise_highlighting<'a, T: CanvasTheme>(
|
|||||||
let start_field = min(*anchor_line, *current_field_idx);
|
let start_field = min(*anchor_line, *current_field_idx);
|
||||||
let end_field = max(*anchor_line, *current_field_idx);
|
let end_field = max(*anchor_line, *current_field_idx);
|
||||||
|
|
||||||
// Vim-like styling:
|
|
||||||
// - Selected lines: contrasting text color + background
|
|
||||||
// - All other lines: normal text color (no special active field color)
|
|
||||||
let highlight_style = Style::default()
|
let highlight_style = Style::default()
|
||||||
.fg(theme.highlight()) // ✅ Contrasting text color for selected text
|
.fg(theme.highlight())
|
||||||
.bg(theme.highlight_bg()) // ✅ Background for selected text
|
.bg(theme.highlight_bg())
|
||||||
.add_modifier(Modifier::BOLD);
|
.add_modifier(Modifier::BOLD);
|
||||||
|
|
||||||
let normal_style = Style::default().fg(theme.fg()); // ✅ Normal text color everywhere else
|
let normal_style = Style::default().fg(theme.fg());
|
||||||
|
|
||||||
if field_index >= start_field && field_index <= end_field {
|
if field_index >= start_field && field_index <= end_field {
|
||||||
// Selected line: contrasting text color + background
|
|
||||||
Line::from(Span::styled(text, highlight_style))
|
Line::from(Span::styled(text, highlight_style))
|
||||||
} else {
|
} else {
|
||||||
// Normal line: normal text color (no special active field color)
|
|
||||||
Line::from(Span::styled(text, normal_style))
|
Line::from(Span::styled(text, normal_style))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set cursor position
|
/// Set cursor position (x clamp only; no Y offset with wrap in this version)
|
||||||
#[cfg(feature = "gui")]
|
#[cfg(feature = "gui")]
|
||||||
fn set_cursor_position(
|
fn set_cursor_position_scrolled(
|
||||||
f: &mut Frame,
|
f: &mut Frame,
|
||||||
field_rect: Rect,
|
field_rect: Rect,
|
||||||
text: &str,
|
text: &str,
|
||||||
current_cursor_pos: usize,
|
current_cursor_pos: usize,
|
||||||
_has_display_override: bool,
|
_has_display_override: bool,
|
||||||
|
h_scroll: u16,
|
||||||
|
left_offset: u16,
|
||||||
) {
|
) {
|
||||||
// Sum display widths of the first current_cursor_pos characters
|
|
||||||
let mut cols: u16 = 0;
|
let mut cols: u16 = 0;
|
||||||
for (i, ch) in text.chars().enumerate() {
|
for (i, ch) in text.chars().enumerate() {
|
||||||
if i >= current_cursor_pos {
|
if i >= current_cursor_pos {
|
||||||
@@ -488,17 +691,19 @@ fn set_cursor_position(
|
|||||||
cols = cols.saturating_add(UnicodeWidthChar::width(ch).unwrap_or(0) as u16);
|
cols = cols.saturating_add(UnicodeWidthChar::width(ch).unwrap_or(0) as u16);
|
||||||
}
|
}
|
||||||
|
|
||||||
let cursor_x = field_rect.x.saturating_add(cols);
|
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;
|
let cursor_y = field_rect.y;
|
||||||
|
f.set_cursor_position((cursor_x, cursor_y));
|
||||||
// Clamp to field bounds
|
|
||||||
let max_cursor_x = field_rect.x + field_rect.width.saturating_sub(1);
|
|
||||||
let safe_cursor_x = cursor_x.min(max_cursor_x);
|
|
||||||
|
|
||||||
f.set_cursor_position((safe_cursor_x, cursor_y));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set default theme if custom not specified
|
/// Default theme
|
||||||
#[cfg(feature = "gui")]
|
#[cfg(feature = "gui")]
|
||||||
pub fn render_canvas_default<D: DataProvider>(
|
pub fn render_canvas_default<D: DataProvider>(
|
||||||
f: &mut Frame,
|
f: &mut Frame,
|
||||||
|
|||||||
@@ -36,13 +36,22 @@ impl ModeManager {
|
|||||||
|
|
||||||
/// Transition to new mode with automatic cursor update (when cursor-style feature enabled)
|
/// Transition to new mode with automatic cursor update (when cursor-style feature enabled)
|
||||||
pub fn transition_to_mode(current_mode: AppMode, new_mode: AppMode) -> std::io::Result<AppMode> {
|
pub fn transition_to_mode(current_mode: AppMode, new_mode: AppMode) -> std::io::Result<AppMode> {
|
||||||
if current_mode != new_mode {
|
#[cfg(feature = "textmode-normal")]
|
||||||
#[cfg(feature = "cursor-style")]
|
{
|
||||||
{
|
// Always force Edit in normalmode
|
||||||
let _ = CursorManager::update_for_mode(new_mode);
|
return Ok(AppMode::Edit);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "textmode-normal"))]
|
||||||
|
{
|
||||||
|
if current_mode != new_mode {
|
||||||
|
#[cfg(feature = "cursor-style")]
|
||||||
|
{
|
||||||
|
let _ = CursorManager::update_for_mode(new_mode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(new_mode)
|
||||||
}
|
}
|
||||||
Ok(new_mode)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Enter highlight mode with cursor styling
|
/// Enter highlight mode with cursor styling
|
||||||
|
|||||||
@@ -54,7 +54,13 @@ impl EditorState {
|
|||||||
current_field: 0,
|
current_field: 0,
|
||||||
cursor_pos: 0,
|
cursor_pos: 0,
|
||||||
ideal_cursor_column: 0,
|
ideal_cursor_column: 0,
|
||||||
|
// NORMALMODE: always start in Edit
|
||||||
|
#[cfg(feature = "textmode-normal")]
|
||||||
current_mode: AppMode::Edit,
|
current_mode: AppMode::Edit,
|
||||||
|
// Default (vim): start in ReadOnly
|
||||||
|
#[cfg(not(feature = "textmode-normal"))]
|
||||||
|
current_mode: AppMode::ReadOnly,
|
||||||
|
|
||||||
#[cfg(feature = "suggestions")]
|
#[cfg(feature = "suggestions")]
|
||||||
suggestions: SuggestionsUIState {
|
suggestions: SuggestionsUIState {
|
||||||
is_active: false,
|
is_active: false,
|
||||||
|
|||||||
@@ -53,10 +53,19 @@ impl<D: DataProvider> FormEditor<D> {
|
|||||||
{
|
{
|
||||||
let mut editor = editor;
|
let mut editor = editor;
|
||||||
editor.initialize_validation();
|
editor.initialize_validation();
|
||||||
|
|
||||||
|
#[cfg(feature = "cursor-style")]
|
||||||
|
{
|
||||||
|
let _ = CursorManager::update_for_mode(editor.ui_state.current_mode);
|
||||||
|
}
|
||||||
editor
|
editor
|
||||||
}
|
}
|
||||||
#[cfg(not(feature = "validation"))]
|
#[cfg(not(feature = "validation"))]
|
||||||
{
|
{
|
||||||
|
#[cfg(feature = "cursor-style")]
|
||||||
|
{
|
||||||
|
let _ = CursorManager::update_for_mode(editor.ui_state.current_mode);
|
||||||
|
}
|
||||||
editor
|
editor
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,8 +9,27 @@ use crate::editor::FormEditor;
|
|||||||
use crate::DataProvider;
|
use crate::DataProvider;
|
||||||
|
|
||||||
impl<D: DataProvider> FormEditor<D> {
|
impl<D: DataProvider> FormEditor<D> {
|
||||||
/// Change mode (for vim compatibility)
|
/// Change mode
|
||||||
pub fn set_mode(&mut self, mode: AppMode) {
|
pub fn set_mode(&mut self, mode: AppMode) {
|
||||||
|
// Avoid unused param warning in normalmode
|
||||||
|
#[cfg(feature = "textmode-normal")]
|
||||||
|
let _ = mode;
|
||||||
|
|
||||||
|
// NORMALMODE: force Edit, ignore requested mode
|
||||||
|
#[cfg(feature = "textmode-normal")]
|
||||||
|
{
|
||||||
|
self.ui_state.current_mode = AppMode::Edit;
|
||||||
|
self.ui_state.selection = SelectionState::None;
|
||||||
|
|
||||||
|
#[cfg(feature = "cursor-style")]
|
||||||
|
{
|
||||||
|
let _ = CursorManager::update_for_mode(AppMode::Edit);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default (not normal): original vim behavior
|
||||||
|
#[cfg(not(feature = "textmode-normal"))]
|
||||||
match (self.ui_state.current_mode, mode) {
|
match (self.ui_state.current_mode, mode) {
|
||||||
(AppMode::ReadOnly, AppMode::Highlight) => {
|
(AppMode::ReadOnly, AppMode::Highlight) => {
|
||||||
self.enter_highlight_mode();
|
self.enter_highlight_mode();
|
||||||
@@ -23,7 +42,6 @@ impl<D: DataProvider> FormEditor<D> {
|
|||||||
if new_mode != AppMode::Highlight {
|
if new_mode != AppMode::Highlight {
|
||||||
self.ui_state.selection = SelectionState::None;
|
self.ui_state.selection = SelectionState::None;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "cursor-style")]
|
#[cfg(feature = "cursor-style")]
|
||||||
{
|
{
|
||||||
let _ = CursorManager::update_for_mode(new_mode);
|
let _ = CursorManager::update_for_mode(new_mode);
|
||||||
@@ -32,7 +50,7 @@ impl<D: DataProvider> FormEditor<D> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Exit edit mode to read-only mode (vim Escape)
|
/// Exit edit mode to read-only mode
|
||||||
pub fn exit_edit_mode(&mut self) -> anyhow::Result<()> {
|
pub fn exit_edit_mode(&mut self) -> anyhow::Result<()> {
|
||||||
#[cfg(feature = "validation")]
|
#[cfg(feature = "validation")]
|
||||||
{
|
{
|
||||||
@@ -41,7 +59,9 @@ impl<D: DataProvider> FormEditor<D> {
|
|||||||
self.ui_state.current_field,
|
self.ui_state.current_field,
|
||||||
current_text,
|
current_text,
|
||||||
) {
|
) {
|
||||||
if let Some(reason) = self.ui_state.validation
|
if let Some(reason) = self
|
||||||
|
.ui_state
|
||||||
|
.validation
|
||||||
.field_switch_block_reason(
|
.field_switch_block_reason(
|
||||||
self.ui_state.current_field,
|
self.ui_state.current_field,
|
||||||
current_text,
|
current_text,
|
||||||
@@ -92,15 +112,29 @@ impl<D: DataProvider> FormEditor<D> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
self.set_mode(AppMode::ReadOnly);
|
// NORMALMODE: stay in Edit (do not switch to ReadOnly)
|
||||||
#[cfg(feature = "suggestions")]
|
#[cfg(feature = "textmode-normal")]
|
||||||
{
|
{
|
||||||
self.close_suggestions();
|
#[cfg(feature = "suggestions")]
|
||||||
|
{
|
||||||
|
self.close_suggestions();
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default (not normal): original vim behavior
|
||||||
|
#[cfg(not(feature = "textmode-normal"))]
|
||||||
|
{
|
||||||
|
self.set_mode(AppMode::ReadOnly);
|
||||||
|
#[cfg(feature = "suggestions")]
|
||||||
|
{
|
||||||
|
self.close_suggestions();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Enter edit mode from read-only mode (vim i/a/o)
|
/// Enter edit mode
|
||||||
pub fn enter_edit_mode(&mut self) {
|
pub fn enter_edit_mode(&mut self) {
|
||||||
#[cfg(feature = "computed")]
|
#[cfg(feature = "computed")]
|
||||||
{
|
{
|
||||||
@@ -111,52 +145,104 @@ impl<D: DataProvider> FormEditor<D> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NORMALMODE: already in Edit, but enforce it
|
||||||
|
#[cfg(feature = "textmode-normal")]
|
||||||
|
{
|
||||||
|
self.ui_state.current_mode = AppMode::Edit;
|
||||||
|
self.ui_state.selection = SelectionState::None;
|
||||||
|
#[cfg(feature = "cursor-style")]
|
||||||
|
{
|
||||||
|
let _ = CursorManager::update_for_mode(AppMode::Edit);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default (not normal): vim behavior
|
||||||
|
#[cfg(not(feature = "textmode-normal"))]
|
||||||
self.set_mode(AppMode::Edit);
|
self.set_mode(AppMode::Edit);
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------------------- Highlight/Visual mode -------------------------
|
// -------------------- Highlight/Visual mode -------------------------
|
||||||
|
|
||||||
pub fn enter_highlight_mode(&mut self) {
|
pub fn enter_highlight_mode(&mut self) {
|
||||||
if self.ui_state.current_mode == AppMode::ReadOnly {
|
// NORMALMODE: ignore request (stay in Edit)
|
||||||
self.ui_state.current_mode = AppMode::Highlight;
|
#[cfg(feature = "textmode-normal")]
|
||||||
self.ui_state.selection = SelectionState::Characterwise {
|
{
|
||||||
anchor: (self.ui_state.current_field, self.ui_state.cursor_pos),
|
return;
|
||||||
};
|
}
|
||||||
|
|
||||||
#[cfg(feature = "cursor-style")]
|
// Default (not normal): original vim
|
||||||
{
|
#[cfg(not(feature = "textmode-normal"))]
|
||||||
let _ = CursorManager::update_for_mode(AppMode::Highlight);
|
{
|
||||||
|
if self.ui_state.current_mode == AppMode::ReadOnly {
|
||||||
|
self.ui_state.current_mode = AppMode::Highlight;
|
||||||
|
self.ui_state.selection = SelectionState::Characterwise {
|
||||||
|
anchor: (self.ui_state.current_field, self.ui_state.cursor_pos),
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(feature = "cursor-style")]
|
||||||
|
{
|
||||||
|
let _ = CursorManager::update_for_mode(AppMode::Highlight);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn enter_highlight_line_mode(&mut self) {
|
pub fn enter_highlight_line_mode(&mut self) {
|
||||||
if self.ui_state.current_mode == AppMode::ReadOnly {
|
// NORMALMODE: ignore
|
||||||
self.ui_state.current_mode = AppMode::Highlight;
|
#[cfg(feature = "textmode-normal")]
|
||||||
self.ui_state.selection =
|
{
|
||||||
SelectionState::Linewise { anchor_field: self.ui_state.current_field };
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(feature = "cursor-style")]
|
// Default (not normal): original vim
|
||||||
{
|
#[cfg(not(feature = "textmode-normal"))]
|
||||||
let _ = CursorManager::update_for_mode(AppMode::Highlight);
|
{
|
||||||
|
if self.ui_state.current_mode == AppMode::ReadOnly {
|
||||||
|
self.ui_state.current_mode = AppMode::Highlight;
|
||||||
|
self.ui_state.selection =
|
||||||
|
SelectionState::Linewise { anchor_field: self.ui_state.current_field };
|
||||||
|
|
||||||
|
#[cfg(feature = "cursor-style")]
|
||||||
|
{
|
||||||
|
let _ = CursorManager::update_for_mode(AppMode::Highlight);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn exit_highlight_mode(&mut self) {
|
pub fn exit_highlight_mode(&mut self) {
|
||||||
if self.ui_state.current_mode == AppMode::Highlight {
|
// NORMALMODE: ignore
|
||||||
self.ui_state.current_mode = AppMode::ReadOnly;
|
#[cfg(feature = "textmode-normal")]
|
||||||
self.ui_state.selection = SelectionState::None;
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(feature = "cursor-style")]
|
// Default (not normal): original vim
|
||||||
{
|
#[cfg(not(feature = "textmode-normal"))]
|
||||||
let _ = CursorManager::update_for_mode(AppMode::ReadOnly);
|
{
|
||||||
|
if self.ui_state.current_mode == AppMode::Highlight {
|
||||||
|
self.ui_state.current_mode = AppMode::ReadOnly;
|
||||||
|
self.ui_state.selection = SelectionState::None;
|
||||||
|
|
||||||
|
#[cfg(feature = "cursor-style")]
|
||||||
|
{
|
||||||
|
let _ = CursorManager::update_for_mode(AppMode::ReadOnly);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_highlight_mode(&self) -> bool {
|
pub fn is_highlight_mode(&self) -> bool {
|
||||||
self.ui_state.current_mode == AppMode::Highlight
|
#[cfg(feature = "textmode-normal")]
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "textmode-normal"))]
|
||||||
|
{
|
||||||
|
return self.ui_state.current_mode == AppMode::Highlight;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn selection_state(&self) -> &SelectionState {
|
pub fn selection_state(&self) -> &SelectionState {
|
||||||
@@ -164,6 +250,8 @@ impl<D: DataProvider> FormEditor<D> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Visual-mode movements reuse existing movement methods
|
// Visual-mode movements reuse existing movement methods
|
||||||
|
// These keep calling the movement methods; in normalmode selection is never enabled,
|
||||||
|
// so these just move without creating a selection.
|
||||||
pub fn move_left_with_selection(&mut self) {
|
pub fn move_left_with_selection(&mut self) {
|
||||||
let _ = self.move_left();
|
let _ = self.move_left();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,10 @@ pub mod suggestions;
|
|||||||
#[cfg(feature = "validation")]
|
#[cfg(feature = "validation")]
|
||||||
pub mod validation;
|
pub mod validation;
|
||||||
|
|
||||||
|
// First-class textarea module and exports
|
||||||
|
#[cfg(feature = "textarea")]
|
||||||
|
pub mod textarea;
|
||||||
|
|
||||||
// Only include computed module if feature is enabled
|
// Only include computed module if feature is enabled
|
||||||
#[cfg(feature = "computed")]
|
#[cfg(feature = "computed")]
|
||||||
pub mod computed;
|
pub mod computed;
|
||||||
@@ -56,10 +60,17 @@ pub use computed::{ComputedProvider, ComputedContext, ComputedState};
|
|||||||
pub use canvas::theme::{CanvasTheme, DefaultCanvasTheme};
|
pub use canvas::theme::{CanvasTheme, DefaultCanvasTheme};
|
||||||
|
|
||||||
#[cfg(feature = "gui")]
|
#[cfg(feature = "gui")]
|
||||||
pub use canvas::gui::render_canvas;
|
pub use canvas::gui::{render_canvas, render_canvas_default};
|
||||||
|
|
||||||
#[cfg(feature = "gui")]
|
#[cfg(feature = "gui")]
|
||||||
pub use canvas::gui::render_canvas_default;
|
pub use canvas::gui::render_canvas_with_options;
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
pub use canvas::gui::{CanvasDisplayOptions, OverflowMode};
|
||||||
|
|
||||||
#[cfg(all(feature = "gui", feature = "suggestions"))]
|
#[cfg(all(feature = "gui", feature = "suggestions"))]
|
||||||
pub use suggestions::gui::render_suggestions_dropdown;
|
pub use suggestions::gui::render_suggestions_dropdown;
|
||||||
|
|
||||||
|
|
||||||
|
#[cfg(feature = "textarea")]
|
||||||
|
pub use textarea::{TextArea, TextAreaProvider, TextAreaState, TextAreaEditor};
|
||||||
|
|||||||
12
canvas/src/textarea/mod.rs
Normal file
12
canvas/src/textarea/mod.rs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
// src/textarea/mod.rs
|
||||||
|
pub mod provider;
|
||||||
|
pub mod state;
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
pub mod widget;
|
||||||
|
|
||||||
|
pub use provider::TextAreaProvider;
|
||||||
|
pub use state::{TextAreaEditor, TextAreaState, TextOverflowMode};
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
pub use widget::TextArea;
|
||||||
134
canvas/src/textarea/provider.rs
Normal file
134
canvas/src/textarea/provider.rs
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
// src/textarea/provider.rs
|
||||||
|
use crate::DataProvider;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct TextAreaProvider {
|
||||||
|
lines: Vec<String>,
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for TextAreaProvider {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
lines: vec![String::new()],
|
||||||
|
name: "Text".to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TextAreaProvider {
|
||||||
|
pub fn from_text<S: Into<String>>(text: S) -> Self {
|
||||||
|
let text = text.into();
|
||||||
|
let mut lines: Vec<String> =
|
||||||
|
text.split('\n').map(|s| s.to_string()).collect();
|
||||||
|
if lines.is_empty() {
|
||||||
|
lines.push(String::new());
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
lines,
|
||||||
|
name: "Text".to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_text(&self) -> String {
|
||||||
|
self.lines.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_text<S: Into<String>>(&mut self, text: S) {
|
||||||
|
let text = text.into();
|
||||||
|
self.lines = text.split('\n').map(|s| s.to_string()).collect();
|
||||||
|
if self.lines.is_empty() {
|
||||||
|
self.lines.push(String::new());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn line_count(&self) -> usize {
|
||||||
|
self.lines.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn char_to_byte_index(s: &str, char_idx: usize) -> usize {
|
||||||
|
s.char_indices()
|
||||||
|
.nth(char_idx)
|
||||||
|
.map(|(i, _)| i)
|
||||||
|
.unwrap_or_else(|| s.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn split_line_at(&mut self, line_idx: usize, at_char: usize) -> usize {
|
||||||
|
if line_idx >= self.lines.len() {
|
||||||
|
return self.lines.len().saturating_sub(1);
|
||||||
|
}
|
||||||
|
let line = &mut self.lines[line_idx];
|
||||||
|
let byte_idx = Self::char_to_byte_index(line, at_char);
|
||||||
|
let right = line[byte_idx..].to_string();
|
||||||
|
line.truncate(byte_idx);
|
||||||
|
let insert_at = line_idx + 1;
|
||||||
|
self.lines.insert(insert_at, right);
|
||||||
|
insert_at
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn join_with_next(&mut self, line_idx: usize) -> Option<usize> {
|
||||||
|
if line_idx + 1 >= self.lines.len() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let left_len = self.lines[line_idx].chars().count();
|
||||||
|
let right = self.lines.remove(line_idx + 1);
|
||||||
|
self.lines[line_idx].push_str(&right);
|
||||||
|
Some(left_len)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn join_with_prev(
|
||||||
|
&mut self,
|
||||||
|
line_idx: usize,
|
||||||
|
) -> Option<(usize, usize)> {
|
||||||
|
if line_idx == 0 || line_idx >= self.lines.len() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let prev_idx = line_idx - 1;
|
||||||
|
let prev_len = self.lines[prev_idx].chars().count();
|
||||||
|
let curr = self.lines.remove(line_idx);
|
||||||
|
self.lines[prev_idx].push_str(&curr);
|
||||||
|
Some((prev_idx, prev_len))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn insert_blank_line_after(&mut self, idx: usize) -> usize {
|
||||||
|
let clamped = idx.min(self.lines.len());
|
||||||
|
let insert_at = if clamped >= self.lines.len() {
|
||||||
|
self.lines.len()
|
||||||
|
} else {
|
||||||
|
clamped + 1
|
||||||
|
};
|
||||||
|
if insert_at == self.lines.len() {
|
||||||
|
self.lines.push(String::new());
|
||||||
|
} else {
|
||||||
|
self.lines.insert(insert_at, String::new());
|
||||||
|
}
|
||||||
|
insert_at
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn insert_blank_line_before(&mut self, idx: usize) -> usize {
|
||||||
|
let insert_at = idx.min(self.lines.len());
|
||||||
|
self.lines.insert(insert_at, String::new());
|
||||||
|
insert_at
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DataProvider for TextAreaProvider {
|
||||||
|
fn field_count(&self) -> usize {
|
||||||
|
self.lines.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn field_name(&self, _index: usize) -> &str {
|
||||||
|
&self.name
|
||||||
|
}
|
||||||
|
|
||||||
|
fn field_value(&self, index: usize) -> &str {
|
||||||
|
self.lines.get(index).map(|s| s.as_str()).unwrap_or("")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_field_value(&mut self, index: usize, value: String) {
|
||||||
|
if index < self.lines.len() {
|
||||||
|
self.lines[index] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
518
canvas/src/textarea/state.rs
Normal file
518
canvas/src/textarea/state.rs
Normal file
@@ -0,0 +1,518 @@
|
|||||||
|
// src/textarea/state.rs
|
||||||
|
use std::ops::{Deref, DerefMut};
|
||||||
|
|
||||||
|
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
|
||||||
|
|
||||||
|
use crate::editor::FormEditor;
|
||||||
|
use crate::textarea::provider::TextAreaProvider;
|
||||||
|
use crate::data_provider::DataProvider;
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
use ratatui::{layout::Rect, widgets::Block};
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
use unicode_width::UnicodeWidthChar;
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
pub(crate) const RIGHT_PAD: u16 = 3;
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
pub(crate) fn compute_h_scroll_with_padding(
|
||||||
|
cursor_cols: u16,
|
||||||
|
width: u16,
|
||||||
|
) -> (u16, u16) {
|
||||||
|
let mut h = 0u16;
|
||||||
|
for _ in 0..2 {
|
||||||
|
let left_cols = if h > 0 { 1 } else { 0 };
|
||||||
|
let max_x_visible = width.saturating_sub(1 + RIGHT_PAD + left_cols);
|
||||||
|
let needed = cursor_cols.saturating_sub(max_x_visible);
|
||||||
|
if needed <= h {
|
||||||
|
return (h, left_cols);
|
||||||
|
}
|
||||||
|
h = needed;
|
||||||
|
}
|
||||||
|
let left_cols = if h > 0 { 1 } else { 0 };
|
||||||
|
(h, left_cols)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
fn normalize_indent(width: u16, indent: u16) -> u16 {
|
||||||
|
indent.min(width.saturating_sub(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
pub(crate) fn count_wrapped_rows_indented(
|
||||||
|
s: &str,
|
||||||
|
width: u16,
|
||||||
|
indent: u16,
|
||||||
|
) -> u16 {
|
||||||
|
if width == 0 {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
let indent = normalize_indent(width, indent);
|
||||||
|
let cont_cap = width.saturating_sub(indent);
|
||||||
|
|
||||||
|
let mut rows: u16 = 1;
|
||||||
|
let mut used: u16 = 0;
|
||||||
|
let mut first = true;
|
||||||
|
|
||||||
|
for ch in s.chars() {
|
||||||
|
let w = UnicodeWidthChar::width(ch).unwrap_or(0) as u16;
|
||||||
|
let cap = if first { width } else { cont_cap };
|
||||||
|
|
||||||
|
if used > 0 && used.saturating_add(w) >= cap {
|
||||||
|
rows = rows.saturating_add(1);
|
||||||
|
first = false;
|
||||||
|
used = indent;
|
||||||
|
}
|
||||||
|
used = used.saturating_add(w);
|
||||||
|
}
|
||||||
|
|
||||||
|
rows
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
fn wrapped_rows_to_cursor_indented(
|
||||||
|
s: &str,
|
||||||
|
width: u16,
|
||||||
|
indent: u16,
|
||||||
|
cursor_chars: usize,
|
||||||
|
) -> (u16, u16) {
|
||||||
|
if width == 0 {
|
||||||
|
return (0, 0);
|
||||||
|
}
|
||||||
|
let indent = normalize_indent(width, indent);
|
||||||
|
let cont_cap = width.saturating_sub(indent);
|
||||||
|
|
||||||
|
let mut row: u16 = 0;
|
||||||
|
let mut used: u16 = 0;
|
||||||
|
let mut first = true;
|
||||||
|
|
||||||
|
for (i, ch) in s.chars().enumerate() {
|
||||||
|
if i >= cursor_chars {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let w = UnicodeWidthChar::width(ch).unwrap_or(0) as u16;
|
||||||
|
let cap = if first { width } else { cont_cap };
|
||||||
|
|
||||||
|
if used > 0 && used.saturating_add(w) >= cap {
|
||||||
|
row = row.saturating_add(1);
|
||||||
|
first = false;
|
||||||
|
used = indent;
|
||||||
|
}
|
||||||
|
used = used.saturating_add(w);
|
||||||
|
}
|
||||||
|
|
||||||
|
(row, used.min(width.saturating_sub(1)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type TextAreaEditor = FormEditor<TextAreaProvider>;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum TextOverflowMode {
|
||||||
|
Indicator { ch: char },
|
||||||
|
Wrap,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct TextAreaState {
|
||||||
|
pub(crate) editor: TextAreaEditor,
|
||||||
|
pub(crate) scroll_y: u16,
|
||||||
|
pub(crate) placeholder: Option<String>,
|
||||||
|
pub(crate) overflow_mode: TextOverflowMode,
|
||||||
|
pub(crate) h_scroll: u16,
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
pub(crate) wrap_indent_cols: u16,
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
pub(crate) edited_this_frame: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for TextAreaState {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
editor: FormEditor::new(TextAreaProvider::default()),
|
||||||
|
scroll_y: 0,
|
||||||
|
placeholder: None,
|
||||||
|
overflow_mode: TextOverflowMode::Indicator { ch: '$' },
|
||||||
|
h_scroll: 0,
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
wrap_indent_cols: 0,
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
edited_this_frame: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deref for TextAreaState {
|
||||||
|
type Target = TextAreaEditor;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.editor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DerefMut for TextAreaState {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
&mut self.editor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TextAreaState {
|
||||||
|
pub fn from_text<S: Into<String>>(text: S) -> Self {
|
||||||
|
let provider = TextAreaProvider::from_text(text);
|
||||||
|
Self {
|
||||||
|
editor: FormEditor::new(provider),
|
||||||
|
scroll_y: 0,
|
||||||
|
placeholder: None,
|
||||||
|
overflow_mode: TextOverflowMode::Indicator { ch: '$' },
|
||||||
|
h_scroll: 0,
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
wrap_indent_cols: 0,
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
edited_this_frame: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn text(&self) -> String {
|
||||||
|
self.editor.data_provider().to_text()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_text<S: Into<String>>(&mut self, text: S) {
|
||||||
|
self.editor.data_provider_mut().set_text(text);
|
||||||
|
self.editor.ui_state.current_field = 0;
|
||||||
|
self.editor.ui_state.cursor_pos = 0;
|
||||||
|
self.editor.ui_state.ideal_cursor_column = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_placeholder<S: Into<String>>(&mut self, s: S) {
|
||||||
|
self.placeholder = Some(s.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn use_overflow_indicator(&mut self, ch: char) {
|
||||||
|
self.overflow_mode = TextOverflowMode::Indicator { ch };
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn use_wrap(&mut self) {
|
||||||
|
self.overflow_mode = TextOverflowMode::Wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_wrap_indent_cols(&mut self, cols: u16) {
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
{
|
||||||
|
self.wrap_indent_cols = cols;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn insert_newline(&mut self) {
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
{
|
||||||
|
self.edited_this_frame = true;
|
||||||
|
}
|
||||||
|
let line_idx = self.current_field();
|
||||||
|
let col = self.cursor_position();
|
||||||
|
|
||||||
|
let new_idx = self
|
||||||
|
.editor
|
||||||
|
.data_provider_mut()
|
||||||
|
.split_line_at(line_idx, col);
|
||||||
|
|
||||||
|
let _ = self.transition_to_field(new_idx);
|
||||||
|
self.move_line_start();
|
||||||
|
self.enter_edit_mode();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn backspace(&mut self) {
|
||||||
|
let col = self.cursor_position();
|
||||||
|
if col > 0 {
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
{
|
||||||
|
self.edited_this_frame = true;
|
||||||
|
}
|
||||||
|
let _ = self.delete_backward();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let line_idx = self.current_field();
|
||||||
|
if line_idx == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some((prev_idx, new_col)) =
|
||||||
|
self.editor.data_provider_mut().join_with_prev(line_idx)
|
||||||
|
{
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
{
|
||||||
|
self.edited_this_frame = true;
|
||||||
|
}
|
||||||
|
let _ = self.transition_to_field(prev_idx);
|
||||||
|
self.set_cursor_position(new_col);
|
||||||
|
self.enter_edit_mode();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn delete_forward_or_join(&mut self) {
|
||||||
|
let line_idx = self.current_field();
|
||||||
|
let line_len = self.current_text().chars().count();
|
||||||
|
let col = self.cursor_position();
|
||||||
|
|
||||||
|
if col < line_len {
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
{
|
||||||
|
self.edited_this_frame = true;
|
||||||
|
}
|
||||||
|
let _ = self.delete_forward();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(new_col) =
|
||||||
|
self.editor.data_provider_mut().join_with_next(line_idx)
|
||||||
|
{
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
{
|
||||||
|
self.edited_this_frame = true;
|
||||||
|
}
|
||||||
|
self.set_cursor_position(new_col);
|
||||||
|
self.enter_edit_mode();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn input(&mut self, key: KeyEvent) {
|
||||||
|
if key.kind != KeyEventKind::Press {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
match (key.code, key.modifiers) {
|
||||||
|
(KeyCode::Enter, _) => self.insert_newline(),
|
||||||
|
(KeyCode::Backspace, _) => self.backspace(),
|
||||||
|
(KeyCode::Delete, _) => self.delete_forward_or_join(),
|
||||||
|
|
||||||
|
(KeyCode::Left, _) => {
|
||||||
|
let _ = self.move_left();
|
||||||
|
}
|
||||||
|
(KeyCode::Right, _) => {
|
||||||
|
let _ = self.move_right();
|
||||||
|
}
|
||||||
|
(KeyCode::Up, _) => {
|
||||||
|
let _ = self.move_up();
|
||||||
|
}
|
||||||
|
(KeyCode::Down, _) => {
|
||||||
|
let _ = self.move_down();
|
||||||
|
}
|
||||||
|
|
||||||
|
(KeyCode::Home, _)
|
||||||
|
| (KeyCode::Char('a'), KeyModifiers::CONTROL) => {
|
||||||
|
self.move_line_start();
|
||||||
|
}
|
||||||
|
(KeyCode::End, _)
|
||||||
|
| (KeyCode::Char('e'), KeyModifiers::CONTROL) => {
|
||||||
|
self.move_line_end();
|
||||||
|
}
|
||||||
|
|
||||||
|
(KeyCode::Char('b'), KeyModifiers::ALT) => self.move_word_prev(),
|
||||||
|
(KeyCode::Char('f'), KeyModifiers::ALT) => self.move_word_next(),
|
||||||
|
(KeyCode::Char('e'), KeyModifiers::ALT) => self.move_word_end(),
|
||||||
|
|
||||||
|
(KeyCode::Char(c), m) if m.is_empty() => {
|
||||||
|
self.enter_edit_mode();
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
{
|
||||||
|
self.edited_this_frame = true;
|
||||||
|
}
|
||||||
|
let _ = self.insert_char(c);
|
||||||
|
}
|
||||||
|
|
||||||
|
(KeyCode::Tab, _) => {
|
||||||
|
self.enter_edit_mode();
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
{
|
||||||
|
self.edited_this_frame = true;
|
||||||
|
}
|
||||||
|
for _ in 0..4 {
|
||||||
|
let _ = self.insert_char(' ');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
fn visual_rows_before_line_and_intra_indented(
|
||||||
|
&self,
|
||||||
|
width: u16,
|
||||||
|
line_idx: usize,
|
||||||
|
) -> u16 {
|
||||||
|
let provider = self.editor.data_provider();
|
||||||
|
let mut acc: u16 = 0;
|
||||||
|
let indent = self.wrap_indent_cols;
|
||||||
|
|
||||||
|
for i in 0..line_idx {
|
||||||
|
let s = provider.field_value(i);
|
||||||
|
acc = acc.saturating_add(count_wrapped_rows_indented(s, width, indent));
|
||||||
|
}
|
||||||
|
acc
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
pub fn cursor(&self, area: Rect, block: Option<&Block<'_>>) -> (u16, u16) {
|
||||||
|
let inner = if let Some(b) = block { b.inner(area) } else { area };
|
||||||
|
let line_idx = self.current_field() as usize;
|
||||||
|
|
||||||
|
match self.overflow_mode {
|
||||||
|
TextOverflowMode::Wrap => {
|
||||||
|
let width = inner.width;
|
||||||
|
let y_top = inner.y;
|
||||||
|
let indent = self.wrap_indent_cols;
|
||||||
|
|
||||||
|
if width == 0 {
|
||||||
|
let prefix = self.visual_rows_before_line_and_intra_indented(1, line_idx);
|
||||||
|
let y = y_top.saturating_add(prefix.saturating_sub(self.scroll_y));
|
||||||
|
return (inner.x, y);
|
||||||
|
}
|
||||||
|
|
||||||
|
let prefix_rows =
|
||||||
|
self.visual_rows_before_line_and_intra_indented(width, line_idx);
|
||||||
|
let current_line = self.current_text();
|
||||||
|
let col_chars = self.display_cursor_position();
|
||||||
|
|
||||||
|
let (subrow, x_cols) = wrapped_rows_to_cursor_indented(
|
||||||
|
¤t_line,
|
||||||
|
width,
|
||||||
|
indent,
|
||||||
|
col_chars,
|
||||||
|
);
|
||||||
|
|
||||||
|
let caret_vis_row = prefix_rows.saturating_add(subrow);
|
||||||
|
let y = y_top.saturating_add(caret_vis_row.saturating_sub(self.scroll_y));
|
||||||
|
let x = inner.x.saturating_add(x_cols);
|
||||||
|
(x, y)
|
||||||
|
}
|
||||||
|
TextOverflowMode::Indicator { .. } => {
|
||||||
|
let y = inner.y + (line_idx as u16).saturating_sub(self.scroll_y);
|
||||||
|
let current_line = self.current_text();
|
||||||
|
let col = self.display_cursor_position();
|
||||||
|
|
||||||
|
let mut x_cols: u16 = 0;
|
||||||
|
let mut total_cols: u16 = 0;
|
||||||
|
for (i, ch) in current_line.chars().enumerate() {
|
||||||
|
let w = UnicodeWidthChar::width(ch).unwrap_or(0) as u16;
|
||||||
|
if i < col {
|
||||||
|
x_cols = x_cols.saturating_add(w);
|
||||||
|
}
|
||||||
|
total_cols = total_cols.saturating_add(w);
|
||||||
|
}
|
||||||
|
|
||||||
|
let left_cols = if self.h_scroll > 0 { 1 } else { 0 };
|
||||||
|
|
||||||
|
let mut x_off_visible = x_cols
|
||||||
|
.saturating_sub(self.h_scroll)
|
||||||
|
.saturating_add(left_cols);
|
||||||
|
|
||||||
|
let limit = inner.width.saturating_sub(1 + RIGHT_PAD);
|
||||||
|
|
||||||
|
if x_off_visible > limit {
|
||||||
|
x_off_visible = limit;
|
||||||
|
}
|
||||||
|
|
||||||
|
let x = inner.x.saturating_add(x_off_visible);
|
||||||
|
(x, y)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
pub(crate) fn ensure_visible(&mut self, area: Rect, block: Option<&Block<'_>>) {
|
||||||
|
let inner = if let Some(b) = block { b.inner(area) } else { area };
|
||||||
|
if inner.height == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
match self.overflow_mode {
|
||||||
|
TextOverflowMode::Indicator { .. } => {
|
||||||
|
let line_idx_u16 = self.current_field() as u16;
|
||||||
|
if line_idx_u16 < self.scroll_y {
|
||||||
|
self.scroll_y = line_idx_u16;
|
||||||
|
} else if line_idx_u16 >= self.scroll_y + inner.height {
|
||||||
|
self.scroll_y = line_idx_u16.saturating_sub(inner.height - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let width = inner.width;
|
||||||
|
if width == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let current_line = self.current_text();
|
||||||
|
let mut total_cols: u16 = 0;
|
||||||
|
for ch in current_line.chars() {
|
||||||
|
total_cols = total_cols
|
||||||
|
.saturating_add(UnicodeWidthChar::width(ch).unwrap_or(0) as u16);
|
||||||
|
}
|
||||||
|
if total_cols <= width {
|
||||||
|
self.h_scroll = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let col = self.display_cursor_position();
|
||||||
|
let mut cursor_cols: u16 = 0;
|
||||||
|
for (i, ch) in current_line.chars().enumerate() {
|
||||||
|
if i >= col {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
cursor_cols = cursor_cols
|
||||||
|
.saturating_add(UnicodeWidthChar::width(ch).unwrap_or(0) as u16);
|
||||||
|
}
|
||||||
|
|
||||||
|
let (target_h, _left_cols) =
|
||||||
|
compute_h_scroll_with_padding(cursor_cols, width);
|
||||||
|
|
||||||
|
if target_h > self.h_scroll {
|
||||||
|
self.h_scroll = target_h;
|
||||||
|
} else if cursor_cols < self.h_scroll {
|
||||||
|
self.h_scroll = cursor_cols;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TextOverflowMode::Wrap => {
|
||||||
|
let width = inner.width;
|
||||||
|
if width == 0 {
|
||||||
|
self.h_scroll = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let indent = self.wrap_indent_cols;
|
||||||
|
let line_idx = self.current_field() as usize;
|
||||||
|
|
||||||
|
let prefix_rows =
|
||||||
|
self.visual_rows_before_line_and_intra_indented(width, line_idx);
|
||||||
|
|
||||||
|
let current_line = self.current_text();
|
||||||
|
let col = self.display_cursor_position();
|
||||||
|
|
||||||
|
let (subrow, _x_cols) =
|
||||||
|
wrapped_rows_to_cursor_indented(¤t_line, width, indent, col);
|
||||||
|
|
||||||
|
let caret_vis_row = prefix_rows.saturating_add(subrow);
|
||||||
|
|
||||||
|
let top = self.scroll_y;
|
||||||
|
let height = inner.height;
|
||||||
|
|
||||||
|
if caret_vis_row < top {
|
||||||
|
self.scroll_y = caret_vis_row;
|
||||||
|
} else {
|
||||||
|
let bottom = top.saturating_add(height.saturating_sub(1));
|
||||||
|
if caret_vis_row > bottom {
|
||||||
|
let shift = caret_vis_row.saturating_sub(bottom);
|
||||||
|
self.scroll_y = top.saturating_add(shift);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.h_scroll = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
pub(crate) fn take_edited_flag(&mut self) -> bool {
|
||||||
|
let v = self.edited_this_frame;
|
||||||
|
self.edited_this_frame = false;
|
||||||
|
v
|
||||||
|
}
|
||||||
|
}
|
||||||
352
canvas/src/textarea/widget.rs
Normal file
352
canvas/src/textarea/widget.rs
Normal file
@@ -0,0 +1,352 @@
|
|||||||
|
// src/textarea/widget.rs
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
use ratatui::{
|
||||||
|
buffer::Buffer,
|
||||||
|
layout::{Alignment, Rect},
|
||||||
|
style::Style,
|
||||||
|
text::{Line, Span},
|
||||||
|
widgets::{
|
||||||
|
Block, BorderType, Borders, Paragraph, StatefulWidget, Widget,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
use crate::data_provider::DataProvider;
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
use crate::textarea::state::{
|
||||||
|
compute_h_scroll_with_padding,
|
||||||
|
count_wrapped_rows_indented,
|
||||||
|
TextAreaState,
|
||||||
|
TextOverflowMode,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
use unicode_width::UnicodeWidthChar;
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct TextArea<'a> {
|
||||||
|
pub(crate) block: Option<Block<'a>>,
|
||||||
|
pub(crate) style: Style,
|
||||||
|
pub(crate) border_type: BorderType,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
impl<'a> Default for TextArea<'a> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
block: Some(
|
||||||
|
Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.border_type(BorderType::Rounded),
|
||||||
|
),
|
||||||
|
style: Style::default(),
|
||||||
|
border_type: BorderType::Rounded,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
impl<'a> TextArea<'a> {
|
||||||
|
pub fn block(mut self, block: Block<'a>) -> Self {
|
||||||
|
self.block = Some(block);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn style(mut self, style: Style) -> Self {
|
||||||
|
self.style = style;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn border_type(mut self, ty: BorderType) -> Self {
|
||||||
|
self.border_type = ty;
|
||||||
|
if let Some(b) = &mut self.block {
|
||||||
|
*b = b.clone().border_type(ty);
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
fn display_width(s: &str) -> u16 {
|
||||||
|
s.chars()
|
||||||
|
.map(|c| UnicodeWidthChar::width(c).unwrap_or(0) as u16)
|
||||||
|
.sum()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
fn display_cols_up_to(s: &str, char_count: usize) -> u16 {
|
||||||
|
let mut cols: u16 = 0;
|
||||||
|
for (i, ch) in s.chars().enumerate() {
|
||||||
|
if i >= char_count {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
cols = cols.saturating_add(UnicodeWidthChar::width(ch).unwrap_or(0) as u16);
|
||||||
|
}
|
||||||
|
cols
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
fn slice_by_display_cols(s: &str, start_cols: u16, max_cols: u16) -> String {
|
||||||
|
if max_cols == 0 {
|
||||||
|
return String::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut current_cols: u16 = 0;
|
||||||
|
let mut output = String::new();
|
||||||
|
let mut taken: u16 = 0;
|
||||||
|
let mut started = false;
|
||||||
|
|
||||||
|
for ch in s.chars() {
|
||||||
|
let w = UnicodeWidthChar::width(ch).unwrap_or(0) as u16;
|
||||||
|
|
||||||
|
if !started {
|
||||||
|
if current_cols.saturating_add(w) <= start_cols {
|
||||||
|
current_cols = current_cols.saturating_add(w);
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
started = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if taken.saturating_add(w) > max_cols {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
output.push(ch);
|
||||||
|
taken = taken.saturating_add(w);
|
||||||
|
current_cols = current_cols.saturating_add(w);
|
||||||
|
}
|
||||||
|
|
||||||
|
output
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
fn clip_window_with_indicator_padded(
|
||||||
|
text: &str,
|
||||||
|
view_width: u16,
|
||||||
|
indicator: char,
|
||||||
|
start_cols: u16,
|
||||||
|
) -> Line<'static> {
|
||||||
|
if view_width == 0 {
|
||||||
|
return Line::from("");
|
||||||
|
}
|
||||||
|
|
||||||
|
let total = display_width(text);
|
||||||
|
|
||||||
|
// Left indicator if we scrolled
|
||||||
|
let show_left = start_cols > 0;
|
||||||
|
let left_cols: u16 = if show_left { 1 } else { 0 };
|
||||||
|
|
||||||
|
// Capacity for text if we also need a right indicator
|
||||||
|
let cap_with_right = view_width.saturating_sub(left_cols + 1);
|
||||||
|
|
||||||
|
// Do we still have content beyond this window?
|
||||||
|
let remaining = total.saturating_sub(start_cols);
|
||||||
|
let show_right = remaining > cap_with_right;
|
||||||
|
|
||||||
|
// Final capacity for visible text
|
||||||
|
let max_visible = if show_right {
|
||||||
|
cap_with_right
|
||||||
|
} else {
|
||||||
|
view_width.saturating_sub(left_cols)
|
||||||
|
};
|
||||||
|
|
||||||
|
let visible = slice_by_display_cols(text, start_cols, max_visible);
|
||||||
|
|
||||||
|
let mut spans: Vec<Span> = Vec::new();
|
||||||
|
if show_left {
|
||||||
|
spans.push(Span::raw(indicator.to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Visible text
|
||||||
|
spans.push(Span::raw(visible.clone()));
|
||||||
|
|
||||||
|
// Place $ flush-right
|
||||||
|
if show_right {
|
||||||
|
let used_cols = left_cols + display_width(&visible);
|
||||||
|
let right_pos = view_width.saturating_sub(1);
|
||||||
|
let filler = right_pos.saturating_sub(used_cols);
|
||||||
|
if filler > 0 {
|
||||||
|
spans.push(Span::raw(" ".repeat(filler as usize)));
|
||||||
|
}
|
||||||
|
spans.push(Span::raw(indicator.to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
Line::from(spans)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
fn wrap_segments_with_indent(
|
||||||
|
s: &str,
|
||||||
|
width: u16,
|
||||||
|
indent: u16,
|
||||||
|
) -> Vec<String> {
|
||||||
|
let mut segments: Vec<String> = Vec::new();
|
||||||
|
if width == 0 {
|
||||||
|
segments.push(String::new());
|
||||||
|
return segments;
|
||||||
|
}
|
||||||
|
|
||||||
|
let indent = indent.min(width.saturating_sub(1));
|
||||||
|
let cont_cap = width.saturating_sub(indent);
|
||||||
|
let indent_str = " ".repeat(indent as usize);
|
||||||
|
|
||||||
|
let mut buf = String::new();
|
||||||
|
let mut used: u16 = 0;
|
||||||
|
let mut first = true;
|
||||||
|
|
||||||
|
for ch in s.chars() {
|
||||||
|
let w = UnicodeWidthChar::width(ch).unwrap_or(0) as u16;
|
||||||
|
let cap = if first { width } else { cont_cap };
|
||||||
|
|
||||||
|
// Early-wrap: wrap before filling the last cell (and avoid empty segment)
|
||||||
|
if used > 0 && used.saturating_add(w) >= cap {
|
||||||
|
segments.push(buf);
|
||||||
|
buf = String::new();
|
||||||
|
used = 0;
|
||||||
|
first = false;
|
||||||
|
if indent > 0 {
|
||||||
|
buf.push_str(&indent_str);
|
||||||
|
used = indent;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buf.push(ch);
|
||||||
|
used = used.saturating_add(w);
|
||||||
|
}
|
||||||
|
|
||||||
|
segments.push(buf);
|
||||||
|
segments
|
||||||
|
}
|
||||||
|
|
||||||
|
// Map visual row offset to (logical line, intra segment)
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
fn resolve_start_line_and_intra_indented(
|
||||||
|
state: &TextAreaState,
|
||||||
|
inner: Rect,
|
||||||
|
) -> (usize, u16) {
|
||||||
|
let provider = state.editor.data_provider();
|
||||||
|
let total = provider.line_count();
|
||||||
|
|
||||||
|
if total == 0 {
|
||||||
|
return (0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let wrap = matches!(state.overflow_mode, TextOverflowMode::Wrap);
|
||||||
|
let width = inner.width;
|
||||||
|
let target_vis = state.scroll_y;
|
||||||
|
|
||||||
|
if !wrap {
|
||||||
|
let start = (target_vis as usize).min(total);
|
||||||
|
return (start, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let indent = state.wrap_indent_cols;
|
||||||
|
|
||||||
|
let mut acc: u16 = 0;
|
||||||
|
for i in 0..total {
|
||||||
|
let s = provider.field_value(i);
|
||||||
|
let rows = count_wrapped_rows_indented(s, width, indent);
|
||||||
|
if acc.saturating_add(rows) > target_vis {
|
||||||
|
let intra = target_vis.saturating_sub(acc);
|
||||||
|
return (i, intra);
|
||||||
|
}
|
||||||
|
acc = acc.saturating_add(rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
(total.saturating_sub(1), 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "gui")]
|
||||||
|
impl<'a> StatefulWidget for TextArea<'a> {
|
||||||
|
type State = TextAreaState;
|
||||||
|
|
||||||
|
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
|
||||||
|
state.ensure_visible(area, self.block.as_ref());
|
||||||
|
|
||||||
|
let inner = if let Some(b) = &self.block {
|
||||||
|
b.clone().render(area, buf);
|
||||||
|
b.inner(area)
|
||||||
|
} else {
|
||||||
|
area
|
||||||
|
};
|
||||||
|
|
||||||
|
let edited_now = state.take_edited_flag();
|
||||||
|
|
||||||
|
let wrap_mode = matches!(state.overflow_mode, TextOverflowMode::Wrap);
|
||||||
|
let provider = state.editor.data_provider();
|
||||||
|
let total = provider.line_count();
|
||||||
|
|
||||||
|
let (start, intra) = resolve_start_line_and_intra_indented(state, inner);
|
||||||
|
|
||||||
|
let mut display_lines: Vec<Line> = Vec::new();
|
||||||
|
|
||||||
|
if total == 0 || start >= total {
|
||||||
|
if let Some(ph) = &state.placeholder {
|
||||||
|
display_lines.push(Line::from(Span::raw(ph.clone())));
|
||||||
|
}
|
||||||
|
} else if wrap_mode {
|
||||||
|
// manual pre-wrap path (unchanged)
|
||||||
|
let mut rows_left = inner.height;
|
||||||
|
let indent = state.wrap_indent_cols;
|
||||||
|
let mut i = start;
|
||||||
|
while i < total && rows_left > 0 {
|
||||||
|
let s = provider.field_value(i);
|
||||||
|
let segments = wrap_segments_with_indent(s, inner.width, indent);
|
||||||
|
let skip = if i == start { intra as usize } else { 0 };
|
||||||
|
for seg in segments.into_iter().skip(skip) {
|
||||||
|
display_lines.push(Line::from(Span::raw(seg)));
|
||||||
|
rows_left = rows_left.saturating_sub(1);
|
||||||
|
if rows_left == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Indicator mode: full inner width; RIGHT_PAD only affects cursor clamp and h-scroll
|
||||||
|
let end = (start.saturating_add(inner.height as usize)).min(total);
|
||||||
|
|
||||||
|
for i in start..end {
|
||||||
|
let s = provider.field_value(i);
|
||||||
|
match state.overflow_mode {
|
||||||
|
TextOverflowMode::Wrap => unreachable!(),
|
||||||
|
TextOverflowMode::Indicator { ch } => {
|
||||||
|
let fits = display_width(&s) <= inner.width;
|
||||||
|
|
||||||
|
let start_cols = if i == state.current_field() {
|
||||||
|
let col_idx = state.display_cursor_position();
|
||||||
|
let cursor_cols = display_cols_up_to(&s, col_idx);
|
||||||
|
let (target_h, _left_cols) =
|
||||||
|
compute_h_scroll_with_padding(cursor_cols, inner.width);
|
||||||
|
|
||||||
|
if fits {
|
||||||
|
if edited_now { target_h } else { 0 }
|
||||||
|
} else {
|
||||||
|
target_h.max(state.h_scroll)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
|
||||||
|
display_lines.push(clip_window_with_indicator_padded(
|
||||||
|
&s,
|
||||||
|
inner.width,
|
||||||
|
ch,
|
||||||
|
start_cols,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let p = Paragraph::new(display_lines)
|
||||||
|
.alignment(Alignment::Left)
|
||||||
|
.style(self.style);
|
||||||
|
|
||||||
|
// No Paragraph::wrap/scroll in wrap mode — we pre-wrap.
|
||||||
|
p.render(inner, buf);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user