use std::future::Future;
use std::pin::Pin;
use rustango::core::ModelSchema;
use rustango::sql::Pool;
use serde_json::Value;
pub const CHOOSER_LIMIT: usize = 50;
pub type SearchRowsFn = fn(Pool, String) -> Pin<Box<dyn Future<Output = Vec<Value>> + Send>>;
pub struct ChooserViewSet {
pub slug: &'static str,
pub label: &'static str,
pub schema: &'static ModelSchema,
pub title_field: &'static str,
pub sub_field: &'static str,
pub search_rows: SearchRowsFn,
}
inventory::collect!(ChooserViewSet);
#[must_use]
pub fn registered() -> Vec<&'static ChooserViewSet> {
let mut v: Vec<_> = inventory::iter::<ChooserViewSet>.into_iter().collect();
v.sort_by_key(|c| c.slug);
v
}
#[must_use]
pub fn find(slug: &str) -> Option<&'static ChooserViewSet> {
inventory::iter::<ChooserViewSet>
.into_iter()
.find(|c| c.slug == slug)
}
#[must_use]
pub fn filter_and_normalize(
rows: Vec<Value>,
query: &str,
search_fields: &[&str],
title_field: &str,
sub_field: &str,
limit: usize,
) -> Vec<Value> {
let needle = query.trim().to_lowercase();
rows.into_iter()
.filter(|row| {
if needle.is_empty() {
return true;
}
search_fields.iter().any(|f| {
row.get(*f)
.and_then(Value::as_str)
.is_some_and(|s| s.to_lowercase().contains(&needle))
})
})
.take(limit)
.map(|mut row| {
let title = field_string(&row, title_field);
let sub = field_string(&row, sub_field);
if let Value::Object(map) = &mut row {
map.insert("title".to_owned(), Value::String(title));
map.insert("sub".to_owned(), Value::String(sub));
}
row
})
.collect()
}
fn field_string(row: &Value, field: &str) -> String {
match row.get(field) {
Some(Value::String(s)) => s.clone(),
None | Some(Value::Null) => String::new(),
Some(other) => other.to_string(),
}
}
#[macro_export]
macro_rules! register_chooser {
($ty:ty, $slug:expr, $label:expr, $title_field:expr, $sub_field:expr $(,)?) => {
$crate::inventory::submit! {
$crate::admin::chooser::ChooserViewSet {
slug: $slug,
label: $label,
schema: <$ty as $crate::__private::Model>::SCHEMA,
title_field: $title_field,
sub_field: $sub_field,
search_rows: |pool: $crate::__private::Pool, query: ::std::string::String| {
::std::boxed::Box::pin(async move {
use $crate::__private::FetcherPool as _;
use $crate::__private::Model as _;
let rows: ::std::vec::Vec<$ty> =
<$ty>::objects().fetch(&pool).await.unwrap_or_default();
let json_rows: ::std::vec::Vec<$crate::__private::serde_json::Value> = rows
.iter()
.filter_map(|r| $crate::__private::serde_json::to_value(r).ok())
.collect();
let search_fields: &[&str] = <$ty>::SCHEMA
.admin
.map(|a| a.search_fields)
.unwrap_or(&[]);
$crate::admin::chooser::filter_and_normalize(
json_rows,
&query,
search_fields,
$title_field,
$sub_field,
$crate::admin::chooser::CHOOSER_LIMIT,
)
})
},
}
}
};
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
crate::register_chooser!(
crate::locale::Locale,
"__test_locale",
"Test Locale",
"code",
"label"
);
#[test]
fn macro_registers_and_find_resolves() {
let cvs = find("__test_locale").expect("registered");
assert_eq!(cvs.label, "Test Locale");
assert_eq!(cvs.title_field, "code");
assert!(registered().iter().any(|c| c.slug == "__test_locale"));
}
fn rows() -> Vec<Value> {
vec![
json!({"id": 1, "code": "en", "label": "English"}),
json!({"id": 2, "code": "fr", "label": "French"}),
json!({"id": 3, "code": "es", "label": "Spanish"}),
]
}
#[test]
fn empty_query_returns_all_normalized() {
let out = filter_and_normalize(rows(), "", &["code", "label"], "code", "label", 50);
assert_eq!(out.len(), 3);
assert_eq!(out[0]["id"], json!(1));
assert_eq!(out[0]["title"], json!("en"));
assert_eq!(out[0]["sub"], json!("English"));
}
#[test]
fn query_matches_any_search_field_case_insensitively() {
let out = filter_and_normalize(rows(), "SPA", &["code", "label"], "code", "label", 50);
assert_eq!(out.len(), 1);
assert_eq!(out[0]["id"], json!(3));
}
#[test]
fn query_only_searches_declared_fields() {
let out = filter_and_normalize(rows(), "english", &["code"], "code", "label", 50);
assert!(out.is_empty());
}
#[test]
fn limit_is_respected() {
let out = filter_and_normalize(rows(), "", &["code"], "code", "label", 2);
assert_eq!(out.len(), 2);
}
#[test]
fn missing_sub_field_normalizes_to_empty() {
let out = filter_and_normalize(rows(), "", &["code"], "code", "nonexistent", 50);
assert_eq!(out[0]["sub"], json!(""));
}
}