Skip to main content

ignite_macros/
lib.rs

1//! Derive macro for Ignite resources: `#[derive(IgniteResource)]`.
2//!
3//! The derive reads an Orbit model and writes the `ignite_core::IgniteResource` impl that
4//! the panel needs: the form fields, the list columns, the query methods, and
5//! the input struct that create and update take. The model must also derive
6//! `OrbitModel` and `Serialize`, because the derive does not write them.
7
8use proc_macro::TokenStream;
9use proc_macro2::{Span, TokenStream as TokenStream2};
10use quote::{format_ident, quote};
11use syn::{
12    parse_macro_input, Data, DeriveInput, Fields, GenericArgument, LitBool, LitStr, PathArguments,
13    Token, Type,
14};
15
16/// Writes `impl ignite_core::IgniteResource` for a struct that models a table.
17///
18/// Struct attributes:
19/// - `#[ignite(table = widgets)]`: the table, required. Its name is the URL slug, and it must be the
20///   table of the model's `#[orbit(table = ...)]` (or the default name of the struct). A mismatch is a
21///   compile error.
22/// - `#[ignite(title = "Widgets")]`: the heading and nav label. Defaults to the table name, capitalized.
23/// - `#[ignite(singular = "Widget")]`: the name of one record, for "New Widget". Defaults to the title without a trailing `s`.
24/// - `#[ignite(navigation_label = "All widgets")]`: the label of the resource's navigation entry, as Filament's `$navigationLabel`. Defaults to the title.
25/// - `#[ignite(navigation_group = "Shop")]`: the navigation group the entry is listed under, as Filament's `$navigationGroup`. Defaults to none: the entry is listed before the groups.
26/// - `#[ignite(navigation_sort = 2)]`: the entry's place, as Filament's `$navigationSort`: lower first. Defaults to none, which comes before any number.
27/// - `#[ignite(navigation_parent_item = "Posts")]`: the navigation entry the resource is listed under, as Filament's `$navigationParentItem`: the parent's label or slug, in the same navigation group. Defaults to none: the resource is an entry of its own.
28/// - `#[ignite(navigation_icon = "post")]`: the name of the entry's icon, as Filament's `$navigationIcon`: what the resource is (`post`, `page`, `media`, `comment`, `users`, `settings`, or a name of the app's own), not a CSS class. The admin theme maps the name to its icon. Defaults to the theme's generic resource icon.
29/// - `#[ignite(conditions = post_conditions)]`: the conditions that show or hide the form's fields, and the live fields, as Filament's `visible()`, `hidden()` and `live()`: the path of a `fn() -> ignite_core::FieldConditions`. Defaults to none: every field shows. A field that a condition may hide should be an `Option`, so it is NULL on create and keeps its stored value on update.
30/// - `#[ignite(tabs = post_tabs)]`: the tabs of the list page, as Filament's `getTabs()`: the path of a `fn() -> Vec<ignite_core::Tab>`. The list query applies the active tab's conditions. Defaults to none: the list has no tabs.
31/// - `#[ignite(default_active_tab = "drafts")]`: the key of the tab shown when the list has no `tab` parameter, as Filament's `getDefaultActiveTab()`. Defaults to the first tab.
32/// - `#[ignite(badges = post_badges)]`: the list columns shown as coloured badges, as Filament's `badge()` and `color()` on a text column: the path of a `fn() -> ignite_core::ColumnBadges`. Defaults to none: every cell is plain text.
33/// - `#[ignite(form_layout = post_layout)]`: the layout of the create and edit forms, as Filament's `Grid`, `Section`, `Group`, `columns()` and `columnSpan()`: the path of a `fn() -> ignite_core::FormLayout`. Defaults to none: the form renders as one card of fields.
34///
35/// Field attributes:
36/// - `primary_key`: the key column. Defaults to a field named `id`.
37/// - `label = "..."`: the label. Defaults to the field name, capitalized and spaced.
38/// - `form_type = "text" | "textarea" | "password" | "number" | "checkbox" | "date"`: the input. Defaults from the type.
39/// - `form_type = "email" | "url" | "color" | "link" | "wysiwyg" | "image" | "file" | "gallery"`: the field types for custom fields (see `ignite_core::FieldKind`). The field must be a `String`; an `image` or `file` may also be an integer, the media item's id. A `link` and a `gallery` store JSON text.
40/// - `form_type = "radio"` with `options = [...]`: the choices as radio buttons. `form_type = "post_object" | "taxonomy" | "user"` with `options = load_choices` or `belongs_to`: a lookup of that kind. `form_type = "relationship"` with `options = load_choices`: several choices, stored as a JSON list in a `String`.
41/// - `form_type = "repeater" | "group" | "clone"` with `fields = SUB_FIELDS`, or `form_type = "flexible_content"` with `blocks = BLOCKS`: a structured field whose sub-fields are a `&'static [ignite_core::Field]` (or blocks a `&'static [ignite_core::Block]`) constant. The field must be a `String`, and stores JSON text.
42/// - `options = [("draft", "Draft"), ...]`: a select with a fixed list of choices. The field must be a `String`.
43/// - `options = load_choices`: a select whose choices come from an async function, `async fn(&Database) -> Result<Vec<(String, String)>, orbit_orm::Error>`, called each time the form is shown. The field must be a `String` or an integer.
44/// - `belongs_to = Category, display = name`: a relation. `Category` is the related model (an `OrbitModel`). The field stores the related row's key, the select lists the related table's rows by `display`, and the list shows that name. The field must be an `i32` or `i64`.
45/// - `step = "0.01"`: the browser's step for an `f32` or `f64` input. The default is `"any"`.
46/// - `required` or `required = false`: whether a blank value is rejected. An `Option` field is optional by default and `required` makes it required. A field that is not an `Option` is always required: `required = false` on it is a compile error (make it an `Option` instead). A `bool` is the exception: it is a checkbox and is never blank.
47/// - `searchable`, `sortable`: the list's search and sort columns.
48/// - `hidden_on_index`: leaves the column out of the list.
49///
50/// Supported field types: `String`, `i16`, `i32`, `i64`, `f32`, `f64`, `bool`,
51/// `chrono::NaiveDate`, `chrono::NaiveDateTime`, and `Option` of any of them. The primary
52/// key must be `i32` or `i64`. A `String` field is a text input (or a textarea, a password
53/// or a select, by attribute); an `f32` or `f64` is a decimal input; a `NaiveDateTime` is a
54/// date-and-time input; a `bool` is a checkbox.
55///
56/// Saving: create writes every field; an `Option` field left blank is NULL. Update writes
57/// every field the form sent: an `Option` field sent blank is written as NULL, so a user
58/// clears an optional value by emptying it on the edit form (since 0.3.0; before, a blank
59/// optional field was skipped on update and kept its value), and an `Option` field the form
60/// did not send at all is left out, so its stored value is kept. A password field is the
61/// exception: left blank on edit, it is not written, so the stored hash is kept. A checkbox
62/// is never blank: one the form did not send is `false`. A field that is not an `Option` is
63/// required. Errors are keyed by the field's name in `ignite_core::FieldErrors`, whose keys
64/// are owned `String`s since 0.3.0.
65///
66/// The generated input struct (`<Model>Input`) has a hidden `__ignite_sent` field that
67/// records which optional fields the form sent. `validate` and `validate_update` fill it.
68/// Code that builds the input with a struct literal must set it (since 0.3.0):
69/// `__ignite_sent: Vec::new()` keeps the stored value of every optional field that is `None`
70/// on update, and listing a field's name, as in `vec!["note"]`, writes NULL for it. An update
71/// that has nothing to write runs no query, and returns the row (or `NotFound`).
72#[proc_macro_derive(IgniteResource, attributes(ignite))]
73pub fn derive_ignite_resource(input: TokenStream) -> TokenStream {
74    let input = parse_macro_input!(input as DeriveInput);
75    match expand(&input) {
76        Ok(tokens) => tokens.into(),
77        Err(error) => error.to_compile_error().into(),
78    }
79}
80
81/// One field of the model, with its attributes resolved.
82struct Field {
83    ident: syn::Ident,
84    ty: Type,
85    /// The inner type, for `Option<T>`; otherwise the type itself.
86    inner: Type,
87    /// What the inner type parses from form text.
88    base: Base,
89    optional: bool,
90    kind: Kind,
91    label: String,
92    required: bool,
93    primary_key: bool,
94    searchable: bool,
95    sortable: bool,
96    hidden_on_index: bool,
97    /// A password: hashed on save, and blank on an edit keeps the stored hash.
98    is_password: bool,
99    /// The choices of a static select.
100    choices: Vec<(String, String)>,
101    /// Where a lookup field's choices come from.
102    lookup: Option<Lookup>,
103    /// The step of a decimal input, as written.
104    step: Option<String>,
105    /// The sub-fields of a repeater, group or clone, or the blocks of a flexible content
106    /// field: the path of a constant.
107    sub_fields: Option<syn::Path>,
108}
109
110#[derive(Clone, Copy, PartialEq, Eq)]
111enum Kind {
112    Text,
113    Textarea,
114    Password,
115    Number,
116    Decimal,
117    Checkbox,
118    Select,
119    Lookup,
120    Date,
121    DateTime,
122    Email,
123    Url,
124    Radio,
125    Color,
126    Image,
127    File,
128    Link,
129    Wysiwyg,
130    PostObject,
131    Relationship,
132    Taxonomy,
133    User,
134    Repeater,
135    Group,
136    FlexibleContent,
137    Gallery,
138    Clone,
139}
140
141impl Kind {
142    /// Whether `ignite_core::Field::check_value` checks the field's text: the kinds added
143    /// for custom fields, except the lookups stored as an integer.
144    fn checks_value(self) -> bool {
145        !matches!(
146            self,
147            Kind::Text
148                | Kind::Textarea
149                | Kind::Password
150                | Kind::Number
151                | Kind::Decimal
152                | Kind::Checkbox
153                | Kind::Select
154                | Kind::Lookup
155                | Kind::Date
156                | Kind::DateTime
157        )
158    }
159}
160
161/// The Rust base type the field parses from form text.
162#[derive(Clone, Copy, PartialEq, Eq)]
163enum Base {
164    Text,
165    Integer,
166    Decimal,
167    Bool,
168    Date,
169    DateTime,
170}
171
172/// The `options` attribute: fixed choices, or a function that loads them.
173enum OptionsSpec {
174    Static(Vec<(String, String)>),
175    Dynamic(syn::Path),
176}
177
178/// Where a lookup field's choices come from.
179enum Lookup {
180    /// A function that returns the choices.
181    Dynamic(syn::Path),
182    /// The rows of a related table: `id` as the value, the `display` column as the label.
183    Related {
184        table: syn::Path,
185        display: syn::Ident,
186    },
187}
188
189fn expand(input: &DeriveInput) -> syn::Result<TokenStream2> {
190    let name = &input.ident;
191    let vis = &input.vis;
192    let fields_data = match &input.data {
193        Data::Struct(data) => match &data.fields {
194            Fields::Named(named) => &named.named,
195            _ => {
196                return Err(syn::Error::new_spanned(
197                    name,
198                    "IgniteResource needs a struct with named fields",
199                ))
200            }
201        },
202        _ => {
203            return Err(syn::Error::new_spanned(
204                name,
205                "IgniteResource can only be derived for a struct",
206            ))
207        }
208    };
209
210    let (table, title, singular, latest, navigation, conditions, form_layout, list_attrs) =
211        struct_attrs(input)?;
212    let table_name = table
213        .segments
214        .last()
215        .map(|s| s.ident.to_string())
216        .unwrap_or_default();
217    let title = title.unwrap_or_else(|| capitalize(&table_name));
218    let singular =
219        singular.unwrap_or_else(|| title.strip_suffix('s').unwrap_or(&title).to_string());
220
221    let mut fields = Vec::new();
222    for field in fields_data {
223        fields.push(field_attrs(field)?);
224    }
225
226    let primary = fields
227        .iter()
228        .find(|f| f.primary_key)
229        .or_else(|| fields.iter().find(|f| f.ident == "id"))
230        .ok_or_else(|| syn::Error::new_spanned(name, "IgniteResource needs a primary key: a field named `id` or one marked `primary_key`"))?;
231    if !is_key_type(&primary.inner) {
232        return Err(syn::Error::new_spanned(
233            &primary.ty,
234            "the primary key must be an i32 or i64",
235        ));
236    }
237    let pk_ident = primary.ident.clone();
238    let pk_name = pk_ident.to_string();
239
240    let latest_records = match &latest {
241        Some(spec) => latest_records_tokens(spec, &fields, &title, name)?,
242        None => quote! { ::core::option::Option::None },
243    };
244
245    let navigation_consts = navigation.consts();
246    let conditions_method = conditions.map(|path| {
247        quote! {
248            fn conditions() -> ::ignite_core::FieldConditions {
249                #path()
250            }
251        }
252    });
253
254    let form_layout_method = form_layout.map(|path| {
255        quote! {
256            fn form_layout() -> ::ignite_core::FormLayout {
257                #path()
258            }
259        }
260    });
261
262    let list_methods = list_attrs.methods();
263
264    let form_fields: Vec<&Field> = fields.iter().filter(|f| f.ident != pk_ident).collect();
265    let input_name = format_ident!("{}Input", name);
266
267    for f in &form_fields {
268        if f.is_password && f.base != Base::Text {
269            return Err(syn::Error::new_spanned(
270                &f.ty,
271                "a password field must be a String (or Option<String>), so the derive can hash it",
272            ));
273        }
274        if !f.optional && !f.required && f.base != Base::Bool {
275            return Err(syn::Error::new_spanned(
276                &f.ty,
277                "a field that is not an Option is required; remove `required = false` or make the field an Option",
278            ));
279        }
280    }
281
282    let input_fields = form_fields.iter().map(|f| {
283        let ident = &f.ident;
284        // A password is Option<String> on input, so a blank edit leaves the column as it is.
285        if f.is_password {
286            quote! { pub #ident: ::core::option::Option<::std::string::String> }
287        } else {
288            let ty = &f.ty;
289            quote! { pub #ident: #ty }
290        }
291    });
292    // The optional fields whose absence from an update keeps the stored value: every
293    // `Option` that is not a password (a password has its own rule) or a checkbox (an
294    // unticked checkbox sends nothing, so absent means false).
295    let sent_names: Vec<String> = form_fields
296        .iter()
297        .filter(|f| tracks_sent(f))
298        .map(|f| f.ident.to_string())
299        .collect();
300    let input_struct = quote! {
301        #vis struct #input_name {
302            #(#input_fields,)*
303            /// The optional fields the form sent, blank or not. An update writes NULL for an
304            /// optional field sent blank, and leaves out one that was not sent, so its stored
305            /// value is kept. Filled by `validate` and `validate_update`.
306            #[doc(hidden)]
307            pub __ignite_sent: ::std::vec::Vec<&'static str>,
308        }
309    };
310
311    // The columns an insert or update writes, from the input struct.
312    let value_steps = form_fields.iter().map(|f| value_step(f));
313
314    let lookup_fields: Vec<&Field> = form_fields
315        .iter()
316        .copied()
317        .filter(|f| f.lookup.is_some())
318        .collect();
319    let options_fn = options_method(&lookup_fields);
320
321    let field_defs = form_fields.iter().map(|f| {
322        let name_lit = f.ident.to_string();
323        let label = &f.label;
324        let kind = kind_tokens(f);
325        let required = f.required;
326        quote! {
327            ::ignite_core::Field {
328                name: #name_lit,
329                label: #label,
330                kind: #kind,
331                required: #required,
332            }
333        }
334    });
335
336    let column_defs = fields
337        .iter()
338        .filter(|f| !f.hidden_on_index && !f.is_password)
339        .map(|f| {
340            let key = f.ident.to_string();
341            let label = &f.label;
342            let sortable = f.sortable;
343            let searchable = f.searchable;
344            quote! {
345                ::ignite_core::Column {
346                    key: #key,
347                    label: #label,
348                    sortable: #sortable,
349                    searchable: #searchable,
350                }
351            }
352        });
353
354    let searchable: Vec<String> = fields
355        .iter()
356        .filter(|f| f.searchable)
357        .map(|f| f.ident.to_string())
358        .collect();
359    // One LIKE per searchable column, joined with OR inside a group, as the search always was.
360    let search_filter = if searchable.is_empty() {
361        quote! {}
362    } else {
363        let first = &searchable[0];
364        let rest = &searchable[1..];
365        quote! {
366            if let ::core::option::Option::Some(pattern) = &pattern {
367                let like = |q: ::orbit_orm::Query<#name>| {
368                    q.where_group(|q| {
369                        q.where_op(#first, ::orbit_orm::Operator::Like, pattern.clone())
370                            #(.or_where_op(#rest, ::orbit_orm::Operator::Like, pattern.clone()))*
371                    })
372                };
373                rows = like(rows);
374                count = like(count);
375            }
376        }
377    };
378
379    let sort_arms = fields.iter().filter(|f| f.sortable).map(|f| {
380        let key = f.ident.to_string();
381        quote! { (::core::option::Option::Some(#key), true) => (#key, ::orbit_orm::Direction::Asc), (::core::option::Option::Some(#key), false) => (#key, ::orbit_orm::Direction::Desc), }
382    });
383
384    let validate_steps = form_fields.iter().map(|f| validate_expr(f));
385    let validate_idents: Vec<&syn::Ident> = form_fields.iter().map(|f| &f.ident).collect();
386    let validate_patterns = form_fields.iter().map(|f| {
387        let ident = &f.ident;
388        if f.optional || f.is_password {
389            quote! { #ident }
390        } else {
391            quote! { ::core::option::Option::Some(#ident) }
392        }
393    });
394
395    let table_check = quote! {
396        const _: () = ::core::assert!(
397            ::ignite_core::table_name_is(<#name as ::orbit_orm::Model>::TABLE, #table_name),
398            "the #[ignite(table = ...)] attribute must name the table of the model's #[orbit(table = ...)]"
399        );
400    };
401
402    Ok(quote! {
403        #table_check
404
405        #input_struct
406
407        impl #name {
408            /// The columns that an insert (`creating`) or an update write, from the input.
409            /// An `Option` that is `None` is written as NULL on create. On update it is written
410            /// as NULL when the form sent it blank, so a cleared optional field is cleared, and
411            /// skipped when the form did not send it. A blank password is skipped on update.
412            #[doc(hidden)]
413            #[allow(unused_mut)]
414            fn __ignite_values(
415                input: &#input_name,
416                creating: bool,
417            ) -> ::std::vec::Vec<(&'static str, ::orbit_orm::Value)> {
418                let _ = creating;
419                let mut values = ::std::vec::Vec::new();
420                #(#value_steps)*
421                values
422            }
423
424            /// Shared by `validate` and `validate_update`. `creating` decides
425            /// whether a blank password is an error.
426            #[doc(hidden)]
427            #[allow(clippy::nonminimal_bool, clippy::needless_bool)]
428            fn __ignite_validate(
429                form: &::ignite_core::FormInput,
430                creating: bool,
431            ) -> ::core::result::Result<#input_name, ::ignite_core::FieldErrors> {
432                let _ = creating;
433                let mut errors = ::ignite_core::FieldErrors::new();
434                #(#validate_steps)*
435                let __ignite_optional: &[&'static str] = &[#(#sent_names),*];
436                let __ignite_sent: ::std::vec::Vec<&'static str> = __ignite_optional
437                    .iter()
438                    .copied()
439                    .filter(|name| form.has(name))
440                    .collect();
441                match (#(#validate_idents,)*) {
442                    (#(#validate_patterns,)*) if errors.is_empty() => {
443                        ::core::result::Result::Ok(#input_name { #(#validate_idents,)* __ignite_sent })
444                    }
445                    _ => ::core::result::Result::Err(errors),
446                }
447            }
448        }
449
450        impl ::ignite_core::IgniteResource for #name {
451            type Record = #name;
452            type Input = #input_name;
453
454            const SLUG: &'static str = #table_name;
455            const TITLE: &'static str = #title;
456            const SINGULAR: &'static str = #singular;
457            #navigation_consts
458
459            fn fields() -> &'static [::ignite_core::Field] {
460                &[#(#field_defs),*]
461            }
462
463            fn columns() -> &'static [::ignite_core::Column] {
464                &[#(#column_defs),*]
465            }
466
467            async fn list(
468                db: &::ignite_core::Database,
469                query: &::ignite_core::ListQuery,
470            ) -> ::core::result::Result<::ignite_core::Page<#name>, ::orbit_orm::Error> {
471                let pattern = query
472                    .search
473                    .as_ref()
474                    .map(|s| format!("%{}%", ::ignite_core::escape_like(s)));
475                let mut rows = query.filter.apply(<#name as ::orbit_orm::Model>::query());
476                let mut count = query.filter.apply(<#name as ::orbit_orm::Model>::query());
477                #search_filter
478
479                let asc = !matches!(query.sort, ::core::option::Option::Some((_, ::ignite_core::Direction::Desc)));
480                let (column, direction) = match (query.sort.as_ref().map(|(k, _)| k.as_str()), asc) {
481                    #(#sort_arms)*
482                    _ => (#pk_name, ::orbit_orm::Direction::Asc),
483                };
484                rows = rows.order_by(column, direction);
485
486                let total = count.count(db).await?;
487                let rows = rows
488                    .limit(query.per_page.max(0) as u64)
489                    .offset(query.offset().max(0) as u64)
490                    .get(db)
491                    .await?;
492                Ok(::ignite_core::Page { rows, total })
493            }
494
495            async fn find(
496                db: &::ignite_core::Database,
497                id: i64,
498            ) -> ::core::result::Result<::core::option::Option<#name>, ::orbit_orm::Error> {
499                <#name as ::orbit_orm::Model>::query().find(db, id).await
500            }
501
502            fn latest_records() -> ::core::option::Option<::ignite_core::LatestRecords> {
503                #latest_records
504            }
505
506            #conditions_method
507            #form_layout_method
508            #list_methods
509
510            async fn latest(
511                db: &::ignite_core::Database,
512                limit: i64,
513            ) -> ::core::result::Result<::std::vec::Vec<#name>, ::orbit_orm::Error> {
514                <#name as ::orbit_orm::Model>::query()
515                    .order_by(#pk_name, ::orbit_orm::Direction::Desc)
516                    .limit(limit.max(0) as u64)
517                    .get(db)
518                    .await
519            }
520
521            async fn create(
522                db: &::ignite_core::Database,
523                input: #input_name,
524            ) -> ::core::result::Result<#name, ::orbit_orm::Error> {
525                let values = #name::__ignite_values(&input, true);
526                let id = <#name as ::orbit_orm::Model>::query().insert(db, &values).await?;
527                <#name as ::ignite_core::IgniteResource>::find(db, id as i64)
528                    .await?
529                    .ok_or(::orbit_orm::Error::NotFound { table: <#name as ::orbit_orm::Model>::TABLE })
530            }
531
532            async fn update(
533                db: &::ignite_core::Database,
534                id: i64,
535                input: #input_name,
536            ) -> ::core::result::Result<#name, ::orbit_orm::Error> {
537                let values = #name::__ignite_values(&input, false);
538                // An update that writes nothing (every field it has was not sent) succeeds
539                // without a query, and returns the row when it exists.
540                if !values.is_empty() {
541                    let changed = <#name as ::orbit_orm::Model>::query()
542                        .where_eq(#pk_name, id)
543                        .update(db, &values)
544                        .await?;
545                    if changed == 0 {
546                        return Err(::orbit_orm::Error::NotFound { table: <#name as ::orbit_orm::Model>::TABLE });
547                    }
548                }
549                <#name as ::ignite_core::IgniteResource>::find(db, id)
550                    .await?
551                    .ok_or(::orbit_orm::Error::NotFound { table: <#name as ::orbit_orm::Model>::TABLE })
552            }
553
554            async fn delete(
555                db: &::ignite_core::Database,
556                id: i64,
557            ) -> ::core::result::Result<u64, ::orbit_orm::Error> {
558                <#name as ::orbit_orm::Model>::query()
559                    .where_eq(#pk_name, id)
560                    .delete(db)
561                    .await
562            }
563
564            fn validate(
565                form: &::ignite_core::FormInput,
566            ) -> ::core::result::Result<#input_name, ::ignite_core::FieldErrors> {
567                #name::__ignite_validate(form, true)
568            }
569
570            fn validate_update(
571                form: &::ignite_core::FormInput,
572            ) -> ::core::result::Result<#input_name, ::ignite_core::FieldErrors> {
573                #name::__ignite_validate(form, false)
574            }
575
576            #options_fn
577        }
578    })
579}
580
581/// One block of the generated `__ignite_values`: pushes the column of `field`. An `Option`
582/// that is `None` is written as NULL on create. On update (since 0.3.0) it is written as NULL
583/// when the form sent it blank, so clearing an optional field on the edit form clears the
584/// stored value, and skipped when the form did not send it, so the stored value is kept, as
585/// Laravel's `update` with validated data leaves out a key the request did not have. A
586/// password is the exception: a blank one is NULL on create and skipped on update, so the
587/// stored hash is kept.
588fn value_step(field: &Field) -> TokenStream2 {
589    let ident = &field.ident;
590    let column = ident.to_string();
591    let convert = value_of(field.base, quote! { x });
592    // A password's input is an `Option` too, so a blank edit leaves the column alone.
593    if field.is_password {
594        quote! {
595            match &input.#ident {
596                ::core::option::Option::Some(x) => values.push((#column, #convert)),
597                ::core::option::Option::None if creating => values.push((#column, ::orbit_orm::Value::Null)),
598                ::core::option::Option::None => {}
599            }
600        }
601    } else if tracks_sent(field) {
602        quote! {
603            match &input.#ident {
604                ::core::option::Option::Some(x) => values.push((#column, #convert)),
605                ::core::option::Option::None if creating || input.__ignite_sent.contains(&#column) => {
606                    values.push((#column, ::orbit_orm::Value::Null))
607                }
608                ::core::option::Option::None => {}
609            }
610        }
611    } else if field.optional {
612        // An optional checkbox: always Some, as an unticked box is false.
613        quote! {
614            match &input.#ident {
615                ::core::option::Option::Some(x) => values.push((#column, #convert)),
616                ::core::option::Option::None => values.push((#column, ::orbit_orm::Value::Null)),
617            }
618        }
619    } else {
620        quote! {
621            {
622                let x = &input.#ident;
623                values.push((#column, #convert));
624            }
625        }
626    }
627}
628
629/// Whether an update keeps the stored value of `field` when the form does not send it: an
630/// `Option` that is neither a password nor a checkbox.
631fn tracks_sent(field: &Field) -> bool {
632    field.optional && !field.is_password && field.base != Base::Bool
633}
634
635/// The `Value` of a reference `x` to a field's base value.
636fn value_of(base: Base, x: TokenStream2) -> TokenStream2 {
637    match base {
638        Base::Text => quote! { ::orbit_orm::Value::from(#x.as_str()) },
639        Base::Integer => quote! { ::orbit_orm::Value::from(*#x as i64) },
640        Base::Decimal => quote! { ::orbit_orm::Value::from(*#x as f64) },
641        Base::Bool | Base::Date | Base::DateTime => quote! { ::orbit_orm::Value::from(*#x) },
642    }
643}
644
645/// The `#[ignite(latest_records(...))]` attribute, as written.
646struct LatestSpec {
647    /// The table heading. Defaults to "Latest" and the title.
648    title: Option<String>,
649    /// The most rows the dashboard table shows.
650    limit: i64,
651    /// Each column key, with the span of the string it came from.
652    columns: Vec<(String, Span)>,
653}
654
655/// The navigation attributes of the struct, as Filament's resource properties. Each one left
656/// out keeps the trait's default.
657#[derive(Default)]
658struct Navigation {
659    label: Option<String>,
660    group: Option<String>,
661    sort: Option<i32>,
662    parent_item: Option<String>,
663    icon: Option<String>,
664}
665
666impl Navigation {
667    /// The `NAVIGATION_*` constants of the attributes that were given.
668    fn consts(&self) -> TokenStream2 {
669        let label = self.label.as_ref().map(|label| {
670            quote! { const NAVIGATION_LABEL: ::core::option::Option<&'static str> = ::core::option::Option::Some(#label); }
671        });
672        let group = self.group.as_ref().map(|group| {
673            quote! { const NAVIGATION_GROUP: ::core::option::Option<&'static str> = ::core::option::Option::Some(#group); }
674        });
675        let sort = self.sort.map(|sort| {
676            quote! { const NAVIGATION_SORT: ::core::option::Option<i32> = ::core::option::Option::Some(#sort); }
677        });
678        let parent_item = self.parent_item.as_ref().map(|parent| {
679            quote! { const NAVIGATION_PARENT_ITEM: ::core::option::Option<&'static str> = ::core::option::Option::Some(#parent); }
680        });
681        let icon = self.icon.as_ref().map(|icon| {
682            quote! { const NAVIGATION_ICON: ::core::option::Option<&'static str> = ::core::option::Option::Some(#icon); }
683        });
684        quote! { #label #group #sort #parent_item #icon }
685    }
686}
687
688/// What the struct-level attributes give: the table, the title, the singular name, the
689/// dashboard table, the navigation, the paths of the functions that give the conditions
690/// and the form layout, and the list page's tabs and badges.
691type StructAttrs = (
692    syn::Path,
693    Option<String>,
694    Option<String>,
695    Option<LatestSpec>,
696    Navigation,
697    Option<syn::Path>,
698    Option<syn::Path>,
699    ListAttrs,
700);
701
702/// The list page's attributes: the tabs, the default tab and the badge columns.
703#[derive(Default)]
704struct ListAttrs {
705    tabs: Option<syn::Path>,
706    default_active_tab: Option<String>,
707    badges: Option<syn::Path>,
708}
709
710impl ListAttrs {
711    /// The `tabs`, `default_active_tab` and `column_badges` methods of the attributes given.
712    fn methods(&self) -> TokenStream2 {
713        let tabs = self.tabs.as_ref().map(|path| {
714            quote! {
715                fn tabs() -> ::std::vec::Vec<::ignite_core::Tab> {
716                    #path()
717                }
718            }
719        });
720        let default = self.default_active_tab.as_ref().map(|key| {
721            quote! {
722                fn default_active_tab() -> ::core::option::Option<&'static str> {
723                    ::core::option::Option::Some(#key)
724                }
725            }
726        });
727        let badges = self.badges.as_ref().map(|path| {
728            quote! {
729                fn column_badges() -> ::ignite_core::ColumnBadges {
730                    #path()
731                }
732            }
733        });
734        quote! { #tabs #default #badges }
735    }
736}
737
738/// Reads `#[ignite(...)]` on the struct: the table, the title, the singular name, the
739/// dashboard table, the navigation, the conditions and the form layout.
740fn struct_attrs(input: &DeriveInput) -> syn::Result<StructAttrs> {
741    let mut table = None;
742    let mut title = None;
743    let mut singular = None;
744    let mut latest = None;
745    let mut navigation = Navigation::default();
746    let mut conditions = None;
747    let mut form_layout = None;
748    let mut list = ListAttrs::default();
749    for attr in input.attrs.iter().filter(|a| a.path().is_ident("ignite")) {
750        attr.parse_nested_meta(|meta| {
751            if meta.path.is_ident("table") {
752                table = Some(meta.value()?.parse::<syn::Path>()?);
753                Ok(())
754            } else if meta.path.is_ident("title") {
755                title = Some(meta.value()?.parse::<LitStr>()?.value());
756                Ok(())
757            } else if meta.path.is_ident("singular") {
758                singular = Some(meta.value()?.parse::<LitStr>()?.value());
759                Ok(())
760            } else if meta.path.is_ident("latest_records") {
761                latest = Some(latest_spec(&meta)?);
762                Ok(())
763            } else if meta.path.is_ident("navigation_label") {
764                navigation.label = Some(meta.value()?.parse::<LitStr>()?.value());
765                Ok(())
766            } else if meta.path.is_ident("navigation_group") {
767                navigation.group = Some(meta.value()?.parse::<LitStr>()?.value());
768                Ok(())
769            } else if meta.path.is_ident("navigation_parent_item") {
770                navigation.parent_item = Some(meta.value()?.parse::<LitStr>()?.value());
771                Ok(())
772            } else if meta.path.is_ident("navigation_icon") {
773                let icon = meta.value()?.parse::<LitStr>()?;
774                let name = icon.value();
775                // Before 0.6.2 the value was CSS classes, such as `dashicons dashicons-admin-post`.
776                if name.trim().is_empty() || name.chars().any(char::is_whitespace) {
777                    return Err(syn::Error::new(
778                        icon.span(),
779                        "`navigation_icon` takes an icon name such as \"post\", \"media\" or \"settings\", which the admin theme maps to its icon, not CSS classes",
780                    ));
781                }
782                navigation.icon = Some(name);
783                Ok(())
784            } else if meta.path.is_ident("navigation_sort") {
785                navigation.sort = Some(sort_value(&meta.value()?.parse::<syn::Expr>()?)?);
786                Ok(())
787            } else if meta.path.is_ident("conditions") {
788                conditions = Some(meta.value()?.parse::<syn::Path>()?);
789                Ok(())
790            } else if meta.path.is_ident("form_layout") {
791                form_layout = Some(meta.value()?.parse::<syn::Path>()?);
792                Ok(())
793            } else if meta.path.is_ident("tabs") {
794                list.tabs = Some(meta.value()?.parse::<syn::Path>()?);
795                Ok(())
796            } else if meta.path.is_ident("default_active_tab") {
797                list.default_active_tab = Some(meta.value()?.parse::<LitStr>()?.value());
798                Ok(())
799            } else if meta.path.is_ident("badges") {
800                list.badges = Some(meta.value()?.parse::<syn::Path>()?);
801                Ok(())
802            } else {
803                Err(meta.error(
804                    "unknown ignite attribute on the struct; expected `table`, `title`, `singular`, `latest_records`, `navigation_label`, `navigation_group`, `navigation_sort`, `navigation_parent_item`, `navigation_icon`, `conditions`, `form_layout`, `tabs`, `default_active_tab` or `badges`",
805                ))
806            }
807        })?;
808    }
809    let table = table.ok_or_else(|| {
810        syn::Error::new_spanned(
811            &input.ident,
812            "IgniteResource needs #[ignite(table = <table name>)]",
813        )
814    })?;
815    Ok((
816        table,
817        title,
818        singular,
819        latest,
820        navigation,
821        conditions,
822        form_layout,
823        list,
824    ))
825}
826
827/// The `i32` of a `navigation_sort` value: an integer literal, or a negative one such as `-1`.
828fn sort_value(expr: &syn::Expr) -> syn::Result<i32> {
829    match expr {
830        syn::Expr::Lit(syn::ExprLit {
831            lit: syn::Lit::Int(int),
832            ..
833        }) => int.base10_parse::<i32>(),
834        syn::Expr::Unary(syn::ExprUnary {
835            op: syn::UnOp::Neg(_),
836            expr: inner,
837            ..
838        }) => match inner.as_ref() {
839            syn::Expr::Lit(syn::ExprLit {
840                lit: syn::Lit::Int(int),
841                ..
842            }) => format!("-{}", int.base10_digits())
843                .parse::<i32>()
844                .map_err(|_| syn::Error::new_spanned(expr, "navigation_sort must fit in an i32")),
845            _ => Err(syn::Error::new_spanned(
846                expr,
847                "navigation_sort takes a whole number",
848            )),
849        },
850        _ => Err(syn::Error::new_spanned(
851            expr,
852            "navigation_sort takes a whole number",
853        )),
854    }
855}
856
857/// Reads `latest_records(limit = 5, columns = "name,email", title = "...")`.
858fn latest_spec(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<LatestSpec> {
859    let mut title = None;
860    let mut limit = 5i64;
861    let mut columns = None;
862    meta.parse_nested_meta(|inner| {
863        if inner.path.is_ident("limit") {
864            let value: syn::LitInt = inner.value()?.parse()?;
865            limit = value.base10_parse::<i64>()?;
866            if limit < 1 {
867                return Err(syn::Error::new(value.span(), "limit must be at least 1"));
868            }
869            Ok(())
870        } else if inner.path.is_ident("columns") {
871            let list: LitStr = inner.value()?.parse()?;
872            let span = list.span();
873            let names: Vec<(String, Span)> = list
874                .value()
875                .split(',')
876                .map(|name| (name.trim().to_string(), span))
877                .collect();
878            columns = Some(names);
879            Ok(())
880        } else if inner.path.is_ident("title") {
881            title = Some(inner.value()?.parse::<LitStr>()?.value());
882            Ok(())
883        } else {
884            Err(inner.error("latest_records takes limit, columns and title"))
885        }
886    })?;
887    let columns = columns.ok_or_else(|| {
888        meta.error(
889            "latest_records needs columns = \"name,email\": the columns the dashboard table shows",
890        )
891    })?;
892    Ok(LatestSpec {
893        title,
894        limit,
895        columns,
896    })
897}
898
899/// Writes the body of `latest_records()` from the attribute, after checking each
900/// column: it must be a field of the model, and it must not be a password.
901fn latest_records_tokens(
902    spec: &LatestSpec,
903    fields: &[Field],
904    title: &str,
905    name: &syn::Ident,
906) -> syn::Result<TokenStream2> {
907    let mut keys = Vec::new();
908    for (key, span) in &spec.columns {
909        if key.is_empty() {
910            return Err(syn::Error::new(
911                *span,
912                "latest_records has an empty column name",
913            ));
914        }
915        let field = fields
916            .iter()
917            .find(|f| f.ident == key.as_str())
918            .ok_or_else(|| syn::Error::new(*span, format!("`{key}` is not a field of {name}")))?;
919        if field.is_password {
920            return Err(syn::Error::new(
921                *span,
922                format!("`{key}` is a password and cannot be shown on the dashboard"),
923            ));
924        }
925        keys.push(key.clone());
926    }
927    let table_title = spec
928        .title
929        .clone()
930        .unwrap_or_else(|| format!("Latest {title}"));
931    let limit = spec.limit;
932    Ok(quote! {
933        ::core::option::Option::Some(::ignite_core::LatestRecords {
934            title: #table_title,
935            columns: &[#(#keys),*],
936            limit: #limit,
937        })
938    })
939}
940
941/// Reads the `#[ignite(...)]` attributes of a field and resolves its defaults.
942fn field_attrs(field: &syn::Field) -> syn::Result<Field> {
943    let ident = field
944        .ident
945        .clone()
946        .ok_or_else(|| syn::Error::new_spanned(field, "IgniteResource needs named fields"))?;
947    let ty = field.ty.clone();
948    let (optional, inner) = match option_inner(&ty) {
949        Some(inner) => (true, inner.clone()),
950        None => (false, ty.clone()),
951    };
952    let base = base_of(&inner).ok_or_else(|| {
953        syn::Error::new_spanned(
954            &ty,
955            "unsupported field type: use String, i16, i32, i64, f32, f64, bool, chrono::NaiveDate, chrono::NaiveDateTime, or Option of one",
956        )
957    })?;
958
959    let mut label = None;
960    let mut form_type = None;
961    let mut required_attr = None;
962    let mut primary_key = false;
963    let mut searchable = false;
964    let mut sortable = false;
965    let mut hidden_on_index = false;
966    let mut options = None;
967    let mut belongs_to = None;
968    let mut display = None;
969    let mut step = None;
970    let mut sub_fields = None;
971    let mut blocks = None;
972    for attr in field.attrs.iter().filter(|a| a.path().is_ident("ignite")) {
973        attr.parse_nested_meta(|meta| {
974            if meta.path.is_ident("label") {
975                label = Some(meta.value()?.parse::<LitStr>()?.value());
976            } else if meta.path.is_ident("form_type") {
977                form_type = Some(meta.value()?.parse::<LitStr>()?);
978            } else if meta.path.is_ident("required") {
979                let value = if meta.input.peek(Token![=]) {
980                    meta.value()?.parse::<LitBool>()?.value
981                } else {
982                    true
983                };
984                required_attr = Some(value);
985            } else if meta.path.is_ident("primary_key") {
986                primary_key = true;
987            } else if meta.path.is_ident("searchable") {
988                searchable = true;
989            } else if meta.path.is_ident("sortable") {
990                sortable = true;
991            } else if meta.path.is_ident("hidden_on_index") {
992                hidden_on_index = true;
993            } else if meta.path.is_ident("options") {
994                let expr: syn::Expr = meta.value()?.parse()?;
995                options = Some(options_of(&expr)?);
996            } else if meta.path.is_ident("belongs_to") {
997                belongs_to = Some(meta.value()?.parse::<syn::Path>()?);
998            } else if meta.path.is_ident("display") {
999                display = Some(meta.value()?.parse::<syn::Ident>()?);
1000            } else if meta.path.is_ident("step") {
1001                step = Some(meta.value()?.parse::<LitStr>()?);
1002            } else if meta.path.is_ident("fields") {
1003                sub_fields = Some(meta.value()?.parse::<syn::Path>()?);
1004            } else if meta.path.is_ident("blocks") {
1005                blocks = Some(meta.value()?.parse::<syn::Path>()?);
1006            } else {
1007                return Err(meta.error(
1008                    "unknown ignite attribute; expected label, form_type, required, primary_key, searchable, sortable, hidden_on_index, options, belongs_to, display, step, fields or blocks",
1009                ));
1010            }
1011            Ok(())
1012        })?;
1013    }
1014
1015    // Options and a relation both make a select, so neither takes a form_type of its own,
1016    // except the kinds that are a select by another name: radio buttons for fixed options,
1017    // and a post object, taxonomy, user or relationship for loaded ones.
1018    let lookup_attr = options.is_some() || belongs_to.is_some();
1019    let choice_kind = match form_type.as_ref().map(|s| s.value()).as_deref() {
1020        Some("radio") if matches!(options, Some(OptionsSpec::Static(_))) => Some(Kind::Radio),
1021        Some("post_object") if lookup_attr && !matches!(options, Some(OptionsSpec::Static(_))) => {
1022            Some(Kind::PostObject)
1023        }
1024        Some("taxonomy") if lookup_attr && !matches!(options, Some(OptionsSpec::Static(_))) => {
1025            Some(Kind::Taxonomy)
1026        }
1027        Some("user") if lookup_attr && !matches!(options, Some(OptionsSpec::Static(_))) => {
1028            Some(Kind::User)
1029        }
1030        Some("relationship") if matches!(options, Some(OptionsSpec::Dynamic(_))) => {
1031            Some(Kind::Relationship)
1032        }
1033        _ => None,
1034    };
1035    if lookup_attr && form_type.is_some() && choice_kind.is_none() {
1036        return Err(syn::Error::new_spanned(
1037            &ty,
1038            "a field with options or belongs_to is a select: remove form_type",
1039        ));
1040    }
1041    if belongs_to.is_some() != display.is_some() {
1042        return Err(syn::Error::new_spanned(
1043            &ty,
1044            "belongs_to and display go together: belongs_to = <model type>, display = <column>",
1045        ));
1046    }
1047    if options.is_some() && belongs_to.is_some() {
1048        return Err(syn::Error::new_spanned(
1049            &ty,
1050            "a field takes options or belongs_to, not both",
1051        ));
1052    }
1053
1054    let mut choices = Vec::new();
1055    let mut lookup = None;
1056    let kind = if let Some(spec) = options {
1057        match spec {
1058            OptionsSpec::Static(pairs) => {
1059                if base != Base::Text {
1060                    return Err(syn::Error::new_spanned(
1061                        &ty,
1062                        "a field with a list of options must be a String (or Option<String>)",
1063                    ));
1064                }
1065                choices = pairs;
1066                choice_kind.unwrap_or(Kind::Select)
1067            }
1068            OptionsSpec::Dynamic(path) => {
1069                if !matches!(base, Base::Text | Base::Integer) {
1070                    return Err(syn::Error::new_spanned(
1071                        &ty,
1072                        "a field with options from a function must be a String or an integer",
1073                    ));
1074                }
1075                if choice_kind == Some(Kind::Relationship) && base != Base::Text {
1076                    return Err(syn::Error::new_spanned(
1077                        &ty,
1078                        "a relationship stores a JSON list, so it must be a String (or Option<String>)",
1079                    ));
1080                }
1081                lookup = Some(Lookup::Dynamic(path));
1082                choice_kind.unwrap_or(Kind::Lookup)
1083            }
1084        }
1085    } else if let Some(table) = belongs_to {
1086        if base != Base::Integer {
1087            return Err(syn::Error::new_spanned(
1088                &ty,
1089                "a belongs_to field stores the related row's id, so it must be an i32 or i64",
1090            ));
1091        }
1092        lookup = Some(Lookup::Related {
1093            table,
1094            display: display
1095                .clone()
1096                .expect("checked: display is set with belongs_to"),
1097        });
1098        choice_kind.unwrap_or(Kind::Lookup)
1099    } else {
1100        match form_type.as_ref().map(|s| s.value()) {
1101            None => match base {
1102                Base::Bool => Kind::Checkbox,
1103                Base::Integer => Kind::Number,
1104                Base::Decimal => Kind::Decimal,
1105                Base::Date => Kind::Date,
1106                Base::DateTime => Kind::DateTime,
1107                Base::Text => Kind::Text,
1108            },
1109            Some(value) => match value.as_str() {
1110                "text" => Kind::Text,
1111                "textarea" => Kind::Textarea,
1112                "password" => Kind::Password,
1113                "number" if base == Base::Decimal => Kind::Decimal,
1114                "number" => Kind::Number,
1115                "checkbox" => Kind::Checkbox,
1116                "date" => Kind::Date,
1117                "email" => Kind::Email,
1118                "url" => Kind::Url,
1119                "color" => Kind::Color,
1120                "image" => Kind::Image,
1121                "file" => Kind::File,
1122                "link" => Kind::Link,
1123                "wysiwyg" => Kind::Wysiwyg,
1124                "gallery" => Kind::Gallery,
1125                "repeater" => Kind::Repeater,
1126                "group" => Kind::Group,
1127                "clone" => Kind::Clone,
1128                "flexible_content" => Kind::FlexibleContent,
1129                "radio" | "post_object" | "taxonomy" | "user" | "relationship" => {
1130                    return Err(syn::Error::new(
1131                        form_type.map(|s| s.span()).unwrap_or_else(Span::call_site),
1132                        "form_type radio takes options = [...]; post_object, taxonomy and user take options = <function> or belongs_to; relationship takes options = <function>",
1133                    ))
1134                }
1135                _ => return Err(syn::Error::new(
1136                    form_type.map(|s| s.span()).unwrap_or_else(Span::call_site),
1137                    "form_type must be one of text, textarea, password, number, checkbox, date, email, url, color, image, file, link, wysiwyg, gallery, radio, post_object, taxonomy, user, relationship, repeater, group, clone or flexible_content",
1138                )),
1139            },
1140        }
1141    };
1142
1143    // A structured field names its sub-fields (or blocks), and only it does.
1144    let sub_fields = match kind {
1145        Kind::Repeater | Kind::Group | Kind::Clone => match (sub_fields, blocks) {
1146            (Some(path), None) => Some(path),
1147            _ => {
1148                return Err(syn::Error::new_spanned(
1149                    &ty,
1150                    "a repeater, group or clone takes fields = <a &'static [ignite_core::Field] constant>",
1151                ))
1152            }
1153        },
1154        Kind::FlexibleContent => match (blocks, sub_fields) {
1155            (Some(path), None) => Some(path),
1156            _ => {
1157                return Err(syn::Error::new_spanned(
1158                    &ty,
1159                    "a flexible_content field takes blocks = <a &'static [ignite_core::Block] constant>",
1160                ))
1161            }
1162        },
1163        _ if sub_fields.is_some() || blocks.is_some() => {
1164            return Err(syn::Error::new_spanned(
1165                &ty,
1166                "fields and blocks apply to a repeater, group, clone or flexible_content field",
1167            ))
1168        }
1169        _ => None,
1170    };
1171    // The kinds for custom fields store text, except a media id, which may be an integer.
1172    let text_kind =
1173        kind.checks_value() && !matches!(kind, Kind::PostObject | Kind::Taxonomy | Kind::User);
1174    if text_kind
1175        && base != Base::Text
1176        && !(matches!(kind, Kind::Image | Kind::File) && base == Base::Integer)
1177    {
1178        return Err(syn::Error::new_spanned(
1179            &ty,
1180            "this form_type stores text, so the field must be a String (or Option<String>); an image or file may also be an integer",
1181        ));
1182    }
1183
1184    if step.is_some() && base != Base::Decimal {
1185        return Err(syn::Error::new_spanned(
1186            &ty,
1187            "step applies to an f32 or f64 field",
1188        ));
1189    }
1190
1191    // A checkbox is never blank, so it is not required unless asked.
1192    let required = required_attr.unwrap_or(!optional && base != Base::Bool);
1193    let label = label.unwrap_or_else(|| capitalize(&ident.to_string().replace('_', " ")));
1194
1195    Ok(Field {
1196        ident,
1197        ty,
1198        inner,
1199        base,
1200        optional,
1201        kind,
1202        label,
1203        required,
1204        primary_key,
1205        searchable,
1206        sortable,
1207        hidden_on_index,
1208        is_password: kind == Kind::Password,
1209        choices,
1210        lookup,
1211        step: step.map(|s| s.value()),
1212        sub_fields,
1213    })
1214}
1215
1216/// The `options = ...` attribute: a list of `("value", "Label")` pairs, or the path of a
1217/// function that returns the choices from the database.
1218fn options_of(expr: &syn::Expr) -> syn::Result<OptionsSpec> {
1219    match expr {
1220        syn::Expr::Array(array) => {
1221            let mut pairs = Vec::new();
1222            for element in &array.elems {
1223                let syn::Expr::Tuple(tuple) = element else {
1224                    return Err(syn::Error::new_spanned(
1225                        element,
1226                        "each option is a pair, such as (\"draft\", \"Draft\")",
1227                    ));
1228                };
1229                let [value, label] = tuple.elems.iter().collect::<Vec<_>>()[..] else {
1230                    return Err(syn::Error::new_spanned(
1231                        tuple,
1232                        "each option is a pair, such as (\"draft\", \"Draft\")",
1233                    ));
1234                };
1235                pairs.push((string_literal(value)?, string_literal(label)?));
1236            }
1237            Ok(OptionsSpec::Static(pairs))
1238        }
1239        syn::Expr::Path(path) => Ok(OptionsSpec::Dynamic(path.path.clone())),
1240        _ => Err(syn::Error::new_spanned(
1241            expr,
1242            "options is a list of (\"value\", \"Label\") pairs, or the path of a function that returns them",
1243        )),
1244    }
1245}
1246
1247/// The text of a string literal, or an error at the expression.
1248fn string_literal(expr: &syn::Expr) -> syn::Result<String> {
1249    match expr {
1250        syn::Expr::Lit(syn::ExprLit {
1251            lit: syn::Lit::Str(text),
1252            ..
1253        }) => Ok(text.value()),
1254        _ => Err(syn::Error::new_spanned(expr, "expected a string literal")),
1255    }
1256}
1257
1258/// The type inside `Option<T>`, if the type is one.
1259fn option_inner(ty: &Type) -> Option<&Type> {
1260    let Type::Path(path) = ty else { return None };
1261    let segment = path.path.segments.last()?;
1262    if segment.ident != "Option" {
1263        return None;
1264    }
1265    let PathArguments::AngleBracketed(args) = &segment.arguments else {
1266        return None;
1267    };
1268    match args.args.first()? {
1269        GenericArgument::Type(inner) => Some(inner),
1270        _ => None,
1271    }
1272}
1273
1274/// What a supported base type parses from form text, or `None` if it is unsupported.
1275fn base_of(ty: &Type) -> Option<Base> {
1276    let Type::Path(path) = ty else { return None };
1277    let ident = path.path.segments.last()?.ident.to_string();
1278    match ident.as_str() {
1279        "String" => Some(Base::Text),
1280        "i16" | "i32" | "i64" => Some(Base::Integer),
1281        "f32" | "f64" => Some(Base::Decimal),
1282        "bool" => Some(Base::Bool),
1283        "NaiveDate" => Some(Base::Date),
1284        "NaiveDateTime" => Some(Base::DateTime),
1285        _ => None,
1286    }
1287}
1288
1289/// Whether a primary key has a type the query methods accept: `i32` or `i64`.
1290fn is_key_type(ty: &Type) -> bool {
1291    let Type::Path(path) = ty else { return false };
1292    path.path
1293        .segments
1294        .last()
1295        .is_some_and(|s| matches!(s.ident.to_string().as_str(), "i32" | "i64"))
1296}
1297
1298/// The `FieldKind` a field's form input has, as tokens.
1299fn kind_tokens(field: &Field) -> TokenStream2 {
1300    match field.kind {
1301        Kind::Text => quote! { ::ignite_core::FieldKind::Text },
1302        Kind::Textarea => quote! { ::ignite_core::FieldKind::Textarea },
1303        Kind::Password => quote! { ::ignite_core::FieldKind::Password },
1304        Kind::Number => quote! { ::ignite_core::FieldKind::Number },
1305        Kind::Decimal => {
1306            let step = field.step.as_deref().unwrap_or("any");
1307            quote! { ::ignite_core::FieldKind::Decimal(#step) }
1308        }
1309        Kind::Checkbox => quote! { ::ignite_core::FieldKind::Checkbox },
1310        Kind::Select => {
1311            let pairs = choice_pairs(&field.choices);
1312            quote! { ::ignite_core::FieldKind::Select(&[#(#pairs),*]) }
1313        }
1314        Kind::Lookup => quote! { ::ignite_core::FieldKind::Lookup },
1315        Kind::Date => quote! { ::ignite_core::FieldKind::Date },
1316        Kind::DateTime => quote! { ::ignite_core::FieldKind::DateTime },
1317        Kind::Email => quote! { ::ignite_core::FieldKind::Email },
1318        Kind::Url => quote! { ::ignite_core::FieldKind::Url },
1319        Kind::Radio => {
1320            let pairs = choice_pairs(&field.choices);
1321            quote! { ::ignite_core::FieldKind::Radio(&[#(#pairs),*]) }
1322        }
1323        Kind::Color => quote! { ::ignite_core::FieldKind::Color },
1324        Kind::Image => quote! { ::ignite_core::FieldKind::Image },
1325        Kind::File => quote! { ::ignite_core::FieldKind::File },
1326        Kind::Link => quote! { ::ignite_core::FieldKind::Link },
1327        Kind::Wysiwyg => quote! { ::ignite_core::FieldKind::Wysiwyg },
1328        Kind::PostObject => quote! { ::ignite_core::FieldKind::PostObject },
1329        Kind::Relationship => quote! { ::ignite_core::FieldKind::Relationship },
1330        Kind::Taxonomy => quote! { ::ignite_core::FieldKind::Taxonomy },
1331        Kind::User => quote! { ::ignite_core::FieldKind::User },
1332        Kind::Gallery => quote! { ::ignite_core::FieldKind::Gallery },
1333        Kind::Repeater | Kind::Group | Kind::Clone | Kind::FlexibleContent => {
1334            let path = field
1335                .sub_fields
1336                .as_ref()
1337                .expect("checked: a structured field has its sub-fields");
1338            match field.kind {
1339                Kind::Repeater => quote! { ::ignite_core::FieldKind::Repeater(#path) },
1340                Kind::Group => quote! { ::ignite_core::FieldKind::Group(#path) },
1341                Kind::Clone => quote! { ::ignite_core::FieldKind::Clone(#path) },
1342                _ => quote! { ::ignite_core::FieldKind::FlexibleContent(#path) },
1343            }
1344        }
1345    }
1346}
1347
1348/// The `(value, label)` tuples of a static list of options.
1349fn choice_pairs(choices: &[(String, String)]) -> Vec<TokenStream2> {
1350    choices
1351        .iter()
1352        .map(|(value, label)| quote! { (#value, #label) })
1353        .collect()
1354}
1355
1356/// One `let` in `validate`: reads the field from the form into an `Option` of its base value,
1357/// and records an error when the value is blank (required) or does not parse.
1358fn validate_expr(field: &Field) -> TokenStream2 {
1359    let ident = &field.ident;
1360    let name = ident.to_string();
1361    let label = &field.label;
1362    let kind = kind_tokens(field);
1363    let required = field.required;
1364    let base = field.base;
1365    let is_password = field.is_password;
1366    let ty = &field.inner;
1367
1368    let convert = match base {
1369        Base::Text if is_password => {
1370            let message = "Could not save this password.".to_string();
1371            quote! {
1372                match ::ignite_core::hash_password(text) {
1373                    Ok(hash) => ::core::option::Option::Some(hash),
1374                    Err(_) => {
1375                        errors.insert(#name.to_string(), #message.to_string());
1376                        ::core::option::Option::None
1377                    }
1378                }
1379            }
1380        }
1381        Base::Text if field.kind == Kind::Select => {
1382            let pairs = choice_pairs(&field.choices);
1383            quote! {
1384                {
1385                    let text = text.trim();
1386                    let choices: &[(&str, &str)] = &[#(#pairs),*];
1387                    if field.check_choice(text, choices, &mut errors) {
1388                        ::core::option::Option::Some(text.to_string())
1389                    } else {
1390                        ::core::option::Option::None
1391                    }
1392                }
1393            }
1394        }
1395        // The kinds for custom fields: the text their check returns.
1396        Base::Text if field.kind.checks_value() => quote! { field.check_value(text, &mut errors) },
1397        Base::Text => quote! { ::core::option::Option::Some(text.to_string()) },
1398        Base::Bool => quote! { ::core::option::Option::Some(form.checkbox(#name)) },
1399        // A media id stored as an integer: checked as a media id, then parsed.
1400        Base::Integer if matches!(field.kind, Kind::Image | Kind::File) => quote! {
1401            field
1402                .check_value(text, &mut errors)
1403                .and_then(|id| id.parse::<#ty>().ok())
1404        },
1405        Base::Integer => quote! { field.check_whole_number::<#ty>(text, &mut errors) },
1406        Base::Decimal => quote! { field.check_decimal::<#ty>(text, &mut errors) },
1407        Base::Date => quote! { field.check_date(text, &mut errors) },
1408        Base::DateTime => quote! { field.check_datetime(text, &mut errors) },
1409    };
1410
1411    // Booleans are never blank: an unticked checkbox is false.
1412    if base == Base::Bool {
1413        return quote! { let #ident = #convert; };
1414    }
1415
1416    // A password is required only when creating. On an edit a blank password
1417    // keeps the stored hash.
1418    quote! {
1419        let #ident = {
1420            let field = ::ignite_core::Field { name: #name, label: #label, kind: #kind, required: #required };
1421            let present = if #required && (creating || !#is_password) {
1422                field.check_required(form, &mut errors)
1423            } else {
1424                form.get(#name)
1425            };
1426            match present {
1427                ::core::option::Option::Some(text) => { let text: &str = text; #convert }
1428                ::core::option::Option::None => ::core::option::Option::None,
1429            }
1430        };
1431    }
1432}
1433
1434/// The `options` method, which the panel calls for each lookup field. It is written
1435/// only when the model has one, so the trait's default serves the rest.
1436fn options_method(lookups: &[&Field]) -> TokenStream2 {
1437    if lookups.is_empty() {
1438        return quote! {};
1439    }
1440    let arms = lookups.iter().map(|f| {
1441        let name_lit = f.ident.to_string();
1442        match f.lookup.as_ref().expect("checked: a lookup field") {
1443            Lookup::Dynamic(path) => quote! { #name_lit => #path(db).await, },
1444            Lookup::Related { table, display } => {
1445                let key_ty = &f.inner;
1446                let display_lit = display.to_string();
1447                quote! {
1448                    #name_lit => {
1449                        let rows: ::std::vec::Vec<(#key_ty, ::std::string::String)> =
1450                            <#table as ::orbit_orm::Model>::query()
1451                                .select(&[<#table as ::orbit_orm::Model>::PRIMARY_KEY, #display_lit])
1452                                .order_by(#display_lit, ::orbit_orm::Direction::Asc)
1453                                .get_as(db)
1454                                .await?;
1455                        ::core::result::Result::Ok(
1456                            rows.into_iter().map(|(id, label)| (id.to_string(), label)).collect(),
1457                        )
1458                    }
1459                }
1460            }
1461        }
1462    });
1463    quote! {
1464        async fn options(
1465            db: &::ignite_core::Database,
1466            field: &str,
1467        ) -> ::core::result::Result<::std::vec::Vec<(::std::string::String, ::std::string::String)>, ::orbit_orm::Error> {
1468            match field {
1469                #(#arms)*
1470                _ => ::core::result::Result::Ok(::std::vec::Vec::new()),
1471            }
1472        }
1473    }
1474}
1475
1476fn capitalize(text: &str) -> String {
1477    let mut chars = text.chars();
1478    match chars.next() {
1479        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
1480        None => String::new(),
1481    }
1482}