use crate::reactive::Signal;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputKey {
Char(char),
Left,
Right,
Up,
Down,
Home,
End,
Backspace,
Delete,
Enter,
Escape,
A,
C,
V,
X,
Z,
Y,
Other,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct InputModifiers {
pub shift: bool,
pub ctrl: bool,
pub alt: bool,
pub meta: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InputKeyResult {
Ignored,
Handled,
CopyToClipboard(String),
Submitted,
}
#[derive(Clone)]
pub struct TextInputState {
pub text: Signal<String>,
pub cursor_index: Signal<usize>,
pub selection_anchor: Signal<Option<usize>>,
pub is_focused: Signal<bool>,
pub scroll_x: std::cell::Cell<f32>,
pub scroll_y: std::cell::Cell<f32>,
undo_stack: Vec<(String, usize)>,
redo_stack: Vec<(String, usize)>,
}
impl TextInputState {
pub fn new() -> Self {
Self::with_text("")
}
pub fn with_text(initial: &str) -> Self {
let text = Signal::new(initial.to_string());
let cursor_index = Signal::new(initial.chars().count());
let selection_anchor = Signal::new(None);
let is_focused = Signal::new(false);
Self {
text,
cursor_index,
selection_anchor,
is_focused,
scroll_x: std::cell::Cell::new(0.0),
scroll_y: std::cell::Cell::new(0.0),
undo_stack: Vec::new(),
redo_stack: Vec::new(),
}
}
pub fn selection_range(&self) -> Option<(usize, usize)> {
if let Some(anchor) = self.selection_anchor.get() {
let cursor = self.cursor_index.get();
if anchor != cursor {
return Some((anchor.min(cursor), anchor.max(cursor)));
}
}
None
}
pub fn has_selection(&self) -> bool {
self.selection_range().is_some()
}
pub fn selected_text(&self) -> Option<String> {
self.selection_range().map(|(start, end)| {
let text = self.text.get();
text.chars().skip(start).take(end - start).collect()
})
}
pub fn select_all(&self) {
let total_chars = self.text.get().chars().count();
self.selection_anchor.set(Some(0));
self.cursor_index.set(total_chars);
}
pub fn clear_selection(&self) {
self.selection_anchor.set(None);
}
pub fn start_selection(&self, index: usize) {
let total = self.text.get().chars().count();
let clamped = index.min(total);
self.selection_anchor.set(Some(clamped));
self.cursor_index.set(clamped);
}
pub fn update_selection_drag(&self, index: usize) {
let total = self.text.get().chars().count();
let clamped = index.min(total);
if self.selection_anchor.get().is_none() {
self.selection_anchor.set(Some(self.cursor_index.get()));
}
self.cursor_index.set(clamped);
}
pub fn select_word_at_index(&self, index: usize) {
let cur_text = self.text.get();
let chars: Vec<char> = cur_text.chars().collect();
let len = chars.len();
if len == 0 {
return;
}
let clamped = index.min(len.saturating_sub(1));
let is_word = is_word_char(chars[clamped]);
let mut start = clamped;
while start > 0 {
let prev = chars[start - 1];
if prev.is_whitespace() || (is_word != is_word_char(prev)) {
break;
}
start -= 1;
}
let mut end = clamped;
while end < len {
let ch = chars[end];
if ch.is_whitespace() || (is_word != is_word_char(ch)) {
break;
}
end += 1;
}
self.selection_anchor.set(Some(start));
self.cursor_index.set(end);
}
pub fn select_line_at_index(&self, index: usize) {
let cur_text = self.text.get();
let chars: Vec<char> = cur_text.chars().collect();
let len = chars.len();
let clamped = index.min(len);
let mut start = clamped;
while start > 0 && chars[start - 1] != '\n' {
start -= 1;
}
let mut end = clamped;
while end < len && chars[end] != '\n' {
end += 1;
}
self.selection_anchor.set(Some(start));
self.cursor_index.set(end);
}
pub fn calculate_char_index_at_offset(text: &str, x_offset: f32, font_size: f32) -> usize {
if x_offset <= 0.0 || text.is_empty() {
return 0;
}
let char_w = font_size * 0.55;
let approx_idx = (x_offset / char_w).round() as usize;
approx_idx.min(text.chars().count())
}
pub fn replace_all_text(&mut self, new_text: &str) {
self.push_undo_snapshot();
self.text.set(new_text.to_string());
self.cursor_index.set(new_text.chars().count());
self.selection_anchor.set(None);
}
pub fn sync_external_text(&mut self, new_text: &str) {
if self.text.get() != new_text {
self.push_undo_snapshot();
self.text.set(new_text.to_string());
let count = new_text.chars().count();
if self.cursor_index.get() > count {
self.cursor_index.set(count);
}
self.selection_anchor.set(None);
}
}
pub fn set_text(&mut self, new_text: &str) {
self.undo_stack.clear();
self.redo_stack.clear();
self.text.set(new_text.to_string());
self.cursor_index.set(new_text.chars().count());
self.selection_anchor.set(None);
}
pub fn insert_text(&mut self, inserted: &str) {
self.push_undo_snapshot();
let cur_text = self.text.get();
let chars: Vec<char> = cur_text.chars().collect();
if let Some((start, end)) = self.selection_range() {
let mut new_chars = Vec::with_capacity(chars.len() + inserted.len());
new_chars.extend_from_slice(&chars[..start]);
new_chars.extend(inserted.chars());
new_chars.extend_from_slice(&chars[end..]);
let new_cursor = start + inserted.chars().count();
self.text.set(new_chars.into_iter().collect());
self.cursor_index.set(new_cursor);
self.selection_anchor.set(None);
} else {
let cursor = self.cursor_index.get().min(chars.len());
let mut new_chars = Vec::with_capacity(chars.len() + inserted.len());
new_chars.extend_from_slice(&chars[..cursor]);
new_chars.extend(inserted.chars());
new_chars.extend_from_slice(&chars[cursor..]);
let new_cursor = cursor + inserted.chars().count();
self.text.set(new_chars.into_iter().collect());
self.cursor_index.set(new_cursor);
self.selection_anchor.set(None);
}
}
pub fn delete_backward(&mut self) {
if self.has_selection() {
self.delete_selection();
return;
}
let cursor = self.cursor_index.get();
if cursor == 0 {
return;
}
self.push_undo_snapshot();
let cur_text = self.text.get();
let mut chars: Vec<char> = cur_text.chars().collect();
if cursor <= chars.len() {
chars.remove(cursor - 1);
self.cursor_index.set(cursor - 1);
self.text.set(chars.into_iter().collect());
}
}
pub fn delete_forward(&mut self) {
if self.has_selection() {
self.delete_selection();
return;
}
let cursor = self.cursor_index.get();
let cur_text = self.text.get();
let mut chars: Vec<char> = cur_text.chars().collect();
if cursor < chars.len() {
self.push_undo_snapshot();
chars.remove(cursor);
self.text.set(chars.into_iter().collect());
}
}
pub fn delete_word_backward(&mut self) {
if self.has_selection() {
self.delete_selection();
return;
}
let cursor = self.cursor_index.get();
if cursor == 0 {
return;
}
let cur_text = self.text.get();
let chars: Vec<char> = cur_text.chars().collect();
let prev_boundary = find_prev_word_boundary(&chars, cursor);
self.push_undo_snapshot();
let mut new_chars = Vec::with_capacity(chars.len());
new_chars.extend_from_slice(&chars[..prev_boundary]);
new_chars.extend_from_slice(&chars[cursor..]);
self.cursor_index.set(prev_boundary);
self.text.set(new_chars.into_iter().collect());
}
pub fn delete_word_forward(&mut self) {
if self.has_selection() {
self.delete_selection();
return;
}
let cursor = self.cursor_index.get();
let cur_text = self.text.get();
let chars: Vec<char> = cur_text.chars().collect();
if cursor >= chars.len() {
return;
}
let next_boundary = find_next_word_boundary(&chars, cursor);
self.push_undo_snapshot();
let mut new_chars = Vec::with_capacity(chars.len());
new_chars.extend_from_slice(&chars[..cursor]);
new_chars.extend_from_slice(&chars[next_boundary..]);
self.text.set(new_chars.into_iter().collect());
}
pub fn delete_selection(&mut self) {
if let Some((start, end)) = self.selection_range() {
self.push_undo_snapshot();
let cur_text = self.text.get();
let chars: Vec<char> = cur_text.chars().collect();
let mut new_chars = Vec::with_capacity(chars.len());
new_chars.extend_from_slice(&chars[..start]);
new_chars.extend_from_slice(&chars[end..]);
self.text.set(new_chars.into_iter().collect());
self.cursor_index.set(start);
self.selection_anchor.set(None);
}
}
pub fn move_left(&self, extend_selection: bool, by_word: bool) {
let cur_text = self.text.get();
let chars: Vec<char> = cur_text.chars().collect();
let cursor = self.cursor_index.get();
if !extend_selection && self.has_selection() {
if let Some((start, _)) = self.selection_range() {
self.selection_anchor.set(None);
self.cursor_index.set(start);
return;
}
}
let new_cursor = if by_word {
find_prev_word_boundary(&chars, cursor)
} else {
cursor.saturating_sub(1)
};
if extend_selection {
if self.selection_anchor.get().is_none() {
self.selection_anchor.set(Some(cursor));
}
} else {
self.selection_anchor.set(None);
}
self.cursor_index.set(new_cursor);
}
pub fn move_right(&self, extend_selection: bool, by_word: bool) {
let cur_text = self.text.get();
let chars: Vec<char> = cur_text.chars().collect();
let cursor = self.cursor_index.get();
if !extend_selection && self.has_selection() {
if let Some((_, end)) = self.selection_range() {
self.selection_anchor.set(None);
self.cursor_index.set(end);
return;
}
}
let new_cursor = if by_word {
find_next_word_boundary(&chars, cursor)
} else {
(cursor + 1).min(chars.len())
};
if extend_selection {
if self.selection_anchor.get().is_none() {
self.selection_anchor.set(Some(cursor));
}
} else {
self.selection_anchor.set(None);
}
self.cursor_index.set(new_cursor);
}
pub fn move_home(&self, extend_selection: bool) {
let cursor = self.cursor_index.get();
if extend_selection {
if self.selection_anchor.get().is_none() {
self.selection_anchor.set(Some(cursor));
}
} else {
self.selection_anchor.set(None);
}
self.cursor_index.set(0);
}
pub fn move_end(&self, extend_selection: bool) {
let total = self.text.get().chars().count();
self.set_cursor_with_selection(total, extend_selection);
}
fn set_cursor_with_selection(&self, new_cursor: usize, extend_selection: bool) {
let cursor = self.cursor_index.get();
if extend_selection {
if self.selection_anchor.get().is_none() {
self.selection_anchor.set(Some(cursor));
}
} else {
self.selection_anchor.set(None);
}
self.cursor_index.set(new_cursor);
}
pub fn line_col_at_index(text: &str, char_idx: usize) -> (usize, usize) {
let mut line = 0usize;
let mut col = 0usize;
for (idx, ch) in text.chars().enumerate() {
if idx >= char_idx {
break;
}
if ch == '\n' {
line += 1;
col = 0;
} else {
col += 1;
}
}
(line, col)
}
pub fn index_from_line_col(text: &str, target_line: usize, target_col: usize) -> usize {
let mut cur_line = 0usize;
let mut cur_col = 0usize;
for (idx, ch) in text.chars().enumerate() {
if cur_line == target_line && (ch == '\n' || cur_col >= target_col) {
return idx;
}
if ch == '\n' {
cur_line += 1;
cur_col = 0;
} else if cur_line == target_line {
cur_col += 1;
}
}
text.chars().count()
}
pub fn move_line_home(&self, extend_selection: bool) {
let text = self.text.get();
let (line, _) = Self::line_col_at_index(&text, self.cursor_index.get());
let target = Self::index_from_line_col(&text, line, 0);
self.set_cursor_with_selection(target, extend_selection);
}
pub fn move_line_end(&self, extend_selection: bool) {
let text = self.text.get();
let (line, _) = Self::line_col_at_index(&text, self.cursor_index.get());
let target = Self::index_from_line_col(&text, line, usize::MAX);
self.set_cursor_with_selection(target, extend_selection);
}
pub fn move_up(&self, extend_selection: bool) {
let text = self.text.get();
let cursor = self.cursor_index.get();
if !extend_selection && self.has_selection() {
if let Some((start, _)) = self.selection_range() {
self.selection_anchor.set(None);
self.cursor_index.set(start);
return;
}
}
let (line, col) = Self::line_col_at_index(&text, cursor);
let target = if line == 0 {
0
} else {
Self::index_from_line_col(&text, line - 1, col)
};
self.set_cursor_with_selection(target, extend_selection);
}
pub fn move_down(&self, extend_selection: bool) {
let text = self.text.get();
let cursor = self.cursor_index.get();
if !extend_selection && self.has_selection() {
if let Some((_, end)) = self.selection_range() {
self.selection_anchor.set(None);
self.cursor_index.set(end);
return;
}
}
let total = text.chars().count();
let (line, col) = Self::line_col_at_index(&text, cursor);
let line_count = text.chars().filter(|&c| c == '\n').count() + 1;
let target = if line + 1 >= line_count {
total
} else {
Self::index_from_line_col(&text, line + 1, col)
};
self.set_cursor_with_selection(target, extend_selection);
}
fn push_undo_snapshot(&mut self) {
self.undo_stack
.push((self.text.get(), self.cursor_index.get()));
if self.undo_stack.len() > 100 {
self.undo_stack.remove(0);
}
self.redo_stack.clear();
}
pub fn undo(&mut self) -> bool {
if let Some((prev_text, prev_cursor)) = self.undo_stack.pop() {
self.redo_stack
.push((self.text.get(), self.cursor_index.get()));
self.text.set(prev_text);
self.cursor_index.set(prev_cursor);
self.selection_anchor.set(None);
true
} else {
false
}
}
pub fn redo(&mut self) -> bool {
if let Some((next_text, next_cursor)) = self.redo_stack.pop() {
self.undo_stack
.push((self.text.get(), self.cursor_index.get()));
self.text.set(next_text);
self.cursor_index.set(next_cursor);
self.selection_anchor.set(None);
true
} else {
false
}
}
pub fn handle_key(
&mut self,
key: InputKey,
modifiers: InputModifiers,
clipboard_content: Option<&str>,
) -> InputKeyResult {
self.handle_key_with_mode(key, modifiers, clipboard_content, false)
}
pub fn handle_key_with_mode(
&mut self,
key: InputKey,
modifiers: InputModifiers,
clipboard_content: Option<&str>,
multiline: bool,
) -> InputKeyResult {
if modifiers.ctrl {
match key {
InputKey::A => {
self.select_all();
return InputKeyResult::Handled;
}
InputKey::C => {
if let Some(sel) = self.selected_text() {
return InputKeyResult::CopyToClipboard(sel);
}
return InputKeyResult::Ignored;
}
InputKey::X => {
if let Some(sel) = self.selected_text() {
self.delete_selection();
return InputKeyResult::CopyToClipboard(sel);
}
return InputKeyResult::Ignored;
}
InputKey::V => {
if let Some(clip) = clipboard_content {
self.insert_text(clip);
return InputKeyResult::Handled;
}
return InputKeyResult::Ignored;
}
InputKey::Z => {
if modifiers.shift {
if self.redo() {
return InputKeyResult::Handled;
}
} else if self.undo() {
return InputKeyResult::Handled;
}
return InputKeyResult::Ignored;
}
InputKey::Y => {
if self.redo() {
return InputKeyResult::Handled;
}
return InputKeyResult::Ignored;
}
InputKey::Left => {
self.move_left(modifiers.shift, true);
return InputKeyResult::Handled;
}
InputKey::Right => {
self.move_right(modifiers.shift, true);
return InputKeyResult::Handled;
}
InputKey::Home => {
self.move_home(modifiers.shift);
return InputKeyResult::Handled;
}
InputKey::End => {
self.move_end(modifiers.shift);
return InputKeyResult::Handled;
}
InputKey::Backspace => {
self.delete_word_backward();
return InputKeyResult::Handled;
}
InputKey::Delete => {
self.delete_word_forward();
return InputKeyResult::Handled;
}
InputKey::Enter if multiline => {
return InputKeyResult::Submitted;
}
_ => {}
}
}
match key {
InputKey::Left => {
self.move_left(modifiers.shift, false);
InputKeyResult::Handled
}
InputKey::Right => {
self.move_right(modifiers.shift, false);
InputKeyResult::Handled
}
InputKey::Up if multiline => {
self.move_up(modifiers.shift);
InputKeyResult::Handled
}
InputKey::Down if multiline => {
self.move_down(modifiers.shift);
InputKeyResult::Handled
}
InputKey::Home => {
if multiline {
self.move_line_home(modifiers.shift);
} else {
self.move_home(modifiers.shift);
}
InputKeyResult::Handled
}
InputKey::End => {
if multiline {
self.move_line_end(modifiers.shift);
} else {
self.move_end(modifiers.shift);
}
InputKeyResult::Handled
}
InputKey::Backspace => {
self.delete_backward();
InputKeyResult::Handled
}
InputKey::Delete => {
self.delete_forward();
InputKeyResult::Handled
}
InputKey::Enter => {
if multiline {
self.insert_text("\n");
InputKeyResult::Handled
} else {
InputKeyResult::Submitted
}
}
InputKey::Escape => {
self.clear_selection();
InputKeyResult::Handled
}
InputKey::Char(c) => {
let mut buf = [0u8; 4];
self.insert_text(c.encode_utf8(&mut buf));
InputKeyResult::Handled
}
_ => InputKeyResult::Ignored,
}
}
}
impl Default for TextInputState {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for TextInputState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TextInputState")
.field("text", &self.text.get())
.field("cursor_index", &self.cursor_index.get())
.field("selection_anchor", &self.selection_anchor.get())
.field("undo_count", &self.undo_stack.len())
.field("redo_count", &self.redo_stack.len())
.finish()
}
}
#[inline]
fn is_word_char(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
fn find_prev_word_boundary(chars: &[char], cursor: usize) -> usize {
if cursor == 0 {
return 0;
}
let mut idx = cursor;
while idx > 0 && chars[idx - 1].is_whitespace() {
idx -= 1;
}
if idx == 0 {
return 0;
}
if is_word_char(chars[idx - 1]) {
while idx > 0 && is_word_char(chars[idx - 1]) {
idx -= 1;
}
} else {
while idx > 0 && !is_word_char(chars[idx - 1]) && !chars[idx - 1].is_whitespace() {
idx -= 1;
}
}
idx
}
fn find_next_word_boundary(chars: &[char], cursor: usize) -> usize {
let len = chars.len();
if cursor >= len {
return len;
}
let mut idx = cursor;
while idx < len && chars[idx].is_whitespace() {
idx += 1;
}
if idx >= len {
return len;
}
if is_word_char(chars[idx]) {
while idx < len && is_word_char(chars[idx]) {
idx += 1;
}
} else {
while idx < len && !is_word_char(chars[idx]) && !chars[idx].is_whitespace() {
idx += 1;
}
}
idx
}