use toasty::stmt::Expr;
use crate::{Lens, form::FormScalar, table::contains_expr};
pub(crate) struct RecordTitle<M> {
read: Box<dyn Fn(&M) -> String + Send + Sync>,
search: TitleSearch,
pub(crate) field: Option<String>,
}
type TitleSearch = Box<dyn Fn(&str) -> Option<Expr<bool>> + Send + Sync>;
impl<M: toasty::schema::Model + Send + Sync + 'static> RecordTitle<M> {
pub(super) fn new<T>(lens: Lens<M, T>) -> Self
where
T: FormScalar + toasty::schema::Field<Inner = String> + Send + Sync + 'static,
{
let path = lens.clone();
let field = crate::toasty_compat::model::root_field::<M>(
&crate::toasty_compat::model::ModelPath::of(lens.path()),
);
Self {
read: Box::new(move |record| lens.read(record).to_form()),
search: Box::new(move |term| contains_expr(&path, term)),
field,
}
}
pub(crate) fn read(&self, record: &M) -> Option<String> {
Some((self.read)(record)).filter(|title| !title.trim().is_empty())
}
pub(crate) fn search_expr(&self, term: &str) -> Option<Expr<bool>> {
(self.search)(term)
}
}