use gpui_kit::{App, SharedString, Window};
use rust_i18n::t;
use super::{InputField, initial_text};
use crate::{
model::{GridRow, OwnedValue},
state::edit::{CellEditor, EditError, EditorOpen, EditorStart},
};
#[derive(Clone, Debug)]
pub struct TextEditor {
placeholder: Option<SharedString>,
max_length: Option<usize>,
empty_value: OwnedValue,
}
impl Default for TextEditor {
fn default() -> Self {
Self::new()
}
}
impl TextEditor {
pub fn new() -> Self {
Self {
placeholder: None,
max_length: None,
empty_value: OwnedValue::Empty,
}
}
pub fn with_placeholder(mut self, text: impl Into<SharedString>) -> Self {
self.placeholder = Some(text.into());
self
}
pub fn with_max_length(mut self, chars: usize) -> Self {
self.max_length = Some(chars);
self
}
pub fn with_empty_value(mut self, value: OwnedValue) -> Self {
self.empty_value = value;
self
}
pub fn placeholder(&self) -> Option<&SharedString> {
self.placeholder.as_ref()
}
pub fn max_length(&self) -> Option<usize> {
self.max_length
}
pub fn empty_value(&self) -> &OwnedValue {
&self.empty_value
}
fn parse(
draft: &str,
max_length: Option<usize>,
empty: &OwnedValue,
) -> Result<OwnedValue, EditError> {
if draft.is_empty() {
return Ok(empty.clone());
}
if let Some(max) = max_length
&& draft.chars().count() > max
{
return Err(EditError::new(t!("live_grid.edit.too_long", count = max)));
}
Ok(OwnedValue::Text(draft.into()))
}
}
impl<R: GridRow> CellEditor<R> for TextEditor {
fn open(&self, start: &EditorStart<'_, R>, window: &mut Window, cx: &mut App) -> EditorOpen {
let text = initial_text(start, '.');
let placeholder = self.placeholder.clone();
let state = InputField::input_state(
&text,
|state| match placeholder {
Some(placeholder) => state.placeholder(placeholder),
None => state,
},
window,
cx,
);
let (max_length, empty) = (self.max_length, self.empty_value.clone());
EditorOpen::Field(Box::new(InputField::new(
state,
text,
false,
Box::new(move |draft| Self::parse(draft, max_length, &empty)),
)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_text_editor_parse() {
let parse = |draft: &str, max: Option<usize>, empty: &OwnedValue| {
TextEditor::parse(draft, max, empty)
};
assert_eq!(parse("", None, &OwnedValue::Empty), Ok(OwnedValue::Empty));
let blank = OwnedValue::Text("".into());
assert_eq!(parse("", None, &blank), Ok(blank.clone()));
assert_eq!(
parse("Сбер", Some(4), &OwnedValue::Empty),
Ok(OwnedValue::Text("Сбер".into()))
);
let error = parse("Сбербанк", Some(4), &OwnedValue::Empty).unwrap_err();
assert_eq!(error.message().as_ref(), "Use at most 4 characters");
let editor = TextEditor::new()
.with_placeholder("Note")
.with_max_length(10)
.with_empty_value(blank.clone());
assert_eq!(editor.placeholder().map(AsRef::as_ref), Some("Note"));
assert_eq!(editor.max_length(), Some(10));
assert_eq!(editor.empty_value(), &blank);
}
}