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