tablo-core 0.7.0

The core toolkit types for Tablo, a server-rendered admin toolkit on Topcoat and Toasty.
Documentation
//! [`EmbeddedColumn`]: an embedded value read off the record, one leaf at a time.

use std::sync::{Arc, OnceLock};

use derive_where::derive_where;
use topcoat::{context::Cx, view::*};

use super::{Column, ColumnBase, ColumnWidth};
use crate::{
    Lens,
    form::FormValues,
    schema::{EmbeddedForm, FieldResolver, Schema},
};

/// A column of an [`EmbeddedForm`] value.
///
/// A detail page shows each of the value's leaves under its own label; an enum shows its variant's
/// name and that variant's leaves only. A table cell lists the same leaves as `label: value`.
///
/// ```rust
/// # #[derive(Debug, Clone, toasty::Embed, tablo_core::EmbeddedForm)]
/// # struct Seo { title: String, description: String }
/// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
/// # struct Post { #[key] #[auto] id: uuid::Uuid, seo: Seo }
/// tablo_core::EmbeddedColumn::new(tablo_core::lens!(Post.seo));
/// ```
///
/// The value's leaves resolve through the app schema, which the column reads when it binds: a
/// panel binds the declarations it mounts, and [`Detail::bind`](crate::Detail::bind) binds one
/// built outside a panel.
#[derive_where(Clone, Debug)]
pub struct EmbeddedColumn<M, T> {
    lens: Lens<M, T>,
    base: ColumnBase,
    /// The value's schema, built when the column binds.
    schema: Arc<OnceLock<Schema>>,
}

impl<M, T> EmbeddedColumn<M, T>
where
    M: toasty::schema::Model,
    T: EmbeddedForm,
{
    /// Bind the column to the embedded value `lens` reads.
    pub fn new(lens: Lens<M, T>) -> Self {
        Self {
            base: ColumnBase::new(lens.path(), ColumnWidth::Wide),
            lens,
            schema: Arc::default(),
        }
    }

    base_builders!();

    /// The value's schema and its leaves as the form spells them, once the column is bound.
    fn spelled(&self, row: &M) -> Option<(&Schema, FormValues)> {
        let schema = self.schema.get()?;
        let mut values = FormValues::new();
        self.lens
            .read(row)
            .write_node(schema.embedded_root(), &mut values);
        Some((schema, values))
    }
}

impl<M, T> Column<M> for EmbeddedColumn<M, T>
where
    M: toasty::schema::Model + Send + Sync + 'static,
    T: EmbeddedForm + Send + Sync + 'static,
{
    base_column_methods!();

    fn text(&self, _cx: &Cx, row: &M) -> String {
        let Some((schema, values)) = self.spelled(row) else {
            return String::new();
        };
        schema
            .embedded_root()
            .shown(&schema.fields, &values)
            .into_iter()
            .filter_map(|index| {
                let field = &schema.fields[index];
                let value = values.text(field.name()).unwrap_or_default();
                let read = field.read(value)?;
                Some(format!("{}: {read}", field.label_str()))
            })
            .collect::<Vec<_>>()
            .join(", ")
    }

    fn entry<'a>(&self, cx: &'a Cx, row: &M) -> BoxView<'a> {
        match self.spelled(row) {
            Some((schema, values)) => schema.embedded_root().display(cx, &schema.fields, &values),
            None => ().boxed(),
        }
    }

    fn misdeclared(&self) -> Option<crate::DeclarationErrorKind> {
        if let Some(error) = self.base.binding.misdeclared() {
            return Some(error);
        }
        match self.schema.get() {
            Some(schema) => schema.declaration_errors().into_iter().next(),
            None => Some(crate::DeclarationErrorKind::Unbound {
                item: std::any::type_name::<T>(),
            }),
        }
    }

    fn bind(&self, resolver: &FieldResolver) {
        self.base.binding.bind(resolver);
        self.schema
            .get_or_init(|| T::build_schema(resolver, self.lens.path().clone()));
    }
}