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