use tui_textarea::TextArea;
pub struct WrapConfig {
pub wrap_width: usize,
}
impl WrapConfig {
pub const COMPOSER: Self = Self { wrap_width: 100 };
pub const DM_PANEL: Self = Self { wrap_width: 110 };
}
pub fn wrap_textarea_if_needed(textarea: &mut TextArea<'static>, config: WrapConfig) {
let (row, col) = textarea.cursor();
let lines: Vec<String> = textarea.lines().to_vec();
if row >= lines.len() {
return;
}
let current_line = &lines[row];
let char_count = current_line.chars().count();
if char_count <= config.wrap_width {
return;
}
let chars: Vec<char> = current_line.chars().collect();
let mut wrap_point = config.wrap_width;
for i in (0..config.wrap_width.min(chars.len())).rev() {
if chars[i] == ' ' {
wrap_point = i;
break;
}
}
let first_part: String = chars[..wrap_point].iter().collect();
let second_part: String = chars[wrap_point..].iter().collect();
let first_part = first_part.trim_end();
let second_part = second_part.trim_start();
let mut new_lines = Vec::new();
for (i, line) in lines.iter().enumerate() {
if i == row {
new_lines.push(first_part.to_string());
new_lines.push(second_part.to_string());
} else {
new_lines.push(line.clone());
}
}
*textarea = TextArea::from(new_lines.iter().map(|s| s.as_str()));
textarea.set_hard_tab_indent(true);
let new_col = if col > wrap_point {
col - wrap_point - 1
} else {
second_part.chars().count()
};
textarea.move_cursor(tui_textarea::CursorMove::Jump(row as u16 + 1, new_col as u16));
}