1use std::future::Future;
21use std::pin::Pin;
22
23use rustango::core::ModelSchema;
24use rustango::sql::Pool;
25use serde_json::Value;
26
27pub const CHOOSER_LIMIT: usize = 50;
29
30pub type SearchRowsFn = fn(Pool, String) -> Pin<Box<dyn Future<Output = Vec<Value>> + Send>>;
36
37pub struct ChooserViewSet {
39 pub slug: &'static str,
41 pub label: &'static str,
43 pub schema: &'static ModelSchema,
45 pub title_field: &'static str,
47 pub sub_field: &'static str,
49 pub search_rows: SearchRowsFn,
51}
52
53inventory::collect!(ChooserViewSet);
54
55#[must_use]
57pub fn registered() -> Vec<&'static ChooserViewSet> {
58 let mut v: Vec<_> = inventory::iter::<ChooserViewSet>.into_iter().collect();
59 v.sort_by_key(|c| c.slug);
60 v
61}
62
63#[must_use]
65pub fn find(slug: &str) -> Option<&'static ChooserViewSet> {
66 inventory::iter::<ChooserViewSet>
67 .into_iter()
68 .find(|c| c.slug == slug)
69}
70
71#[must_use]
78pub fn filter_and_normalize(
79 rows: Vec<Value>,
80 query: &str,
81 search_fields: &[&str],
82 title_field: &str,
83 sub_field: &str,
84 limit: usize,
85) -> Vec<Value> {
86 let needle = query.trim().to_lowercase();
87 rows.into_iter()
88 .filter(|row| {
89 if needle.is_empty() {
90 return true;
91 }
92 search_fields.iter().any(|f| {
93 row.get(*f)
94 .and_then(Value::as_str)
95 .is_some_and(|s| s.to_lowercase().contains(&needle))
96 })
97 })
98 .take(limit)
99 .map(|mut row| {
100 let title = field_string(&row, title_field);
101 let sub = field_string(&row, sub_field);
102 if let Value::Object(map) = &mut row {
103 map.insert("title".to_owned(), Value::String(title));
104 map.insert("sub".to_owned(), Value::String(sub));
105 }
106 row
107 })
108 .collect()
109}
110
111fn field_string(row: &Value, field: &str) -> String {
114 match row.get(field) {
115 Some(Value::String(s)) => s.clone(),
116 None | Some(Value::Null) => String::new(),
117 Some(other) => other.to_string(),
118 }
119}
120
121#[macro_export]
133macro_rules! register_chooser {
134 ($ty:ty, $slug:expr, $label:expr, $title_field:expr, $sub_field:expr $(,)?) => {
135 $crate::inventory::submit! {
136 $crate::admin::chooser::ChooserViewSet {
137 slug: $slug,
138 label: $label,
139 schema: <$ty as $crate::__private::Model>::SCHEMA,
140 title_field: $title_field,
141 sub_field: $sub_field,
142 search_rows: |pool: $crate::__private::Pool, query: ::std::string::String| {
143 ::std::boxed::Box::pin(async move {
144 use $crate::__private::FetcherPool as _;
145 use $crate::__private::Model as _;
146 let rows: ::std::vec::Vec<$ty> =
147 <$ty>::objects().fetch(&pool).await.unwrap_or_default();
148 let json_rows: ::std::vec::Vec<$crate::__private::serde_json::Value> = rows
149 .iter()
150 .filter_map(|r| $crate::__private::serde_json::to_value(r).ok())
151 .collect();
152 let search_fields: &[&str] = <$ty>::SCHEMA
153 .admin
154 .map(|a| a.search_fields)
155 .unwrap_or(&[]);
156 $crate::admin::chooser::filter_and_normalize(
157 json_rows,
158 &query,
159 search_fields,
160 $title_field,
161 $sub_field,
162 $crate::admin::chooser::CHOOSER_LIMIT,
163 )
164 })
165 },
166 }
167 }
168 };
169}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174 use serde_json::json;
175
176 crate::register_chooser!(
179 crate::locale::Locale,
180 "__test_locale",
181 "Test Locale",
182 "code",
183 "label"
184 );
185
186 #[test]
187 fn macro_registers_and_find_resolves() {
188 let cvs = find("__test_locale").expect("registered");
189 assert_eq!(cvs.label, "Test Locale");
190 assert_eq!(cvs.title_field, "code");
191 assert!(registered().iter().any(|c| c.slug == "__test_locale"));
192 }
193
194 fn rows() -> Vec<Value> {
195 vec![
196 json!({"id": 1, "code": "en", "label": "English"}),
197 json!({"id": 2, "code": "fr", "label": "French"}),
198 json!({"id": 3, "code": "es", "label": "Spanish"}),
199 ]
200 }
201
202 #[test]
203 fn empty_query_returns_all_normalized() {
204 let out = filter_and_normalize(rows(), "", &["code", "label"], "code", "label", 50);
205 assert_eq!(out.len(), 3);
206 assert_eq!(out[0]["id"], json!(1));
208 assert_eq!(out[0]["title"], json!("en"));
209 assert_eq!(out[0]["sub"], json!("English"));
210 }
211
212 #[test]
213 fn query_matches_any_search_field_case_insensitively() {
214 let out = filter_and_normalize(rows(), "SPA", &["code", "label"], "code", "label", 50);
216 assert_eq!(out.len(), 1);
217 assert_eq!(out[0]["id"], json!(3));
218 }
219
220 #[test]
221 fn query_only_searches_declared_fields() {
222 let out = filter_and_normalize(rows(), "english", &["code"], "code", "label", 50);
224 assert!(out.is_empty());
225 }
226
227 #[test]
228 fn limit_is_respected() {
229 let out = filter_and_normalize(rows(), "", &["code"], "code", "label", 2);
230 assert_eq!(out.len(), 2);
231 }
232
233 #[test]
234 fn missing_sub_field_normalizes_to_empty() {
235 let out = filter_and_normalize(rows(), "", &["code"], "code", "nonexistent", 50);
236 assert_eq!(out[0]["sub"], json!(""));
237 }
238}