use std::{
cell::RefCell,
collections::{BTreeMap, HashMap, HashSet},
rc::Rc,
};
use gpui::{
App, Entity, FocusHandle, Pixels, Point, ScrollHandle, SharedString, Subscription, Task, Window,
};
use super::{
path::{FieldKey, FormValues, Path},
validators::{FormError, FormValidators, LocalFuture, ValidationEvent, Validators},
};
use crate::Cx;
mod arrays;
#[cfg(feature = "devtools")]
pub(crate) mod devtools;
mod draft;
mod field;
mod submit;
mod validation;
pub use arrays::ArrayFieldApi;
#[cfg(feature = "persist")]
use draft::{watch_draft, Draft, DraftState};
pub use field::FieldApi;
pub(crate) use submit::submit;
use submit::{settle_submit, WaitingSubmit};
use validation::{erase, validate_keys, ErasedField};
type SubmitHandler<V> = Rc<dyn Fn(V, &mut App) -> Task<Result<(), FormError>>>;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FieldMeta {
pub is_touched: bool,
pub is_blurred: bool,
pub is_dirty: bool,
pub is_validating: bool,
pub error_map: BTreeMap<ValidationEvent, SharedString>,
pub form_error_map: BTreeMap<ValidationEvent, SharedString>,
}
impl FieldMeta {
#[must_use]
pub fn errors(&self) -> Vec<SharedString> {
let mut errors: Vec<SharedString> = Vec::new();
for error in self.error_map.values().chain(self.form_error_map.values()) {
if !errors.contains(error) {
errors.push(error.clone());
}
}
errors
}
#[must_use]
pub fn is_valid(&self) -> bool {
self.error_map.is_empty() && self.form_error_map.is_empty()
}
#[must_use]
pub fn is_pristine(&self) -> bool {
!self.is_dirty
}
}
pub(crate) struct Binding<V> {
pub(crate) input: Entity<crate::components::InputState>,
pub(crate) path: Rc<RefCell<Path<V, String>>>,
pub(crate) _subscriptions: Vec<Subscription>,
}
pub(crate) struct FormInner<V> {
pub(crate) values: V,
defaults: V,
meta: HashMap<SharedString, FieldMeta>,
order: Vec<SharedString>,
fields: HashMap<SharedString, ErasedField<V>>,
form_validators: FormValidators<V>,
form_errors: BTreeMap<ValidationEvent, Vec<SharedString>>,
on_submit: Option<SubmitHandler<V>>,
is_submitting: bool,
is_submitted: bool,
waiting_submit: Option<WaitingSubmit>,
attempts: u32,
async_runs: HashMap<(SharedString, ValidationEvent), (u64, Task<()>)>,
async_generation: u64,
mounted: HashSet<SharedString>,
pub(crate) bindings: HashMap<SharedString, Binding<V>>,
pub(crate) focus: HashMap<SharedString, FocusHandle>,
pub(crate) scroll: Option<ScrollHandle>,
pub(crate) anchors: HashMap<SharedString, FieldAnchor>,
revision: u64,
#[cfg(feature = "persist")]
draft: Option<DraftState>,
}
pub(crate) type FieldAnchor = Rc<std::cell::Cell<Option<Point<Pixels>>>>;
pub struct FormOptions<V> {
defaults: V,
validators: FormValidators<V>,
fields: Vec<(SharedString, ErasedField<V>)>,
on_submit: Option<SubmitHandler<V>>,
scroll: Option<ScrollHandle>,
#[cfg(feature = "persist")]
draft: Option<Draft<V>>,
}
impl<V: FormValues> FormOptions<V> {
#[must_use]
pub fn new(defaults: V) -> Self {
Self {
defaults,
validators: FormValidators::new(),
fields: Vec::new(),
on_submit: None,
scroll: None,
#[cfg(feature = "persist")]
draft: None,
}
}
#[must_use]
pub fn scroll_handle(mut self, handle: ScrollHandle) -> Self {
self.scroll = Some(handle);
self
}
#[must_use]
pub fn validators(mut self, validators: FormValidators<V>) -> Self {
self.validators = validators;
self
}
#[must_use]
pub fn field<T: Clone + 'static>(
mut self,
path: impl Into<Path<V, T>>,
validators: Validators<T>,
) -> Self {
let path = path.into();
self.fields
.push((path.key().clone(), erase(path, validators)));
self
}
#[must_use]
pub fn on_submit(
mut self,
submit: impl Fn(V, &mut App) -> Task<Result<(), FormError>> + 'static,
) -> Self {
self.on_submit = Some(Rc::new(submit));
self
}
#[cfg(feature = "persist")]
#[must_use]
pub fn persist_draft(mut self, options: crate::persist::PersistOptions) -> Self
where
V: serde::Serialize + serde::de::DeserializeOwned,
{
self.draft = Some(Draft {
options,
load: |file| file.load::<V>(),
save: |file, values, cx| file.save(values.clone(), cx),
});
self
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FormState {
pub can_submit: bool,
pub is_submitting: bool,
pub is_submitted: bool,
pub submission_attempts: u32,
pub is_valid: bool,
pub is_dirty: bool,
pub is_touched: bool,
pub is_validating: bool,
pub errors: Vec<SharedString>,
}
pub struct Form<V> {
pub(crate) entity: Entity<FormInner<V>>,
values: Rc<V>,
state: FormState,
}
impl<V> Clone for Form<V> {
fn clone(&self) -> Self {
Self {
entity: self.entity.clone(),
values: self.values.clone(),
state: self.state.clone(),
}
}
}
#[track_caller]
pub fn use_form<V: FormValues>(cx: &mut Cx, options: FormOptions<V>) -> Form<V> {
let FormOptions {
defaults,
validators,
fields,
on_submit,
scroll,
#[cfg(feature = "persist")]
draft,
} = options;
let entity = cx.window.use_state(cx.app, |_, cx| {
#[cfg(not(feature = "persist"))]
let _ = cx;
FormInner {
#[cfg(feature = "persist")]
values: draft
.as_ref()
.and_then(|draft| {
(draft.load)(&crate::persist::DraftFile::new(cx, draft.options.clone()))
})
.unwrap_or_else(|| defaults.clone()),
#[cfg(not(feature = "persist"))]
values: defaults.clone(),
defaults,
meta: HashMap::new(),
order: Vec::new(),
fields: HashMap::new(),
form_validators: FormValidators::new(),
form_errors: BTreeMap::new(),
on_submit: None,
is_submitting: false,
is_submitted: false,
waiting_submit: None,
attempts: 0,
async_runs: HashMap::new(),
async_generation: 0,
mounted: HashSet::new(),
bindings: HashMap::new(),
focus: HashMap::new(),
scroll: None,
anchors: HashMap::new(),
revision: 0,
#[cfg(feature = "persist")]
draft: None,
}
});
#[cfg(feature = "devtools")]
devtools::register(&entity, cx.app);
#[cfg(feature = "persist")]
if let Some(draft) = draft {
if entity.read(cx.app).draft.is_none() {
let file = Rc::new(crate::persist::DraftFile::new(cx.app, draft.options));
watch_draft(&entity, cx.app, file, draft.save);
}
}
let mut new_fields = Vec::new();
entity.update(cx.app, |inner, _| {
inner.form_validators = validators;
inner.on_submit = on_submit;
inner.scroll = scroll;
for (key, field) in fields {
if !inner.fields.contains_key(&key) {
new_fields.push(key.clone());
}
inner.fields.insert(key, field);
}
});
mount(&entity, cx.app, &new_fields);
Form::snapshot(entity, cx.app)
}
fn mount<V: FormValues>(form: &Entity<FormInner<V>>, cx: &mut App, keys: &[SharedString]) {
let unmounted: Vec<SharedString> = form.update(cx, |inner, _| {
keys.iter()
.filter(|key| inner.mounted.insert((*key).clone()))
.cloned()
.collect()
});
if !unmounted.is_empty() {
validate_keys(form, cx, &unmounted, ValidationEvent::Mount);
}
}
impl<V: FormValues> Form<V> {
fn snapshot(entity: Entity<FormInner<V>>, cx: &App) -> Self {
let inner = entity.read(cx);
let is_valid = inner.is_valid();
let state = FormState {
can_submit: is_valid && !inner.is_submitting,
is_submitting: inner.is_submitting,
is_submitted: inner.is_submitted,
submission_attempts: inner.attempts,
is_valid,
is_dirty: inner.meta.values().any(|meta| meta.is_dirty),
is_touched: inner.meta.values().any(|meta| meta.is_touched),
is_validating: inner.is_validating(),
errors: inner.form_errors.values().flatten().cloned().collect(),
};
let values = Rc::new(inner.values.clone());
Self {
entity,
values,
state,
}
}
#[must_use]
pub fn values(&self) -> &V {
&self.values
}
#[must_use]
pub fn state(&self) -> &FormState {
&self.state
}
#[must_use]
pub fn is_dirty(&self) -> bool {
self.state.is_dirty
}
pub fn field<T: Clone + 'static>(
&self,
cx: &mut App,
path: impl Into<Path<V, T>>,
) -> FieldApi<V, T> {
let path = path.into();
let key = path.key().clone();
self.entity.update(cx, |inner, _| {
inner.meta_mut(&key);
});
mount(&self.entity, cx, std::slice::from_ref(&key));
FieldApi::read(&self.entity, path, cx)
}
pub fn field_with<T: Clone + 'static>(
&self,
cx: &mut App,
path: impl Into<Path<V, T>>,
validators: Validators<T>,
) -> FieldApi<V, T> {
let path = path.into();
let key = path.key().clone();
let field = erase(path.clone(), validators);
self.entity.update(cx, |inner, _| {
inner.fields.insert(key, field);
});
self.field(cx, path)
}
pub fn array_field<E: Clone + 'static>(
&self,
cx: &mut App,
path: impl Into<Path<V, Vec<E>>>,
) -> ArrayFieldApi<V, E> {
let path = path.into();
let items = path.get(&self.values).cloned().unwrap_or_default();
let _ = cx;
ArrayFieldApi {
form: self.entity.clone(),
path,
items,
}
}
pub fn set_value<T: 'static>(&self, cx: &mut App, path: impl Into<Path<V, T>>, value: T) {
set_value(&self.entity, cx, &path.into(), value);
}
pub fn apply_errors(&self, cx: &mut App, errors: FormError) {
self.entity.update(cx, |inner, cx| {
inner.apply_form_error(ValidationEvent::Server, errors);
cx.notify();
});
}
pub fn validate(&self, cx: &mut App, event: ValidationEvent) {
let keys = self.entity.read(cx).order.clone();
validate_keys(&self.entity, cx, &keys, event);
}
pub fn reset(&self, cx: &mut App) {
self.entity.update(cx, |inner, cx| {
inner.values = inner.defaults.clone();
inner.revision += 1;
inner.discard_draft();
inner.meta.clear();
inner.form_errors.clear();
inner.async_runs.clear();
if inner.waiting_submit.take().is_some() {
inner.is_submitting = false;
}
inner.attempts = 0;
inner.is_submitted = false;
cx.notify();
});
}
pub fn reset_field<T: Clone + 'static>(&self, cx: &mut App, path: impl Into<Path<V, T>>) {
let path = path.into();
self.entity.update(cx, |inner, cx| {
if let Some(default) = path.get(&inner.defaults).cloned() {
inner.revision += 1;
if let Some(value) = path.get_mut(&mut inner.values) {
*value = default;
}
}
inner.meta.insert(path.key().clone(), FieldMeta::default());
inner.async_runs.retain(|(key, _), _| key != path.key());
cx.notify();
});
settle_submit(&self.entity, cx);
}
pub fn submit(&self, window: &mut Window, cx: &mut App) {
submit(&self.entity, Some(window), cx);
}
pub fn submit_handler<Event>(&self) -> impl Fn(&Event, &mut Window, &mut App) + 'static {
let form = self.entity.clone();
move |_, window, cx| submit(&form, Some(window), cx)
}
}
pub(crate) fn set_value<V: FormValues, T: 'static>(
form: &Entity<FormInner<V>>,
cx: &mut App,
path: &Path<V, T>,
value: T,
) {
let key = path.key().clone();
let changed = form.update(cx, |inner, _| {
let Some(slot) = path.get_mut(&mut inner.values) else {
return false;
};
*slot = value;
inner.revision += 1;
let meta = inner.meta_mut(&key);
meta.is_dirty = true;
meta.is_touched = true;
meta.error_map.remove(&ValidationEvent::Submit);
meta.error_map.remove(&ValidationEvent::Server);
meta.form_error_map.remove(&ValidationEvent::Submit);
meta.form_error_map.remove(&ValidationEvent::Server);
true
});
if !changed {
return;
}
let mut keys = vec![key.clone()];
keys.extend(form.read(cx).listeners(&key));
validate_keys(form, cx, &keys, ValidationEvent::Change);
}
pub(crate) fn blur<V: FormValues>(form: &Entity<FormInner<V>>, cx: &mut App, key: &SharedString) {
form.update(cx, |inner, _| {
let meta = inner.meta_mut(key);
meta.is_touched = true;
meta.is_blurred = true;
});
validate_keys(form, cx, std::slice::from_ref(key), ValidationEvent::Blur);
}
impl<F, T> FieldKey for FieldApi<F, T> {
fn field_key(&self) -> SharedString {
self.path.key().clone()
}
}