Skip to main content

rustango_cms/admin/
chooser.rs

1//! Generic chooser registry — register a chooser for any
2//! `#[derive(Model)]` type, generalising the three hand-rolled choosers
3//! (page / snippet / document).
4//!
5//! A host registers with
6//! [`register_chooser!`](crate::register_chooser!)`(Ty, "slug", "Label", "title_field", "sub_field")`;
7//! the admin then serves `/cms-admin/__chooser/<slug>?q=…` returning the
8//! same `{ "items": [ { id, title, sub, … } ] }` shape the bespoke
9//! choosers use. The editor's chooser overlay (`cms-ux.js`) resolves an
10//! unregistered `data-chooser-kind` to this endpoint automatically, so a
11//! registered chooser needs **no** JavaScript change — a widget just
12//! sets its slug as the kind.
13//!
14//! Search runs over the model's `admin(search_fields = …)` (the same
15//! metadata the framework admin uses), matched case-insensitively as a
16//! substring on each declared field — mirroring the in-memory filter the
17//! bespoke choosers already do. A dedicated form `WidgetKind` for model
18//! choosers is the natural next step.
19
20use std::future::Future;
21use std::pin::Pin;
22
23use rustango::core::ModelSchema;
24use rustango::sql::Pool;
25use serde_json::Value;
26
27/// Cap on returned rows — matches the bespoke choosers' limit.
28pub const CHOOSER_LIMIT: usize = 50;
29
30/// Type-erased "search rows as normalised chooser items". Built by
31/// [`register_chooser!`](crate::register_chooser!) from the concrete model's
32/// `objects().fetch()` + its schema `search_fields` (the fetch is a
33/// derive-generated inherent method, so it can't be reached generically —
34/// hence the thunk, same shape as [`crate::admin::model_admin`]).
35pub type SearchRowsFn = fn(Pool, String) -> Pin<Box<dyn Future<Output = Vec<Value>> + Send>>;
36
37/// One registered chooser.
38pub struct ChooserViewSet {
39    /// URL slug under `/cms-admin/__chooser/<slug>` + the chooser kind.
40    pub slug: &'static str,
41    /// Human-readable singular label (dialog heading).
42    pub label: &'static str,
43    /// The model's schema — exposes `search_fields` + `display`.
44    pub schema: &'static ModelSchema,
45    /// Row field shown as the item title.
46    pub title_field: &'static str,
47    /// Row field shown as the secondary (sub) line.
48    pub sub_field: &'static str,
49    /// Search the model + normalise rows to `{id, title, sub, …}`.
50    pub search_rows: SearchRowsFn,
51}
52
53inventory::collect!(ChooserViewSet);
54
55/// Every registered chooser, sorted by slug.
56#[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/// The chooser registered under `slug`, if any.
64#[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/// Filter already-serialized `rows` by `query` (case-insensitive
72/// substring over `search_fields`), cap at `limit`, and normalise each
73/// to carry a `title` + `sub` key (from `title_field` / `sub_field`)
74/// alongside its original fields. An empty / blank query returns the
75/// first `limit` rows. Pure — the [`register_chooser!`](crate::register_chooser!) thunk and the
76/// unit tests both call it.
77#[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
111/// A row field as a display string: strings bare, null / missing empty,
112/// everything else its compact JSON.
113fn 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/// Register a generic chooser for a `#[derive(Model)]` type.
122///
123/// ```ignore
124/// rustango_cms::register_chooser!(crate::Author, "author", "Author", "name", "email");
125/// // → /cms-admin/__chooser/author?q=… ; a widget with
126/// //   data-chooser-kind="author" drives it via the shared overlay.
127/// ```
128///
129/// The model must derive `serde::Serialize` (rows are serialised to JSON
130/// for the search filter). Search uses the model's
131/// `admin(search_fields = …)`.
132#[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    // Dogfood the macro on a real CMS model to prove it compiles +
177    // registers (Locale has `admin(search_fields = …)`).
178    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        // Each item carries id + title (title_field) + sub (sub_field).
207        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        // "spa" matches the label "Spanish".
215        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        // "english" is in `label`, but if we don't declare label, no match.
223        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}