ignite-core 0.7.3

Core types for Ignite, the admin panel for Rocket.rs: resources, fields, forms and runtime resources.
Documentation
//! The trait a table implements to be managed by the admin panel.

use std::future::Future;

use orbit_orm::{Database, Error};
use serde::Serialize;

use crate::action::{BulkAction, RowAction};
use crate::condition::FieldConditions;
use crate::field::{Column, Field};
use crate::form::{FieldErrors, FormInput};
use crate::layout::FormLayout;
use crate::list::{ColumnBadges, ListFilter, Tab};
use crate::policy::ActingUser;
use crate::query::{ListQuery, Page};
use crate::widget::{LatestRecords, Stat, StatWidget};

/// The navigation parents of a resource: `parent` (its `NAVIGATION_PARENT_ITEM`), then
/// `more` (its `NAVIGATION_PARENT_ITEMS`), in order, each once, without blank names.
pub fn navigation_parents<'a>(
    parent: Option<&'a str>,
    more: impl IntoIterator<Item = &'a str>,
) -> Vec<&'a str> {
    let mut parents: Vec<&str> = Vec::new();
    for name in parent.into_iter().chain(more) {
        if !name.trim().is_empty() && !parents.contains(&name) {
            parents.push(name);
        }
    }
    parents
}

/// Checks at compile time that `table` is `expected`. The derive uses it to check that the
/// `table` attribute names the same table as the Orbit model's `TABLE`.
pub const fn table_name_is(table: &str, expected: &str) -> bool {
    let (a, b) = (table.as_bytes(), expected.as_bytes());
    if a.len() != b.len() {
        return false;
    }
    let mut i = 0;
    while i < a.len() {
        if a[i] != b[i] {
            return false;
        }
        i += 1;
    }
    true
}

/// A table of records the panel can list, create, edit and delete.
///
/// Implement it by hand, or with `#[derive(IgniteResource)]`. The panel calls the query methods
/// with the app's [`Database`], and renders the forms from [`fields`](Self::fields) and the list
/// from [`columns`](Self::columns). The query methods are async, so each returns a future.
pub trait IgniteResource: Send + Sync + 'static {
    /// One row, as the database returns it. It must serialize to JSON with
    /// field names matching `fields()` and `columns()`.
    type Record: Serialize + Send;
    /// Validated form input for create and update.
    type Input: Send;

    /// URL segment: `"users"` mounts the resource at `/admin/users`.
    const SLUG: &'static str;
    /// Heading and navigation label: `"Users"`.
    const TITLE: &'static str;
    /// The name of one record, for headings such as "New User" (added in v1).
    const SINGULAR: &'static str = "Record";
    /// Rows per page on the list view.
    const PER_PAGE: i64 = 20;
    /// The label of the resource's navigation entry, as Filament's `$navigationLabel`. The
    /// default, `None`, is the [`TITLE`](Self::TITLE).
    const NAVIGATION_LABEL: Option<&'static str> = None;
    /// The navigation group the resource is listed under, as Filament's `$navigationGroup`:
    /// the group's name, shown as a heading in the sidebar. The panel's `navigation_groups`
    /// orders the groups. The default, `None`, lists the resource before the groups, as
    /// Filament lists ungrouped items first.
    const NAVIGATION_GROUP: Option<&'static str> = None;
    /// The resource's place in the navigation, as Filament's `$navigationSort`: a lower number
    /// comes first. The default, `None`, comes before any number. In a group, resources with
    /// the same place are listed by label; without a group, in the order they were added.
    const NAVIGATION_SORT: Option<i32> = None;
    /// The navigation entry the resource is listed under, as Filament's
    /// `$navigationParentItem`: the parent's navigation label (or its slug, as Filament also
    /// takes the parent's class). The entry shows under its parent, as a submenu does, sorted
    /// among the other children by [`NAVIGATION_SORT`](Self::NAVIGATION_SORT). As in Filament,
    /// the parent must be in the same navigation group and must not be a child itself, and an
    /// entry whose parent is not in the sidebar (unknown, or one the user may not see) is not
    /// listed. The default, `None`, lists the resource as an entry of its own.
    const NAVIGATION_PARENT_ITEM: Option<&'static str> = None;
    /// More navigation entries the resource is listed under, each by its label or slug, as
    /// [`NAVIGATION_PARENT_ITEM`](Self::NAVIGATION_PARENT_ITEM) names one: the entry is
    /// listed under each of these parents that the sidebar shows, as a WordPress taxonomy's
    /// screen is listed under every post type it is attached to. Filament takes one parent
    /// item; this is Ignite's addition, and it keeps Filament's rule that a parent is in the
    /// same navigation group. The parents are [`NAVIGATION_PARENT_ITEM`](Self::NAVIGATION_PARENT_ITEM)
    /// first, then these, in order, each once. An entry none of whose parents the sidebar
    /// shows is not listed. The default, none, keeps the single parent (or none).
    const NAVIGATION_PARENT_ITEMS: &'static [&'static str] = &[];
    /// Whether the resource has a navigation entry, as Filament's `$shouldRegisterNavigation`
    /// (and WordPress's `show_in_menu => false`). `false` leaves the entry out of the sidebar,
    /// and with it the entries listed only under it; the resource's pages still answer, so
    /// guard them with its policy. The default, `true`, lists it.
    const SHOULD_REGISTER_NAVIGATION: bool = true;
    /// The name of the resource's navigation icon, as Filament's `$navigationIcon`: a name
    /// that says what the resource is, such as `"post"`, `"page"`, `"media"`, `"comment"`,
    /// `"users"` or `"settings"`, or a name of the app's own, such as a custom post type's
    /// `"book"`. It is not a CSS class: the active admin theme maps the name to its own icon
    /// (the `ignite` theme to a Tabler icon, a WordPress-like theme to a Dashicon), and shows
    /// its generic resource icon for a name it does not know. The default, `None`, shows the
    /// theme's generic resource icon.
    const NAVIGATION_ICON: Option<&'static str> = None;
    /// Whether the resource's navigation entry lists a link to its create page, as a Filament
    /// resource has a create page (`getUrl('create')`). The link is part of the entry's group in
    /// the sidebar: it is listed under the entry, before its child entries, and shows and hides
    /// with them. It is listed only for a user who may create a record. The default, `true`,
    /// lists it; `false` leaves it out, such as for a taxonomy whose terms are added elsewhere.
    const NAVIGATION_CREATE_ITEM: bool = true;
    /// The label of the create link ([`NAVIGATION_CREATE_ITEM`](Self::NAVIGATION_CREATE_ITEM)),
    /// such as `"Add New Post"`. The default is `"Add new"`.
    const NAVIGATION_CREATE_LABEL: &'static str = "Add new";

    /// Stat cards for the dashboard, in display order. The default is none.
    /// Override it to show counts, such as the total number of rows.
    fn widgets(db: &Database) -> impl Future<Output = Result<Vec<StatWidget>, Error>> + Send {
        let _ = db;
        async { Ok(Vec::new()) }
    }

    /// The dashboard cards of the resource for the signed-in `user`, as the stats of a
    /// Filament stats overview widget: each [`Stat`] has a title, a value and an optional
    /// description. The panel shows them only to a user who may view the resource's records.
    /// The default is the cards of [`widgets`](Self::widgets), so a resource that implements
    /// `widgets` shows them as before.
    fn stats(
        db: &Database,
        user: &ActingUser,
    ) -> impl Future<Output = Result<Vec<Stat>, Error>> + Send {
        let _ = user;
        async move {
            Ok(Self::widgets(db)
                .await?
                .into_iter()
                .map(Stat::from)
                .collect())
        }
    }

    /// The dashboard table of the newest records, or `None` for no table (added in v1).
    fn latest_records() -> Option<LatestRecords> {
        None
    }

    /// Up to `limit` records, newest first (added in v1). The panel calls it with the
    /// `limit` of [`latest_records`](Self::latest_records). The default is no records.
    fn latest(
        db: &Database,
        limit: i64,
    ) -> impl Future<Output = Result<Vec<Self::Record>, Error>> + Send {
        let _ = (db, limit);
        async { Ok(Vec::new()) }
    }

    /// Form fields, in display order.
    fn fields() -> &'static [Field];
    /// Table columns, in display order. Each column's `key` is a field name.
    fn columns() -> &'static [Column];

    /// The conditions that show or hide the form's fields, and the live fields, as Filament's
    /// `visible()`, `hidden()` and `live()` (see [`FieldConditions`]). The panel reads them
    /// once, when it is built. The default is none: every field shows. `#[derive(IgniteResource)]`
    /// writes it for `#[ignite(conditions = path)]`.
    ///
    /// The panel removes a hidden field from the submitted form before it calls
    /// [`validate`](Self::validate) or [`validate_update`](Self::validate_update), so a field
    /// that may be hidden must be one `validate` accepts as missing, such as an `Option` field
    /// of the derive: left out on update, it keeps its stored value.
    fn conditions() -> FieldConditions {
        FieldConditions::new()
    }

    /// The layout of the create and edit forms: the grid's columns, and the sections and
    /// groups that place the fields in it, as a Filament resource's `form()` schema with
    /// `Grid`, `Section`, `Group`, `columns()` and `columnSpan()` (see [`FormLayout`]). The
    /// panel reads it once, when it is built. The default has no layout: the form renders as
    /// one card of fields, as before.
    fn form_layout() -> FormLayout {
        FormLayout::new()
    }

    /// The settings of the form's repeaters and flexible content fields, by path, as
    /// Filament's `minItems()`, `maxItems()` and `itemLabel()` (see
    /// [`Repeaters`](crate::Repeaters)). The panel reads them once, when it is built. The
    /// default has none: every repeater has the default settings. A static resource checks
    /// the row counts in its own `validate`, with
    /// [`Field::check_value_in`](crate::Field::check_value_in).
    fn repeaters() -> crate::Repeaters {
        crate::Repeaters::new()
    }

    /// The tabs of the list page, in display order, as Filament's `getTabs()` on a List page:
    /// each [`Tab`] has a key, a label and the conditions its rows meet, and shows the number
    /// of rows it matches (see [`tab_counts_follow_search`](Self::tab_counts_follow_search)). The
    /// list's `tab` query parameter chooses
    /// one. The panel reads them once, when it is built. The default is none: the list has no
    /// tabs, as before. `#[derive(IgniteResource)]` writes it for `#[ignite(tabs = path)]`.
    fn tabs() -> Vec<Tab> {
        Vec::new()
    }

    /// The key of the tab a list request without a `tab` parameter shows, as Filament's
    /// `getDefaultActiveTab()`. The default, `None` (or a key that is not a tab), is the first
    /// tab. `#[derive(IgniteResource)]` writes it for `#[ignite(default_active_tab = "key")]`.
    fn default_active_tab() -> Option<&'static str> {
        None
    }

    /// Whether each tab's count is for the current search. The default, `false`, counts every
    /// row of the tab, whatever the search, as a Filament tab's `badge()` counts its own query,
    /// which the table's search does not narrow; the list itself still shows only the rows
    /// that match. Without a search the counts are the same either way.
    /// `#[derive(IgniteResource)]` writes it for `#[ignite(tab_counts_follow_search = true)]`.
    fn tab_counts_follow_search() -> bool {
        false
    }

    /// Whether a tab whose count is 0 is left out of the list page. The default, `true`,
    /// leaves it out, except the default tab (the [`default_active_tab`](Self::default_active_tab),
    /// or the first) and the tab being shown, which always render. `false` renders every tab.
    /// `#[derive(IgniteResource)]` writes it for `#[ignite(hide_empty_tabs = false)]`.
    fn hide_empty_tabs() -> bool {
        true
    }

    /// The list columns that show their value as a coloured badge, as Filament's `badge()`
    /// and `color()` on a text column (see [`ColumnBadges`]). The panel reads them once, when
    /// it is built. The default is none: every cell is plain text. `#[derive(IgniteResource)]`
    /// writes it for `#[ignite(badges = path)]`.
    fn column_badges() -> ColumnBadges {
        ColumnBadges::new()
    }

    /// The actions on each row of the list page, in display order, as Filament's
    /// `recordActions()`: links, or POSTs that run a task on the record, each with its label,
    /// confirmation, visibility rule, colour and ability (see [`RowAction`]). The panel reads
    /// them once, when it is built. The default is none: each row has its Edit and Delete
    /// buttons only. `#[derive(IgniteResource)]` writes it for `#[ignite(row_actions = path)]`.
    fn row_actions() -> Vec<RowAction> {
        Vec::new()
    }

    /// The actions on the records ticked in the list, as Filament's `toolbarActions()` with
    /// `BulkAction::make()` (see [`BulkAction`]): the list shows a checkbox on each row and a
    /// select of these actions above the table. The default is none: no checkboxes.
    /// `#[derive(IgniteResource)]` writes it for `#[ignite(bulk_actions = path)]`.
    fn bulk_actions() -> Vec<BulkAction> {
        Vec::new()
    }

    /// The records whose built-in Delete button is hidden, as Filament's
    /// `DeleteAction::make()->hidden(fn ($record) => ...)`: a record that meets the filter shows
    /// no Delete button on the list, and the panel refuses its delete (403), such as a post in
    /// the trash, which WordPress deletes only with "Delete Permanently". The panel reads it
    /// once, when it is built. The default, `None`, shows the Delete button on every record the
    /// user may delete. `#[derive(IgniteResource)]` writes it for
    /// `#[ignite(hide_default_delete_when = path)]`, the path of a `fn() -> ListFilter`.
    fn hide_default_delete_when() -> Option<ListFilter> {
        None
    }

    /// The choices of a [`FieldKind::Lookup`](crate::FieldKind::Lookup) field, as
    /// `(value, label)` pairs in display order (added in v1), and of every other field whose
    /// kind [loads its options](crate::FieldKind::loads_options): a post object,
    /// relationship, taxonomy or user field. The panel calls it when it
    /// shows the form, to fill the select, and when it checks a submitted value. The
    /// default is no choices. `#[derive(IgniteResource)]` writes it for `options = ...`
    /// and `belongs_to = ...`.
    fn options(
        db: &Database,
        field: &str,
    ) -> impl Future<Output = Result<Vec<(String, String)>, Error>> + Send {
        let _ = (db, field);
        async { Ok(Vec::new()) }
    }

    /// Returns one page of rows that match `query`.
    fn list(
        db: &Database,
        query: &ListQuery,
    ) -> impl Future<Output = Result<Page<Self::Record>, Error>> + Send;
    /// Returns the row with `id`, or `None` if there is no such row.
    fn find(
        db: &Database,
        id: i64,
    ) -> impl Future<Output = Result<Option<Self::Record>, Error>> + Send;
    /// Inserts a row from `input` and returns it.
    fn create(
        db: &Database,
        input: Self::Input,
    ) -> impl Future<Output = Result<Self::Record, Error>> + Send;
    /// Updates the row with `id` from `input` and returns it.
    fn update(
        db: &Database,
        id: i64,
        input: Self::Input,
    ) -> impl Future<Output = Result<Self::Record, Error>> + Send;
    /// Deletes the row with `id` and returns the number of rows deleted.
    fn delete(db: &Database, id: i64) -> impl Future<Output = Result<u64, Error>> + Send;

    /// Turns the submitted form into `Input` for a create, or returns one message
    /// per field. Call [`Field::check_required`] for required fields.
    fn validate(form: &FormInput) -> Result<Self::Input, FieldErrors>;

    /// Turns the submitted form into `Input` for an update. The default is
    /// [`validate`](Self::validate). Override it when a field may be left blank
    /// on edit, such as a password that keeps its stored value.
    fn validate_update(form: &FormInput) -> Result<Self::Input, FieldErrors> {
        Self::validate(form)
    }

    /// [`list`](Self::list) for the signed-in `user`: the panel's list calls it. Restrict the
    /// rows to the user here, as a Filament resource does in `getEloquentQuery()`. The default
    /// is [`list`](Self::list), for every user.
    fn list_for(
        db: &Database,
        user: &ActingUser,
        query: &ListQuery,
    ) -> impl Future<Output = Result<Page<Self::Record>, Error>> + Send {
        let _ = user;
        Self::list(db, query)
    }

    /// [`find`](Self::find) for the signed-in `user`: the panel finds the record of the edit
    /// form, of its save and of the delete action with it. Return `None` for a row the user's
    /// list leaves out, so the panel answers 404. The default is [`find`](Self::find).
    fn find_for(
        db: &Database,
        user: &ActingUser,
        id: i64,
    ) -> impl Future<Output = Result<Option<Self::Record>, Error>> + Send {
        let _ = user;
        Self::find(db, id)
    }

    /// [`create`](Self::create) for the signed-in `user`. The default is
    /// [`create`](Self::create).
    fn create_for(
        db: &Database,
        user: &ActingUser,
        input: Self::Input,
    ) -> impl Future<Output = Result<Self::Record, Error>> + Send {
        let _ = user;
        Self::create(db, input)
    }

    /// [`update`](Self::update) for the signed-in `user`. The panel calls it only after
    /// [`find_for`](Self::find_for) found the row and the [`Policy`](crate::Policy) allowed the
    /// update. The default is [`update`](Self::update).
    fn update_for(
        db: &Database,
        user: &ActingUser,
        id: i64,
        input: Self::Input,
    ) -> impl Future<Output = Result<Self::Record, Error>> + Send {
        let _ = user;
        Self::update(db, id, input)
    }

    /// [`delete`](Self::delete) for the signed-in `user`. The panel calls it only after
    /// [`find_for`](Self::find_for) found the row and the [`Policy`](crate::Policy) allowed the
    /// delete. The default is [`delete`](Self::delete).
    fn delete_for(
        db: &Database,
        user: &ActingUser,
        id: i64,
    ) -> impl Future<Output = Result<u64, Error>> + Send {
        let _ = user;
        Self::delete(db, id)
    }

    /// [`options`](Self::options) for the signed-in `user`: the choices the form shows and
    /// checks a submitted value against. The default is [`options`](Self::options).
    fn options_for(
        db: &Database,
        user: &ActingUser,
        field: &str,
    ) -> impl Future<Output = Result<Vec<(String, String)>, Error>> + Send {
        let _ = user;
        Self::options(db, field)
    }
}