use crate::capabilities::foundation::theme::use_theme;
use gpui::{prelude::*, *};
use std::ops::Range;
use crate::capabilities::controls::text_util;
use crate::capabilities::controls::validation;
pub use crate::capabilities::controls::validation::{ValidationError, ValidationRules};
use crate::capabilities::foundation::edit;
pub fn init(cx: &mut App) {
if !crate::capabilities::foundation::initialization::begin(cx, "textarea-state") {
return;
}
cx.bind_keys([
KeyBinding::new("backspace", Backspace, Some("Textarea")),
KeyBinding::new("delete", Delete, Some("Textarea")),
KeyBinding::new("left", Left, Some("Textarea")),
KeyBinding::new("right", Right, Some("Textarea")),
KeyBinding::new("up", Up, Some("Textarea")),
KeyBinding::new("down", Down, Some("Textarea")),
KeyBinding::new("shift-left", SelectLeft, Some("Textarea")),
KeyBinding::new("shift-right", SelectRight, Some("Textarea")),
KeyBinding::new("shift-up", SelectUp, Some("Textarea")),
KeyBinding::new("shift-down", SelectDown, Some("Textarea")),
KeyBinding::new("home", Home, Some("Textarea")),
KeyBinding::new("end", End, Some("Textarea")),
KeyBinding::new("enter", Enter, Some("Textarea")),
KeyBinding::new("shift-enter", ShiftEnter, Some("Textarea")),
KeyBinding::new("tab", Tab, Some("Textarea")),
KeyBinding::new("shift-tab", ShiftTab, Some("Textarea")),
#[cfg(target_os = "macos")]
KeyBinding::new("cmd-a", SelectAll, Some("Textarea")),
#[cfg(not(target_os = "macos"))]
KeyBinding::new("ctrl-a", SelectAll, Some("Textarea")),
#[cfg(target_os = "macos")]
KeyBinding::new("cmd-c", Copy, Some("Textarea")),
#[cfg(not(target_os = "macos"))]
KeyBinding::new("ctrl-c", Copy, Some("Textarea")),
#[cfg(target_os = "macos")]
KeyBinding::new("cmd-x", Cut, Some("Textarea")),
#[cfg(not(target_os = "macos"))]
KeyBinding::new("ctrl-x", Cut, Some("Textarea")),
#[cfg(target_os = "macos")]
KeyBinding::new("cmd-v", Paste, Some("Textarea")),
#[cfg(not(target_os = "macos"))]
KeyBinding::new("ctrl-v", Paste, Some("Textarea")),
KeyBinding::new("escape", Escape, Some("Textarea")),
#[cfg(target_os = "macos")]
KeyBinding::new("alt-left", WordLeft, Some("Textarea")),
#[cfg(target_os = "macos")]
KeyBinding::new("alt-right", WordRight, Some("Textarea")),
#[cfg(not(target_os = "macos"))]
KeyBinding::new("ctrl-left", WordLeft, Some("Textarea")),
#[cfg(not(target_os = "macos"))]
KeyBinding::new("ctrl-right", WordRight, Some("Textarea")),
#[cfg(target_os = "macos")]
KeyBinding::new("alt-shift-left", SelectWordLeft, Some("Textarea")),
#[cfg(target_os = "macos")]
KeyBinding::new("alt-shift-right", SelectWordRight, Some("Textarea")),
#[cfg(not(target_os = "macos"))]
KeyBinding::new("ctrl-shift-left", SelectWordLeft, Some("Textarea")),
#[cfg(not(target_os = "macos"))]
KeyBinding::new("ctrl-shift-right", SelectWordRight, Some("Textarea")),
]);
}
actions!(
textarea_state,
[
Backspace,
Delete,
Left,
Right,
Up,
Down,
SelectLeft,
SelectRight,
SelectUp,
SelectDown,
SelectAll,
Home,
End,
Copy,
Cut,
Paste,
Enter,
ShiftEnter,
Tab,
ShiftTab,
Escape,
WordLeft,
WordRight,
SelectWordLeft,
SelectWordRight,
]
);
#[derive(Clone, Debug)]
pub enum TextareaEvent {
Change,
Focus,
Blur,
Enter,
ShiftEnter,
Tab,
ShiftTab,
Validate(Result<(), ValidationError>),
}
impl EventEmitter<TextareaEvent> for TextareaState {}
pub struct TextareaState {
focus_handle: FocusHandle,
pub scroll_handle: ScrollHandle,
pub content: SharedString,
pub placeholder: SharedString,
pub disabled: bool,
pub initialized: bool,
selected_range: Range<usize>,
selection_reversed: bool,
marked_range: Option<Range<usize>>,
last_layouts: Vec<WrappedLine>,
last_bounds: Option<Bounds<Pixels>>,
last_visual_line_count: usize,
last_line_height: Pixels,
is_selecting: bool,
was_focused: bool,
cursor_visible: bool,
_blink_task: Option<Task<()>>,
event_subscription: Option<Subscription>,
pub validation_rules: ValidationRules,
pub validation_error: Option<ValidationError>,
pub success_message: Option<SharedString>,
pub validate_on_blur: bool,
pub validate_on_change: bool,
}
#[derive(Clone, Copy)]
struct VisualLineInfo {
logical_line_idx: usize,
logical_start: usize,
local_start: usize,
local_end: usize,
origin_y: Pixels,
}
impl TextareaState {
pub fn new(cx: &mut Context<Self>) -> Self {
Self {
focus_handle: cx.focus_handle(),
scroll_handle: ScrollHandle::new(),
content: "".into(),
placeholder: "".into(),
disabled: false,
initialized: false,
selected_range: 0..0,
selection_reversed: false,
marked_range: None,
last_layouts: Vec::new(),
last_bounds: None,
last_visual_line_count: 1,
last_line_height: px(20.0),
is_selecting: false,
was_focused: false,
cursor_visible: true,
_blink_task: None,
event_subscription: None,
validation_rules: ValidationRules::default(),
validation_error: None,
success_message: None,
validate_on_blur: true,
validate_on_change: false,
}
}
pub(super) fn replace_event_subscription(&mut self, subscription: Option<Subscription>) {
self.event_subscription = subscription;
}
pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
self.placeholder = placeholder.into();
self
}
pub fn value(mut self, value: impl Into<SharedString>) -> Self {
self.content = value.into();
let len = self.content.len();
self.selected_range = len..len;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn content(&self) -> &str {
&self.content
}
pub fn visual_line_count_for_layout(&self) -> usize {
self.visual_line_count()
}
pub fn set_value(
&mut self,
value: impl Into<SharedString>,
_window: &mut Window,
cx: &mut Context<Self>,
) {
let value = self.truncate_to_max_length(value.into());
if self.content != value {
self.content = value;
let len = self.content.len();
self.selected_range = len..len;
self.marked_range.take();
self.selection_reversed = false;
self.invalidate_layout_cache();
if self.should_auto_validate(self.validate_on_change) {
self.validate(cx).ok();
}
cx.emit(TextareaEvent::Change);
cx.notify();
}
}
pub fn is_composing(&self) -> bool {
self.marked_range.is_some()
}
pub fn composition_char_count(&self) -> usize {
self.marked_range
.as_ref()
.and_then(|range| self.content.get(range.clone()))
.map(|marked| marked.chars().count())
.unwrap_or(0)
}
pub fn validation_rules(mut self, rules: ValidationRules) -> Self {
self.validation_rules = rules;
self
}
pub fn min_length(mut self, min: usize) -> Self {
self.validation_rules.min_length = Some(min);
self
}
pub fn max_length(mut self, max: usize) -> Self {
self.validation_rules.max_length = Some(max);
self
}
pub fn required(mut self, required: bool) -> Self {
self.validation_rules.required = required;
self
}
fn truncate_to_max_length(&self, value: SharedString) -> SharedString {
self.validation_rules
.max_length
.map(|max_length| value.chars().take(max_length).collect::<String>().into())
.unwrap_or(value)
}
fn should_auto_validate(&self, enabled: bool) -> bool {
let rules = &self.validation_rules;
enabled
&& (rules.required
|| rules.min_length.is_some()
|| rules.max_length.is_some()
|| rules.pattern.is_some()
|| rules.custom_validator.is_some())
}
pub fn validate(&mut self, cx: &mut Context<Self>) -> Result<(), ValidationError> {
let value = self.committed_content();
if let Some(result) =
validation::check_required_empty(self.validation_rules.required, &value, None)
{
if result.is_ok() {
self.validation_error = None;
self.success_message = None;
cx.emit(TextareaEvent::Validate(Ok(())));
cx.notify();
return Ok(());
}
return self.finish_validation(result, cx);
}
let result = validation::check_constraints(&self.validation_rules, &value, None);
self.finish_validation(result, cx)
}
fn finish_validation(
&mut self,
result: Result<(), ValidationError>,
cx: &mut Context<Self>,
) -> Result<(), ValidationError> {
match &result {
Ok(()) => {
self.validation_error = None;
self.success_message = Some("Valid input".into());
}
Err(error) => {
self.validation_error = Some(error.clone());
}
}
cx.emit(TextareaEvent::Validate(result.clone()));
cx.notify();
result
}
fn committed_content(&self) -> String {
let Some(range) = self.marked_range.as_ref() else {
return self.content.to_string();
};
let Some(_) = self.content.get(range.clone()) else {
return self.content.to_string();
};
let mut committed = self.content.to_string();
committed.replace_range(range.clone(), "");
committed
}
fn line_start_offsets(&self) -> Vec<usize> {
let mut offsets = vec![0usize];
for (i, ch) in self.content.char_indices() {
if ch == '\n' {
offsets.push(i + ch.len_utf8());
}
}
offsets
}
fn logical_line_for_offset(&self, offset: usize) -> usize {
let starts = self.line_start_offsets();
let mut line = 0;
for (i, &start) in starts.iter().enumerate() {
if start <= offset {
line = i;
} else {
break;
}
}
line
}
fn line_start_for_offset(&self, offset: usize) -> usize {
let starts = self.line_start_offsets();
let line = self.logical_line_for_offset(offset);
starts[line]
}
fn line_end_for_offset(&self, offset: usize) -> usize {
let starts = self.line_start_offsets();
let line = self.logical_line_for_offset(offset);
if line + 1 < starts.len() {
starts[line + 1] - 1
} else {
self.content.len()
}
}
fn visual_line_count(&self) -> usize {
self.last_visual_line_count.max(1)
}
fn lines(&self) -> Vec<&str> {
if self.content.is_empty() {
return vec![""];
}
let s: &str = &self.content;
let mut result: Vec<&str> = s.split('\n').collect();
if result.is_empty() {
result.push("");
}
result
}
fn visual_lines_for_layouts(
&self,
layouts: &[WrappedLine],
line_height: Pixels,
) -> Vec<VisualLineInfo> {
let starts = self.line_start_offsets();
let mut visual_lines = Vec::new();
let mut current_y = Pixels::ZERO;
for (logical_line_idx, wrapped_line) in layouts.iter().enumerate() {
let logical_start = starts.get(logical_line_idx).copied().unwrap_or(0);
let mut local_start = 0;
let mut visual_line_idx = 0;
for wrap_boundary in wrapped_line.wrap_boundaries() {
let glyph =
&wrapped_line.runs()[wrap_boundary.run_ix].glyphs[wrap_boundary.glyph_ix];
let local_end = glyph.index;
visual_lines.push(VisualLineInfo {
logical_line_idx,
logical_start,
local_start,
local_end,
origin_y: current_y + line_height * visual_line_idx as f32,
});
local_start = local_end;
visual_line_idx += 1;
}
visual_lines.push(VisualLineInfo {
logical_line_idx,
logical_start,
local_start,
local_end: wrapped_line.text.len(),
origin_y: current_y + line_height * visual_line_idx as f32,
});
current_y += line_height * (visual_line_idx + 1) as f32;
}
if visual_lines.is_empty() {
visual_lines.push(VisualLineInfo {
logical_line_idx: 0,
logical_start: 0,
local_start: 0,
local_end: 0,
origin_y: Pixels::ZERO,
});
}
visual_lines
}
fn visual_lines(&self, line_height: Pixels) -> Vec<VisualLineInfo> {
self.visual_lines_for_layouts(&self.last_layouts, line_height)
}
fn point_for_offset_in_layouts(
&self,
layouts: &[WrappedLine],
offset: usize,
line_height: Pixels,
) -> Option<(usize, Point<Pixels>)> {
let logical_line_idx = self.logical_line_for_offset(offset);
let logical_start = *self.line_start_offsets().get(logical_line_idx)?;
let wrapped_line = layouts.get(logical_line_idx)?;
let local_offset = offset
.saturating_sub(logical_start)
.min(wrapped_line.text.len());
wrapped_line
.position_for_index(local_offset, line_height)
.map(|point| (logical_line_idx, point))
}
fn point_for_offset(
&self,
offset: usize,
line_height: Pixels,
) -> Option<(usize, Point<Pixels>)> {
self.point_for_offset_in_layouts(&self.last_layouts, offset, line_height)
}
fn vertical_navigation_target(
&self,
offset: usize,
delta: isize,
line_height: Pixels,
) -> Option<usize> {
if self.last_layouts.is_empty() {
return None;
}
let (logical_line_idx, cursor_point) = self.point_for_offset(offset, line_height)?;
let visual_lines = self.visual_lines(line_height);
let logical_line_origin_y = visual_lines
.iter()
.find(|line| line.logical_line_idx == logical_line_idx)?
.origin_y;
let cursor_visual_y = logical_line_origin_y + cursor_point.y;
let current_visual_line_idx = visual_lines.iter().position(|line| {
cursor_visual_y >= line.origin_y && cursor_visual_y < line.origin_y + line_height
})?;
let target_visual_line_idx = current_visual_line_idx as isize + delta;
if target_visual_line_idx < 0 || target_visual_line_idx >= visual_lines.len() as isize {
return None;
}
let target_line = visual_lines[target_visual_line_idx as usize];
let target_wrapped_line = self.last_layouts.get(target_line.logical_line_idx)?;
let logical_line_origin_y = visual_lines
.iter()
.find(|line| line.logical_line_idx == target_line.logical_line_idx)?
.origin_y;
let target_local_y = target_line.origin_y - logical_line_origin_y;
let target_local_x = cursor_point.x;
let target_local_offset = target_wrapped_line
.closest_index_for_position(gpui::point(target_local_x, target_local_y), line_height)
.unwrap_or_else(|boundary| boundary);
Some(target_line.logical_start + target_local_offset)
}
fn cursor_offset(&self) -> usize {
text_util::cursor_offset(&self.selected_range, self.selection_reversed)
}
fn move_to(&mut self, offset: usize, cx: &mut Context<Self>) {
let offset = self.clamp_offset(offset);
self.selected_range = offset..offset;
self.selection_reversed = false;
self.reset_blink(cx);
cx.notify();
}
fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
let offset = self.clamp_offset(offset);
(self.selected_range, self.selection_reversed) = text_util::extend_selection(
self.selected_range.clone(),
self.selection_reversed,
offset,
);
self.reset_blink(cx);
cx.notify();
}
fn clamp_offset(&self, offset: usize) -> usize {
text_util::clamp_offset(&self.content, offset)
}
fn previous_boundary(&self, offset: usize) -> usize {
text_util::previous_grapheme_boundary(&self.content, offset)
}
fn next_boundary(&self, offset: usize) -> usize {
text_util::next_grapheme_boundary(&self.content, offset)
}
fn previous_word_boundary(&self, offset: usize) -> usize {
text_util::previous_word_boundary(&self.content, offset)
}
fn next_word_boundary(&self, offset: usize) -> usize {
text_util::next_word_boundary(&self.content, offset)
}
fn offset_to_utf16(&self, offset: usize) -> usize {
crate::capabilities::controls::text_util::offset_to_utf16(&self.content, offset)
}
fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
crate::capabilities::controls::text_util::range_to_utf16(&self.content, range)
}
fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
crate::capabilities::controls::text_util::range_from_utf16(&self.content, range_utf16)
}
fn invalidate_layout_cache(&mut self) {
self.last_layouts.clear();
self.last_bounds = None;
self.last_visual_line_count = 1;
}
fn start_blink(&mut self, cx: &mut Context<Self>) {
self._blink_task = None;
self.cursor_visible = true;
self._blink_task = Some(edit::spawn_caret_blink(cx, |this, cx| {
this.cursor_visible = !this.cursor_visible;
cx.notify();
}));
}
fn stop_blink(&mut self) {
self._blink_task = None;
self.cursor_visible = true;
}
fn reset_blink(&mut self, cx: &mut Context<Self>) {
self.stop_blink();
self.start_blink(cx);
}
fn sync_focus_state(&mut self, is_focused: bool, _window: &mut Window, cx: &mut Context<Self>) {
if self.was_focused == is_focused {
return;
}
self.was_focused = is_focused;
if is_focused {
self.start_blink(cx);
cx.emit(TextareaEvent::Focus);
} else {
self.stop_blink();
self.is_selecting = false;
if self.should_auto_validate(self.validate_on_blur) {
self.validate(cx).ok();
}
cx.emit(TextareaEvent::Blur);
}
cx.notify();
}
fn on_mouse_down(
&mut self,
event: &MouseDownEvent,
_window: &mut Window,
cx: &mut Context<Self>,
) {
self.is_selecting = true;
let idx = self.index_for_mouse_position(event.position);
if event.click_count == 2 {
let start = self.previous_word_boundary(idx);
let end = self.next_word_boundary(idx);
self.selected_range = start..end;
self.selection_reversed = false;
self.reset_blink(cx);
cx.notify();
} else if event.modifiers.shift {
self.select_to(idx, cx);
} else {
self.move_to(idx, cx);
}
}
fn on_mouse_up(&mut self, _: &MouseUpEvent, _: &mut Window, _cx: &mut Context<Self>) {
self.is_selecting = false;
}
fn on_mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {
if self.is_selecting {
let idx = self.index_for_mouse_position(event.position);
self.select_to(idx, cx);
}
}
fn index_for_mouse_position(&self, position: Point<Pixels>) -> usize {
if self.content.is_empty() {
return 0;
}
let Some(bounds) = self.last_bounds.as_ref() else {
return 0;
};
if self.last_layouts.is_empty() {
return 0;
}
let relative_y = position.y - bounds.top();
if relative_y <= Pixels::ZERO {
return 0;
}
if position.y >= bounds.bottom() {
return self.content.len();
}
let line_height = self.last_line_height;
let visual_lines = self.visual_lines(line_height);
let relative_x = (position.x - bounds.left()).max(Pixels::ZERO);
for visual_line in &visual_lines {
if relative_y >= visual_line.origin_y && relative_y < visual_line.origin_y + line_height
{
let Some(wrapped_line) = self.last_layouts.get(visual_line.logical_line_idx) else {
return self.content.len();
};
let logical_line_origin_y = visual_lines
.iter()
.find(|line| line.logical_line_idx == visual_line.logical_line_idx)
.map(|line| line.origin_y)
.unwrap_or(Pixels::ZERO);
let local_y = relative_y - logical_line_origin_y;
let local_offset = wrapped_line
.closest_index_for_position(gpui::point(relative_x, local_y), line_height)
.unwrap_or_else(|boundary| boundary);
return visual_line.logical_start + local_offset;
}
}
self.content.len()
}
pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
if self.selected_range.is_empty() {
self.select_to(self.previous_boundary(self.cursor_offset()), cx);
}
self.replace_text_in_range(None, "", window, cx);
}
pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
if self.selected_range.is_empty() {
self.select_to(self.next_boundary(self.cursor_offset()), cx);
}
self.replace_text_in_range(None, "", window, cx);
}
pub fn left(&mut self, _: &Left, _: &mut Window, cx: &mut Context<Self>) {
if self.selected_range.is_empty() {
self.move_to(self.previous_boundary(self.cursor_offset()), cx);
} else {
self.move_to(self.selected_range.start, cx);
}
}
pub fn right(&mut self, _: &Right, _: &mut Window, cx: &mut Context<Self>) {
if self.selected_range.is_empty() {
self.move_to(self.next_boundary(self.cursor_offset()), cx);
} else {
self.move_to(self.selected_range.end, cx);
}
}
pub fn up(&mut self, _: &Up, _: &mut Window, cx: &mut Context<Self>) {
if !self.selected_range.is_empty() {
self.move_to(self.selected_range.start, cx);
return;
}
let line_height = self.last_line_height;
if let Some(new_offset) =
self.vertical_navigation_target(self.cursor_offset(), -1, line_height)
{
self.move_to(new_offset, cx);
}
}
pub fn down(&mut self, _: &Down, _: &mut Window, cx: &mut Context<Self>) {
if !self.selected_range.is_empty() {
self.move_to(self.selected_range.end, cx);
return;
}
let line_height = self.last_line_height;
if let Some(new_offset) =
self.vertical_navigation_target(self.cursor_offset(), 1, line_height)
{
self.move_to(new_offset, cx);
}
}
pub fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
self.select_to(self.previous_boundary(self.cursor_offset()), cx);
}
pub fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
self.select_to(self.next_boundary(self.cursor_offset()), cx);
}
pub fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
let line_height = self.last_line_height;
if let Some(new_offset) =
self.vertical_navigation_target(self.cursor_offset(), -1, line_height)
{
self.select_to(new_offset, cx);
}
}
pub fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
let line_height = self.last_line_height;
if let Some(new_offset) =
self.vertical_navigation_target(self.cursor_offset(), 1, line_height)
{
self.select_to(new_offset, cx);
}
}
pub fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
self.selected_range = 0..self.content.len();
self.selection_reversed = false;
self.reset_blink(cx);
cx.notify();
}
pub fn home(&mut self, _: &Home, _: &mut Window, cx: &mut Context<Self>) {
let line_start = self.line_start_for_offset(self.cursor_offset());
self.move_to(line_start, cx);
}
pub fn end(&mut self, _: &End, _: &mut Window, cx: &mut Context<Self>) {
let line_end = self.line_end_for_offset(self.cursor_offset());
self.move_to(line_end, cx);
}
pub fn word_left(&mut self, _: &WordLeft, _: &mut Window, cx: &mut Context<Self>) {
let offset = self.previous_word_boundary(self.cursor_offset());
if self.selected_range.is_empty() {
self.move_to(offset, cx);
} else {
self.move_to(self.selected_range.start.min(offset), cx);
}
}
pub fn word_right(&mut self, _: &WordRight, _: &mut Window, cx: &mut Context<Self>) {
let offset = self.next_word_boundary(self.cursor_offset());
if self.selected_range.is_empty() {
self.move_to(offset, cx);
} else {
self.move_to(self.selected_range.end.max(offset), cx);
}
}
pub fn select_word_left(&mut self, _: &SelectWordLeft, _: &mut Window, cx: &mut Context<Self>) {
self.select_to(self.previous_word_boundary(self.cursor_offset()), cx);
}
pub fn select_word_right(
&mut self,
_: &SelectWordRight,
_: &mut Window,
cx: &mut Context<Self>,
) {
self.select_to(self.next_word_boundary(self.cursor_offset()), cx);
}
pub fn enter(&mut self, _: &Enter, window: &mut Window, cx: &mut Context<Self>) {
self.replace_text_in_range(None, "\n", window, cx);
cx.emit(TextareaEvent::Enter);
}
pub fn shift_enter(&mut self, _: &ShiftEnter, _window: &mut Window, cx: &mut Context<Self>) {
cx.emit(TextareaEvent::ShiftEnter);
}
pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
self.replace_text_in_range(None, " ", window, cx);
cx.emit(TextareaEvent::Tab);
}
pub fn shift_tab(&mut self, _: &ShiftTab, _window: &mut Window, cx: &mut Context<Self>) {
cx.emit(TextareaEvent::ShiftTab);
}
pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
if !self.selected_range.is_empty() {
cx.write_to_clipboard(ClipboardItem::new_string(
self.content[self.selected_range.clone()].to_string(),
));
}
}
pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
if !self.selected_range.is_empty() {
cx.write_to_clipboard(ClipboardItem::new_string(
self.content[self.selected_range.clone()].to_string(),
));
self.replace_text_in_range(None, "", window, cx);
}
}
pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {
self.replace_text_in_range(None, &text, window, cx);
}
}
pub fn escape(&mut self, _: &Escape, _window: &mut Window, cx: &mut Context<Self>) {
self.selected_range = self.content.len()..self.content.len();
cx.notify();
}
}
impl EntityInputHandler for TextareaState {
fn text_for_range(
&mut self,
range_utf16: Range<usize>,
actual_range: &mut Option<Range<usize>>,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Option<String> {
let range = self.range_from_utf16(&range_utf16);
actual_range.replace(self.range_to_utf16(&range));
Some(self.content[range].to_string())
}
fn selected_text_range(
&mut self,
_ignore_disabled_input: bool,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Option<UTF16Selection> {
Some(UTF16Selection {
range: self.range_to_utf16(&self.selected_range),
reversed: self.selection_reversed,
})
}
fn marked_text_range(
&self,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Option<Range<usize>> {
self.marked_range
.as_ref()
.map(|range| self.range_to_utf16(range))
}
fn unmark_text(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
self.marked_range = None;
self.invalidate_layout_cache();
if self.should_auto_validate(self.validate_on_change) {
self.validate(cx).ok();
}
}
fn replace_text_in_range(
&mut self,
range_utf16: Option<Range<usize>>,
new_text: &str,
window: &mut Window,
cx: &mut Context<Self>,
) {
let had_marked_text = self.marked_range.is_some();
let range = range_utf16
.as_ref()
.map(|r| self.range_from_utf16(r))
.or(self.marked_range.clone())
.unwrap_or(self.selected_range.clone());
let new_text = if let Some(max_length) = self.validation_rules.max_length {
let retained_chars =
self.content.chars().count() - self.content[range.clone()].chars().count();
let allowed_chars = max_length.saturating_sub(retained_chars);
new_text.chars().take(allowed_chars).collect::<String>()
} else {
new_text.to_owned()
};
let next_content: SharedString =
(self.content[0..range.start].to_owned() + &new_text + &self.content[range.end..])
.into();
let content_changed = self.content != next_content;
self.content = next_content;
self.selected_range = range.start + new_text.len()..range.start + new_text.len();
self.marked_range.take();
self.selection_reversed = false;
if self.focus_handle.is_focused(window) {
self.reset_blink(cx);
}
self.invalidate_layout_cache();
if (content_changed || had_marked_text)
&& self.should_auto_validate(self.validate_on_change)
{
self.validate(cx).ok();
}
if content_changed || had_marked_text {
cx.emit(TextareaEvent::Change);
}
cx.notify();
}
fn replace_and_mark_text_in_range(
&mut self,
range_utf16: Option<Range<usize>>,
new_text: &str,
new_selected_range_utf16: Option<Range<usize>>,
window: &mut Window,
cx: &mut Context<Self>,
) {
let range = range_utf16
.as_ref()
.map(|r| self.range_from_utf16(r))
.or(self.marked_range.clone())
.unwrap_or(self.selected_range.clone());
self.content =
(self.content[0..range.start].to_owned() + new_text + &self.content[range.end..])
.into();
if !new_text.is_empty() {
self.marked_range = Some(range.start..range.start + new_text.len());
} else {
self.marked_range = None;
}
self.selected_range = text_util::selection_after_replacement(
new_text,
new_selected_range_utf16.as_ref(),
range.start,
);
self.selection_reversed = false;
if self.focus_handle.is_focused(window) {
self.reset_blink(cx);
}
self.invalidate_layout_cache();
cx.notify();
}
fn bounds_for_range(
&mut self,
range_utf16: Range<usize>,
bounds: Bounds<Pixels>,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Option<Bounds<Pixels>> {
if self.last_layouts.is_empty() {
return None;
}
let range = self.range_from_utf16(&range_utf16);
let line_height = bounds.size.height / self.visual_line_count() as f32;
let visual_lines = self.visual_lines(line_height);
let (start_logical_line_idx, start_point) =
self.point_for_offset(range.start, line_height)?;
let (end_logical_line_idx, end_point) = self.point_for_offset(range.end, line_height)?;
let start_logical_origin_y = visual_lines
.iter()
.find(|line| line.logical_line_idx == start_logical_line_idx)?
.origin_y;
let end_logical_origin_y = visual_lines
.iter()
.find(|line| line.logical_line_idx == end_logical_line_idx)?
.origin_y;
Some(Bounds::from_corners(
point(
bounds.left() + start_point.x,
bounds.top() + start_logical_origin_y + start_point.y,
),
point(
bounds.left() + end_point.x,
bounds.top() + end_logical_origin_y + end_point.y + line_height,
),
))
}
fn character_index_for_point(
&mut self,
point: Point<Pixels>,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Option<usize> {
let bounds = self.last_bounds.as_ref()?;
bounds.localize(&point)?;
if self.last_layouts.is_empty() {
return None;
}
let byte_offset = self.index_for_mouse_position(point);
Some(self.offset_to_utf16(byte_offset))
}
}
impl Render for TextareaState {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let entity = cx.entity();
div()
.w_full()
.on_mouse_down(MouseButton::Left, {
let entity = entity.clone();
move |event: &MouseDownEvent, window: &mut Window, cx: &mut App| {
entity.update(cx, |state, cx| {
state.on_mouse_down(event, window, cx);
});
}
})
.on_mouse_up(MouseButton::Left, {
let entity = entity.clone();
move |event: &MouseUpEvent, window: &mut Window, cx: &mut App| {
entity.update(cx, |state, cx| {
state.on_mouse_up(event, window, cx);
});
}
})
.on_mouse_up_out(MouseButton::Left, {
let entity = entity.clone();
move |event: &MouseUpEvent, window: &mut Window, cx: &mut App| {
entity.update(cx, |state, cx| {
state.on_mouse_up(event, window, cx);
});
}
})
.on_mouse_move({
let entity = entity.clone();
move |event: &MouseMoveEvent, window: &mut Window, cx: &mut App| {
entity.update(cx, |state, cx| {
state.on_mouse_move(event, window, cx);
});
}
})
.child(TextareaTextElement {
state: entity.clone(),
})
}
}
impl Focusable for TextareaState {
fn focus_handle(&self, _: &App) -> FocusHandle {
self.focus_handle.clone()
}
}
struct TextareaTextElement {
state: Entity<TextareaState>,
}
struct TextareaPrepaintState {
lines: Vec<WrappedLine>,
cursor: Option<PaintQuad>,
selections: Vec<PaintQuad>,
}
impl IntoElement for TextareaTextElement {
type Element = Self;
fn into_element(self) -> Self::Element {
self
}
}
impl Element for TextareaTextElement {
type RequestLayoutState = ();
type PrepaintState = TextareaPrepaintState;
fn id(&self) -> Option<ElementId> {
None
}
fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
None
}
fn request_layout(
&mut self,
_id: Option<&GlobalElementId>,
_inspector_id: Option<&InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, Self::RequestLayoutState) {
let state = self.state.read(cx);
let line_count = state.visual_line_count();
let line_height = window.line_height();
let mut style = Style::default();
style.size.width = relative(1.).into();
style.size.height = (line_height * line_count as f32).into();
(window.request_layout(style, [], cx), ())
}
fn prepaint(
&mut self,
_id: Option<&GlobalElementId>,
_inspector_id: Option<&InspectorElementId>,
bounds: Bounds<Pixels>,
_request_layout: &mut Self::RequestLayoutState,
window: &mut Window,
cx: &mut App,
) -> Self::PrepaintState {
let input = self.state.read(cx);
let text_style = window.text_style();
let theme = use_theme(cx);
let font_size = text_style.font_size.to_pixels(window.rem_size());
let line_height = window.line_height();
let content_lines = input.lines();
let starts = input.line_start_offsets();
let selected_range = input.selected_range.clone();
let cursor_offset = input.cursor_offset();
let is_empty = input.content.is_empty();
let placeholder = input.placeholder.clone();
let marked_range = input.marked_range.clone();
let wrap_width = Some(bounds.size.width.max(px(1.0)));
let mut wrapped_lines = Vec::with_capacity(content_lines.len().max(1));
for (line_idx, line_text) in content_lines.iter().enumerate() {
let (display_text, text_color) = if is_empty && line_idx == 0 {
(placeholder.clone(), theme.tokens.muted_foreground)
} else if is_empty {
(SharedString::from(""), text_style.color)
} else {
(SharedString::from(line_text.to_string()), text_style.color)
};
let base_run = TextRun {
len: display_text.len(),
font: text_style.font(),
color: text_color,
background_color: None,
underline: None,
strikethrough: None,
};
let runs = if !is_empty {
if let Some(ref marked) = marked_range {
let line_start = starts[line_idx];
let line_end = line_start + line_text.len();
let mark_start = marked.start.max(line_start).saturating_sub(line_start);
let mark_end = marked.end.min(line_end).saturating_sub(line_start);
if mark_start < mark_end && mark_start < display_text.len() {
vec![
TextRun {
len: mark_start,
..base_run.clone()
},
TextRun {
len: mark_end - mark_start,
underline: Some(UnderlineStyle {
color: Some(base_run.color),
thickness: edit::IME_UNDERLINE_THICKNESS,
wavy: false,
}),
..base_run.clone()
},
TextRun {
len: display_text.len() - mark_end,
..base_run.clone()
},
]
.into_iter()
.filter(|r| r.len > 0)
.collect()
} else {
vec![base_run]
}
} else {
vec![base_run]
}
} else {
vec![base_run]
};
let mut shaped = window
.text_system()
.shape_text(display_text, font_size, &runs, wrap_width, None)
.unwrap_or_default();
wrapped_lines.push(shaped.pop().unwrap_or_default());
}
let visual_lines = input.visual_lines_for_layouts(&wrapped_lines, line_height);
let mut cursor_quad = None;
let mut selection_quads = Vec::new();
if selected_range.is_empty() {
if let Some((logical_line_idx, cursor_point)) =
input.point_for_offset_in_layouts(&wrapped_lines, cursor_offset, line_height)
{
let logical_line_origin_y = visual_lines
.iter()
.find(|line| line.logical_line_idx == logical_line_idx)
.map(|line| line.origin_y)
.unwrap_or(Pixels::ZERO);
cursor_quad = Some(fill(
Bounds::new(
point(
bounds.left() + cursor_point.x,
bounds.top() + logical_line_origin_y + cursor_point.y,
),
size(edit::CARET_WIDTH, line_height),
),
theme.tokens.primary,
));
}
} else if !is_empty {
for visual_line in &visual_lines {
let visual_start = visual_line.logical_start + visual_line.local_start;
let visual_end = visual_line.logical_start + visual_line.local_end;
let overlaps_text =
selected_range.start < visual_end && selected_range.end > visual_start;
let spans_newline = selected_range.end > visual_end
&& visual_line.local_end
== wrapped_lines
.get(visual_line.logical_line_idx)
.map(|line| line.text.len())
.unwrap_or(0);
if !overlaps_text && !spans_newline {
continue;
}
let Some(wrapped_line) = wrapped_lines.get(visual_line.logical_line_idx) else {
continue;
};
let local_start = selected_range
.start
.max(visual_start)
.saturating_sub(visual_line.logical_start)
.min(wrapped_line.text.len());
let local_end = selected_range
.end
.min(visual_end)
.saturating_sub(visual_line.logical_start)
.min(wrapped_line.text.len());
let Some(start_point) = wrapped_line.position_for_index(local_start, line_height)
else {
continue;
};
let end_point = wrapped_line
.position_for_index(local_end, line_height)
.unwrap_or(start_point);
let logical_line_origin_y = visual_lines
.iter()
.find(|line| line.logical_line_idx == visual_line.logical_line_idx)
.map(|line| line.origin_y)
.unwrap_or(Pixels::ZERO);
let x_end = if spans_newline {
wrapped_line.width().max(end_point.x + px(4.0))
} else {
end_point.x
};
selection_quads.push(fill(
Bounds::from_corners(
point(
bounds.left() + start_point.x,
bounds.top() + logical_line_origin_y + start_point.y,
),
point(
bounds.left() + x_end,
bounds.top() + logical_line_origin_y + end_point.y + line_height,
),
),
theme
.tokens
.primary
.opacity(edit::SELECTION_HIGHLIGHT_OPACITY),
));
}
}
TextareaPrepaintState {
lines: wrapped_lines,
cursor: cursor_quad,
selections: selection_quads,
}
}
fn paint(
&mut self,
_id: Option<&GlobalElementId>,
_inspector_id: Option<&InspectorElementId>,
bounds: Bounds<Pixels>,
_request_layout: &mut Self::RequestLayoutState,
prepaint: &mut Self::PrepaintState,
window: &mut Window,
cx: &mut App,
) {
let focus_handle = self.state.read(cx).focus_handle.clone();
let disabled = self.state.read(cx).disabled;
let line_height = window.line_height();
if !disabled {
window.handle_input(
&focus_handle,
ElementInputHandler::new(bounds, self.state.clone()),
cx,
);
}
for selection in prepaint.selections.drain(..) {
window.paint_quad(selection);
}
let lines = std::mem::take(&mut prepaint.lines);
let mut painted_lines = Vec::with_capacity(lines.len());
let mut current_y = Pixels::ZERO;
for line in lines.into_iter() {
let origin = point(bounds.left(), bounds.top() + current_y);
let _ = line.paint(
origin,
line_height,
TextAlign::default(),
Some(bounds),
window,
cx,
);
current_y += line.size(line_height).height;
painted_lines.push(line);
}
let is_focused = focus_handle.is_focused(window);
if is_focused {
let cursor_visible = self.state.read(cx).cursor_visible;
if cursor_visible {
if let Some(cursor) = prepaint.cursor.take() {
window.paint_quad(cursor);
}
}
}
self.state.update(cx, |state, cx| {
let visual_line_count = painted_lines
.iter()
.map(|line| line.wrap_boundaries().len() + 1)
.sum::<usize>()
.max(1);
state.last_layouts = painted_lines;
state.last_bounds = Some(bounds);
state.last_line_height = line_height;
if state.last_visual_line_count != visual_line_count {
state.last_visual_line_count = visual_line_count;
cx.notify();
}
state.sync_focus_state(is_focused, window, cx);
});
}
}
pub fn wire_actions(state: &Entity<TextareaState>, window: &mut Window, cx: &App) -> Stateful<Div> {
let disabled = state.read(cx).disabled;
let focus_handle = state.read(cx).focus_handle(cx);
let scroll_handle = state.read(cx).scroll_handle.clone();
let focus_handle_for_mouse = focus_handle.clone();
div()
.id(("textarea", state.entity_id()))
.key_context("Textarea")
.track_focus(&focus_handle.tab_index(0).tab_stop(true))
.track_scroll(&scroll_handle)
.overflow_y_scroll()
.when(!disabled, |this| {
this.on_mouse_down(MouseButton::Left, move |_event, window, _cx| {
window.focus(&focus_handle_for_mouse);
})
.on_action(window.listener_for(state, TextareaState::backspace))
.on_action(window.listener_for(state, TextareaState::delete))
.on_action(window.listener_for(state, TextareaState::left))
.on_action(window.listener_for(state, TextareaState::right))
.on_action(window.listener_for(state, TextareaState::up))
.on_action(window.listener_for(state, TextareaState::down))
.on_action(window.listener_for(state, TextareaState::select_left))
.on_action(window.listener_for(state, TextareaState::select_right))
.on_action(window.listener_for(state, TextareaState::select_up))
.on_action(window.listener_for(state, TextareaState::select_down))
.on_action(window.listener_for(state, TextareaState::select_all))
.on_action(window.listener_for(state, TextareaState::home))
.on_action(window.listener_for(state, TextareaState::end))
.on_action(window.listener_for(state, TextareaState::copy))
.on_action(window.listener_for(state, TextareaState::cut))
.on_action(window.listener_for(state, TextareaState::paste))
.on_action(window.listener_for(state, TextareaState::enter))
.on_action(window.listener_for(state, TextareaState::shift_enter))
.on_action(window.listener_for(state, TextareaState::tab))
.on_action(window.listener_for(state, TextareaState::shift_tab))
.on_action(window.listener_for(state, TextareaState::escape))
.on_action(window.listener_for(state, TextareaState::word_left))
.on_action(window.listener_for(state, TextareaState::word_right))
.on_action(window.listener_for(state, TextareaState::select_word_left))
.on_action(window.listener_for(state, TextareaState::select_word_right))
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::capabilities::foundation::theme::{install_theme, Theme};
struct TestView {
state: Entity<TextareaState>,
}
#[gpui::test]
fn builders_configure_common_state_options() {
let mut app = TestApp::new();
app.update(|cx| install_theme(cx, Theme::light()));
let state = app.update(|cx| {
cx.new(|cx| {
TextareaState::new(cx)
.value("hello")
.placeholder("p")
.disabled(true)
})
});
app.update(|cx| {
let state = state.read(cx);
assert_eq!(state.content(), "hello");
assert_eq!(state.placeholder, "p");
assert!(state.disabled);
});
}
impl Render for TestView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
}
}
#[gpui::test]
fn word_left_moves_cursor_to_previous_word_boundary() {
let mut app = TestApp::new();
app.update(|cx| install_theme(cx, Theme::light()));
let state = app.update(|cx| cx.new(TextareaState::new));
let mut window = app.open_window(|_, _| TestView {
state: state.clone(),
});
let text = "foo bar baz";
window.update(|view, window, cx| {
view.state.update(cx, |state, cx| {
state.set_value(text, window, cx);
state.word_left(&WordLeft, window, cx);
assert_eq!(state.selected_range, 8..8, "should stop before baz");
state.word_left(&WordLeft, window, cx);
assert_eq!(state.selected_range, 4..4, "should stop before bar");
state.word_left(&WordLeft, window, cx);
assert_eq!(state.selected_range, 0..0, "should reach start");
});
});
}
#[gpui::test]
fn word_right_moves_cursor_to_next_word_boundary() {
let mut app = TestApp::new();
app.update(|cx| install_theme(cx, Theme::light()));
let state = app.update(|cx| cx.new(TextareaState::new));
let mut window = app.open_window(|_, _| TestView {
state: state.clone(),
});
window.update(|view, window, cx| {
view.state.update(cx, |state, cx| {
state.set_value("foo bar baz", window, cx);
state.selected_range = 0..0;
state.word_right(&WordRight, window, cx);
assert_eq!(state.selected_range, 4..4, "should stop at bar start");
state.word_right(&WordRight, window, cx);
assert_eq!(state.selected_range, 8..8, "should stop at baz start");
state.word_right(&WordRight, window, cx);
assert_eq!(state.selected_range, 11..11, "should reach end");
});
});
}
#[gpui::test]
fn word_movement_handles_unicode() {
let mut app = TestApp::new();
app.update(|cx| install_theme(cx, Theme::light()));
let state = app.update(|cx| cx.new(TextareaState::new));
let mut window = app.open_window(|_, _| TestView {
state: state.clone(),
});
let text = "中文 test";
window.update(|view, window, cx| {
view.state.update(cx, |state, cx| {
state.set_value(text, window, cx);
state.word_left(&WordLeft, window, cx);
assert_eq!(state.selected_range, 7..7, "should stop before test");
state.word_left(&WordLeft, window, cx);
assert_eq!(state.selected_range, 0..0, "should reach start");
});
});
}
#[gpui::test]
fn grapheme_deletion_removes_whole_unicode_clusters() {
let mut app = TestApp::new();
app.update(|cx| install_theme(cx, Theme::light()));
let state = app.update(|cx| cx.new(TextareaState::new));
let mut window = app.open_window(|_, _| TestView {
state: state.clone(),
});
window.update(|view, window, cx| {
view.state.update(cx, |state, cx| {
state.set_value("a👩💻e\u{301}b", window, cx);
state.backspace(&Backspace, window, cx);
assert_eq!(state.content(), "a👩💻e\u{301}");
assert_eq!(
state.selected_range,
state.content().len()..state.content().len()
);
state.backspace(&Backspace, window, cx);
assert_eq!(state.content(), "a👩💻");
assert_eq!(
state.selected_range,
state.content().len()..state.content().len()
);
state.selected_range = "a".len().."a".len();
state.selection_reversed = false;
state.delete(&Delete, window, cx);
assert_eq!(state.content(), "a");
assert_eq!(state.selected_range, "a".len().."a".len());
});
});
}
#[gpui::test]
fn selection_direction_flips_when_crossing_the_anchor() {
let mut app = TestApp::new();
app.update(|cx| install_theme(cx, Theme::light()));
let state = app.update(|cx| cx.new(TextareaState::new));
let mut window = app.open_window(|_, _| TestView {
state: state.clone(),
});
window.update(|view, window, cx| {
view.state.update(cx, |state, cx| {
let text = "a😀b";
let emoji_start = "a".len();
let emoji_end = "a😀".len();
state.set_value(text, window, cx);
state.selected_range = emoji_start..emoji_start;
state.selection_reversed = false;
state.select_right(&SelectRight, window, cx);
assert_eq!(state.selected_range, emoji_start..emoji_end);
assert!(!state.selection_reversed);
state.select_left(&SelectLeft, window, cx);
assert_eq!(state.selected_range, emoji_start..emoji_start);
assert!(!state.selection_reversed);
state.select_left(&SelectLeft, window, cx);
assert_eq!(state.selected_range, 0..emoji_start);
assert!(state.selection_reversed);
state.selected_range = emoji_end..emoji_end;
state.selection_reversed = false;
state.select_left(&SelectLeft, window, cx);
assert_eq!(state.selected_range, emoji_start..emoji_end);
assert!(state.selection_reversed);
state.select_right(&SelectRight, window, cx);
assert_eq!(state.selected_range, emoji_end..emoji_end);
assert!(state.selection_reversed);
state.select_right(&SelectRight, window, cx);
assert_eq!(state.selected_range, emoji_end..text.len());
assert!(!state.selection_reversed);
});
});
}
#[gpui::test]
fn utf16_ranges_preserve_astral_character_boundaries() {
let mut app = TestApp::new();
app.update(|cx| install_theme(cx, Theme::light()));
let state = app.update(|cx| cx.new(TextareaState::new));
let mut window = app.open_window(|_, _| TestView {
state: state.clone(),
});
window.update(|view, window, cx| {
view.state.update(cx, |state, cx| {
state.set_value("a😀b", window, cx);
let mut actual_range = None;
assert_eq!(
state.text_for_range(1..3, &mut actual_range, window, cx),
Some("😀".to_string())
);
assert_eq!(actual_range, Some(1..3));
state.selected_range = "a".len().."a😀".len();
let selected = state
.selected_text_range(false, window, cx)
.expect("selection should be available");
assert_eq!(selected.range, 1..3);
assert!(!selected.reversed);
state.replace_text_in_range(Some(1..3), "", window, cx);
assert_eq!(state.content(), "ab");
assert_eq!(state.selected_range, 1..1);
});
});
}
#[gpui::test]
fn validate_required_fails_on_empty() {
let mut app = TestApp::new();
app.update(|cx| install_theme(cx, Theme::light()));
let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).required(true)));
app.update(|cx| {
let result = state.update(cx, |state, cx| state.validate(cx));
assert!(result.is_err());
assert_eq!(
state
.read(cx)
.validation_error
.as_ref()
.unwrap()
.message
.as_ref(),
"This field is required"
);
});
}
#[gpui::test]
fn validate_enforces_min_and_max_length() {
let mut app = TestApp::new();
app.update(|cx| install_theme(cx, Theme::light()));
let state = app.update(|cx| {
cx.new(|cx| {
TextareaState::new(cx)
.min_length(2)
.max_length(3)
.value("a")
})
});
app.update(|cx| {
let result = state.update(cx, |state, cx| state.validate(cx));
assert!(result.is_err());
assert_eq!(
state
.read(cx)
.validation_error
.as_ref()
.unwrap()
.message
.as_ref(),
"Must be at least 2 characters"
);
});
let state =
app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(3).value("abcd")));
app.update(|cx| {
let result = state.update(cx, |state, cx| state.validate(cx));
assert!(result.is_err());
});
let state = app.update(|cx| {
cx.new(|cx| {
TextareaState::new(cx)
.min_length(2)
.max_length(3)
.value("abc")
})
});
app.update(|cx| {
let result = state.update(cx, |state, cx| state.validate(cx));
assert!(result.is_ok());
assert!(state.read(cx).validation_error.is_none());
assert_eq!(
state.read(cx).success_message.as_ref().unwrap().as_ref(),
"Valid input"
);
});
}
#[gpui::test]
fn validate_optional_empty_clears_stale_messages() {
let mut app = TestApp::new();
app.update(|cx| install_theme(cx, Theme::light()));
let state = app.update(|cx| cx.new(TextareaState::new));
app.update(|cx| {
state.update(cx, |state, cx| {
state.validation_error = Some(ValidationError {
message: "stale".into(),
field_name: None,
});
state.success_message = Some("stale".into());
let result = state.validate(cx);
assert!(result.is_ok());
assert!(state.validation_error.is_none());
assert!(state.success_message.is_none());
});
});
}
#[gpui::test]
fn validate_runs_custom_validator() {
let mut app = TestApp::new();
app.update(|cx| install_theme(cx, Theme::light()));
let state = app.update(|cx| {
cx.new(|cx| {
TextareaState::new(cx)
.value("forbidden")
.validation_rules(ValidationRules {
custom_validator: Some(std::sync::Arc::new(|value| {
if value.contains("forbidden") {
Err(ValidationError {
message: "Contains forbidden word".into(),
field_name: None,
})
} else {
Ok(())
}
})),
..Default::default()
})
})
});
app.update(|cx| {
let result = state.update(cx, |state, cx| state.validate(cx));
assert!(result.is_err());
assert_eq!(
state
.read(cx)
.validation_error
.as_ref()
.unwrap()
.message
.as_ref(),
"Contains forbidden word"
);
});
}
#[gpui::test]
fn validate_emits_event_with_result() {
let mut app = TestApp::new();
app.update(|cx| install_theme(cx, Theme::light()));
let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).required(true)));
let outcomes = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
let outcomes_for_sub = outcomes.clone();
app.update(|cx| {
cx.subscribe(&state, move |_, event: &TextareaEvent, _| {
if let TextareaEvent::Validate(result) = event {
outcomes_for_sub.borrow_mut().push(result.is_err());
}
})
.detach();
});
app.update(|cx| {
state.update(cx, |state, cx| state.validate(cx)).ok();
});
assert_eq!(outcomes.borrow().as_slice(), &[true]);
}
#[gpui::test]
fn ime_composition_state_is_queryable() {
let mut app = TestApp::new();
app.update(|cx| install_theme(cx, Theme::light()));
let state = app.update(|cx| cx.new(TextareaState::new));
let mut window = app.open_window(|_, _| TestView {
state: state.clone(),
});
window.update(|view, window, cx| {
view.state.update(cx, |state, cx| {
state.set_value("hello", window, cx);
assert!(!state.is_composing());
assert_eq!(state.composition_char_count(), 0);
state.replace_and_mark_text_in_range(None, "nihao", None, window, cx);
assert!(state.is_composing());
assert_eq!(state.composition_char_count(), 5);
assert_eq!(
state.content().chars().count() - state.composition_char_count(),
5
);
});
});
window.update(|view, window, cx| {
view.state.update(cx, |state, cx| {
state.replace_text_in_range(None, "你好", window, cx);
assert!(!state.is_composing());
assert_eq!(state.composition_char_count(), 0);
assert_eq!(state.content(), "hello你好");
});
});
}
#[gpui::test]
fn max_length_commit_does_not_count_inflight_composition() {
let mut app = TestApp::new();
app.update(|cx| install_theme(cx, Theme::light()));
let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(7)));
let mut window = app.open_window(|_, _| TestView {
state: state.clone(),
});
window.update(|view, window, cx| {
view.state.update(cx, |state, cx| {
state.set_value("hello", window, cx);
state.replace_and_mark_text_in_range(None, "nihao", None, window, cx);
state.replace_text_in_range(None, "你好", window, cx);
assert_eq!(state.content(), "hello你好");
});
});
}
#[gpui::test]
fn validate_ignores_inflight_ime_text() {
let mut app = TestApp::new();
app.update(|cx| install_theme(cx, Theme::light()));
let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).min_length(6)));
let mut window = app.open_window(|_, _| TestView {
state: state.clone(),
});
window.update(|view, window, cx| {
view.state.update(cx, |state, cx| {
state.set_value("hello", window, cx);
state.replace_and_mark_text_in_range(None, "nihao", None, window, cx);
let result = state.validate(cx);
assert!(result.is_err());
assert!(state.validation_error.is_some());
state.replace_text_in_range(None, "", window, cx);
let result = state.validate(cx);
assert!(result.is_err());
assert!(state.validation_error.is_some());
});
});
}
}