rok-ui 0.9.2

shadcn/ui-style component system for GPUI desktop apps, with a React-like developer experience.
Documentation
//! Typed paths into form values.

use std::{fmt, marker::PhantomData, rc::Rc};

use gpui::SharedString;

/// A field of a struct, generated by `#[derive(FormValues)]` as an associated constant:
/// `SignUp::EMAIL` is a `Field<SignUp, String>`.
pub struct Field<F, T> {
    name: &'static str,
    get: fn(&F) -> &T,
    get_mut: fn(&mut F) -> &mut T,
}

impl<F, T> Field<F, T> {
    /// A field named `name` with its accessors. `#[derive(FormValues)]` writes these.
    #[must_use]
    pub const fn new(name: &'static str, get: fn(&F) -> &T, get_mut: fn(&mut F) -> &mut T) -> Self {
        Self { name, get, get_mut }
    }

    /// The field's name.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        self.name
    }
}

impl<F, T> Clone for Field<F, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<F, T> Copy for Field<F, T> {}

impl<F, T> fmt::Debug for Field<F, T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "Field({})", self.name)
    }
}

type Getter<F, T> = Rc<dyn Fn(&F) -> Option<&T>>;
type GetterMut<F, T> = Rc<dyn Fn(&mut F) -> Option<&mut T>>;

/// A path from form values `F` to a value `T`, possibly through nested structs and list items:
/// `SignUp::TEAM.at(0).then(Invite::EMAIL)` is the first invite's email, keyed `team.0.email`.
pub struct Path<F, T> {
    key: SharedString,
    get: Getter<F, T>,
    get_mut: GetterMut<F, T>,
    _types: PhantomData<fn(F) -> T>,
}

impl<F, T> Path<F, T> {
    /// The path as text: `email`, `team.0.email`. Errors and field state are keyed by it.
    #[must_use]
    pub fn key(&self) -> &SharedString {
        &self.key
    }

    /// The value at this path, if it exists (a list item may have been removed).
    #[must_use]
    pub fn get<'a>(&self, values: &'a F) -> Option<&'a T> {
        (self.get)(values)
    }

    /// The value at this path, mutably.
    pub fn get_mut<'a>(&self, values: &'a mut F) -> Option<&'a mut T> {
        (self.get_mut)(values)
    }
}

impl<F: 'static, T: 'static> Path<F, T> {
    /// Continue into a field of `T`.
    #[must_use]
    pub fn then<U: 'static>(&self, next: impl Into<Path<T, U>>) -> Path<F, U> {
        let next = next.into();
        let (get, get_mut) = (self.get.clone(), self.get_mut.clone());
        let (next_get, next_get_mut) = (next.get.clone(), next.get_mut.clone());
        Path {
            key: format!("{}.{}", self.key, next.key).into(),
            get: Rc::new(move |values| get(values).and_then(|value| next_get(value))),
            get_mut: Rc::new(move |values| get_mut(values).and_then(|value| next_get_mut(value))),
            _types: PhantomData,
        }
    }
}

impl<F: 'static, E: 'static> Path<F, Vec<E>> {
    /// The list item at `index`.
    #[must_use]
    pub fn at(&self, index: usize) -> Path<F, E> {
        let (get, get_mut) = (self.get.clone(), self.get_mut.clone());
        Path {
            key: format!("{}.{index}", self.key).into(),
            get: Rc::new(move |values| get(values).and_then(|list| list.get(index))),
            get_mut: Rc::new(move |values| get_mut(values).and_then(|list| list.get_mut(index))),
            _types: PhantomData,
        }
    }
}

impl<F: 'static, T: 'static> Field<F, T> {
    /// Continue into a field of `T`.
    #[must_use]
    pub fn then<U: 'static>(self, next: impl Into<Path<T, U>>) -> Path<F, U> {
        Path::from(self).then(next)
    }
}

impl<F: 'static, E: 'static> Field<F, Vec<E>> {
    /// The list item at `index`.
    #[must_use]
    pub fn at(self, index: usize) -> Path<F, E> {
        Path::from(self).at(index)
    }
}

impl<F: 'static, T: 'static> From<Field<F, T>> for Path<F, T> {
    fn from(field: Field<F, T>) -> Self {
        let (get, get_mut) = (field.get, field.get_mut);
        Self {
            key: field.name.into(),
            get: Rc::new(move |values| Some(get(values))),
            get_mut: Rc::new(move |values| Some(get_mut(values))),
            _types: PhantomData,
        }
    }
}

impl<F, T> Clone for Path<F, T> {
    fn clone(&self) -> Self {
        Self {
            key: self.key.clone(),
            get: self.get.clone(),
            get_mut: self.get_mut.clone(),
            _types: PhantomData,
        }
    }
}

impl<F, T> fmt::Debug for Path<F, T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "Path({})", self.key)
    }
}

/// Anything that names a field: a [`Field`] constant or a [`Path`].
pub trait FieldKey {
    /// The path as text.
    fn field_key(&self) -> SharedString;
}

impl<F, T> FieldKey for Field<F, T> {
    fn field_key(&self) -> SharedString {
        self.name.into()
    }
}

impl<F, T> FieldKey for Path<F, T> {
    fn field_key(&self) -> SharedString {
        self.key.clone()
    }
}

/// Values a form edits, implemented with `#[derive(FormValues)]`, which also generates a
/// [`Field`] constant per struct field (`email` becomes `EMAIL`).
pub trait FormValues: Clone + 'static {}