Skip to main content

tablo_core/schema/fields/builders/
choices.rs

1//! The choice builder's modifiers: its options, how they render, and where they load from.
2
3use std::sync::Arc;
4
5use super::{
6    super::{super::condition::Watched, ChoiceControl, ControlKind, choice},
7    ChoiceField, IntoOptions, OptionSource,
8};
9use crate::values::FormScalar;
10
11impl<F> ChoiceField<F> {
12    fn choice_mut(&mut self) -> &mut ChoiceControl {
13        match &mut self.0.control {
14            ControlKind::Choice(choice) => choice,
15            _ => unreachable!("a ChoiceField holds a choice control"),
16        }
17    }
18
19    /// Static options: values that are their own label
20    /// (`["draft", "published"]`), `(value, label)` pairs whose label is a string or a
21    /// [`Text`](crate::Text) (`[("draft", text!("status-draft"))]`), or a
22    /// [`#[derive(Options)]`](crate::Options) enum's
23    /// [`options()`](crate::schema::Options::options).
24    pub fn options(mut self, options: impl IntoOptions) -> Self {
25        self.choice_mut().options = options.into_options();
26        self
27    }
28
29    /// Offers `T`'s options, each drawn in its color and with its icon when the choice renders
30    /// as [`buttons`](Self::buttons): what a record form's `#[form(options)]` field declares.
31    #[doc(hidden)]
32    pub fn options_of<T: crate::schema::Options>(mut self) -> Self {
33        let choice = self.choice_mut();
34        choice.options = T::options();
35        choice.faces = T::faces();
36        self
37    }
38
39    /// Takes several options: a checkbox per option, posting the field's key once per checked
40    /// box. A record form's many-to-many field (`Vec<K>` with `#[form(relationship = R)]`) is one,
41    /// and so is its `Vec` with `#[form(options = T)]`, stored in a list column;
42    /// [`parse_list`](crate::values::parse_list) reads one in an action's input.
43    ///
44    /// It offers at most [`MAX_RELATIONSHIP_OPTIONS`](crate::schema::MAX_RELATIONSHIP_OPTIONS)
45    /// records: past them it lists none but the chosen ones, and refuses a submission choosing
46    /// another. A record form's edit re-checks only the keys the record does not link yet.
47    /// `searchable` filters the listed options as the user types. A condition cannot watch it,
48    /// it cannot depend on another field, and its `default` is a list.
49    pub fn multiple(mut self) -> Self {
50        self.choice_mut().multiple = true;
51        self
52    }
53
54    /// Takes any values the user types, as tags: a [`multiple`](Self::multiple) choice whose
55    /// [`options`](Self::options), if any, are suggestions.
56    ///
57    /// - It renders a checkbox per suggestion and per value it holds, checked while it holds it,
58    ///   then a text input adding values, several at once separated by commas.
59    /// - Each value is trimmed, and a blank one or a repeat is dropped, so a value cannot hold a
60    ///   comma. Any other value is accepted: [`max_items`](Self::max_items) caps how many.
61    /// - Mounting refuses it on a [`relationship`](Self::relationship)'s choice, whose values name
62    ///   records.
63    ///
64    /// A record form's `Vec<String>` marked `#[form(tags)]` is one.
65    pub fn tags(mut self) -> Self {
66        let choice = self.choice_mut();
67        choice.multiple = true;
68        choice.tags = true;
69        self
70    }
71
72    /// Renders a radio per option rather than a `<select>`, so every option shows without a
73    /// click: for a few options, such as a status or a visibility. A [`multiple`](Self::multiple)
74    /// choice keeps its checkboxes.
75    ///
76    /// The options load as a select's do, and past the option cap only the chosen one lists.
77    /// [`searchable`](Self::searchable) filters the listed options as the user types. A radio
78    /// choice cannot [depend on](Self::depends_on) another field, since the browser lists its
79    /// options once, but another choice can depend on it.
80    ///
81    /// ```rust
82    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
83    /// # struct Post { #[key] #[auto] id: uuid::Uuid, visibility: String }
84    /// # use tablo_core::{Field, lens};
85    /// Field::choice(lens!(Post.visibility))
86    ///     .options(vec![
87    ///         ("public".to_string(), "Public".to_string()),
88    ///         ("private".to_string(), "Private".to_string()),
89    ///     ])
90    ///     .radio();
91    /// ```
92    pub fn radio(mut self) -> Self {
93        self.choice_mut().layout = choice::Layout::Radio;
94        self
95    }
96
97    /// Renders a button per option, pressed while its option is chosen: a compact
98    /// [`radio`](Self::radio) list, or with [`multiple`](Self::multiple), a compact checkbox
99    /// list. It takes the same modifiers and limits as [`radio`](Self::radio).
100    ///
101    /// ```rust
102    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
103    /// # struct Task { #[key] #[auto] id: uuid::Uuid, priority: String }
104    /// # use tablo_core::{Field, lens};
105    /// Field::choice(lens!(Task.priority))
106    ///     .options(["low", "normal", "high"])
107    ///     .buttons();
108    /// ```
109    pub fn buttons(mut self) -> Self {
110        self.choice_mut().layout = choice::Layout::Buttons;
111        self
112    }
113
114    /// Refuse a submission choosing fewer than `count` options. A [`multiple`](Self::multiple)
115    /// choice's blank answer is the empty list, which no other rule refuses, so `min_items(1)` is
116    /// how one requires a choice. Only the server checks it. A choice that is not `multiple` fails
117    /// the mount, as does a minimum above `max_items` or above the count of static options.
118    pub fn min_items(mut self, count: usize) -> Self {
119        self.choice_mut().bounds.min = Some(count);
120        self
121    }
122
123    /// Refuse a submission choosing more than `count` options; [`min_items`](Self::min_items)
124    /// says which choices take it.
125    pub fn max_items(mut self, count: usize) -> Self {
126        self.choice_mut().bounds.max = Some(count);
127        self
128    }
129
130    /// Filters options as the user types, fetching from the relationship past the option cap.
131    pub fn searchable(mut self) -> Self {
132        self.choice_mut().searchable = true;
133        self
134    }
135
136    /// Loads options from a related source's tenant-scoped query, each valued by its primary key
137    /// and labelled by the source's [`label`](OptionSource::label), degrading to type-to-search
138    /// past the option cap.
139    ///
140    /// A resource's options carry its [`record_title`](crate::ResourceDef::record_title), the
141    /// title its detail page shows. [`relationship_labelled`](Self::relationship_labelled)
142    /// labels one field's options otherwise.
143    ///
144    /// - Options come from the related resource's tenant-scoped query and follow its policy: the
145    ///   list is empty and the field shows "not available" unless the related resource's policy
146    ///   allows `ViewAny`, and each record must pass its `View`.
147    /// - A submitted key must be one of those records, so a hand-crafted POST cannot point at
148    ///   another tenant's row. The write checks the key again inside its transaction, so a record
149    ///   deleted, moved to another tenant or hidden since the form validated refuses the write with
150    ///   the same field error.
151    /// - At most 200 options load. Past that, a `.searchable()` choice turns into type-to-search
152    ///   against `GET {list_url}/-/options`, which searches the related table's `searchable()`
153    ///   columns; a non-searchable choice shows an error instead. `.searchable()` also filters a
154    ///   short list as you type. Without JavaScript the plain select remains.
155    pub fn relationship<R>(mut self) -> Self
156    where
157        R: OptionSource + 'static,
158    {
159        self.choice_mut().relationship = Some(choice::Relationship::new::<R>(R::label));
160        self
161    }
162
163    /// Offers to create the related record from the form: a link beside the select opens the
164    /// [`relationship`](Self::relationship)'s resource's create page in a dialog, and the record it
165    /// saves becomes the choice, while the form keeps what was typed in it.
166    ///
167    /// - The dialog frames the related resource's own create page, so the record passes that
168    ///   resource's policy, tenancy, field access, rules and hooks, as a create from its list does.
169    ///   The link renders only while the panel mounts the resource with a create page and its
170    ///   policy allows `ViewAny` and `Create`, and not while the choice renders disabled.
171    /// - The saved record becomes the choice only when the related resource's scoped query holds
172    ///   it, as its options would; otherwise the dialog says it was created and the choice stays as
173    ///   it was. The submission checks the key as for any relationship.
174    /// - The option shows the record's [`record_title`](crate::ResourceDef::record_title) until the
175    ///   form renders again, even under [`relationship_labelled`](Self::relationship_labelled).
176    /// - The dialog takes the height of the form, up to the screen's, and titles it. In the dialog
177    ///   a [`Section`](crate::Section) has no panel and does not fold, and a section alone in the
178    ///   form shows no title.
179    /// - Without JavaScript the link opens the create page in a new tab, and the record is offered
180    ///   once the form renders again.
181    /// - Mounting refuses a creatable choice that is not a single select over a resource's records:
182    ///   a multiple choice, [radios](Self::radio) or [buttons](Self::buttons), a
183    ///   [dependent](Self::depends_on) or [filtered](Self::options_where) choice, a source that is
184    ///   not a resource, a choice a [condition disables](Self::disabled_when), and a choice in a
185    ///   repeater's rows.
186    pub fn creatable(mut self) -> Self {
187        self.choice_mut().creatable = true;
188        self
189    }
190
191    /// Offers only the related rows whose column `column` equals the value `parent` posts: the
192    /// cities of the chosen country. The browser fetches the options again when `parent` changes,
193    /// and a submission must name a row of the posted parent value. A blank parent offers none.
194    ///
195    /// `column` belongs to the [`relationship`](Self::relationship)'s source model; mounting
196    /// refuses another model, a choice without a relationship, and a `parent` the schema does not
197    /// place.
198    ///
199    /// - The form renders the options of the parent's current value, and none while it is blank.
200    ///   When the parent changes, the browser fetches the new options from `GET
201    ///   {list_url}/-/options` and keeps the current choice only if they still offer it. A choice
202    ///   they drop changes too, so a choice depending on it, or a condition watching it, follows.
203    /// - A submission must name a record of the parent value it posts, or, on an edit that does not
204    ///   post the parent, of its stored value. The write checks the key again inside its
205    ///   transaction, as for any relationship.
206    /// - The 200-option cap counts the parent's records. Past it, a `.searchable()` dependent
207    ///   choice searches among them, and any other offers no option. A failed fetch offers none
208    ///   either.
209    /// - Without JavaScript the options stay those of the value the page rendered with, and a
210    ///   submission naming another value's record is refused.
211    /// - `column` must belong to the relationship's model, and the parent must be placed in the
212    ///   same schema: mounting refuses either mistake. Only a resource's form serves the options,
213    ///   so mounting also refuses a dependent choice in an action's input.
214    /// - A multiple choice neither depends on another field nor narrows one: mounting refuses both.
215    pub fn depends_on<M, T>(
216        mut self,
217        parent: &impl Watched<F>,
218        column: impl Into<toasty::stmt::Path<M, T>>,
219    ) -> Self
220    where
221        M: toasty::schema::Model + Send + Sync + 'static,
222        T: FormScalar + toasty::stmt::IntoExpr<T> + Send + Sync + 'static,
223    {
224        let column: toasty::stmt::Path<M, T> = column.into();
225        let field = crate::toasty_compat::model::field::<M>(
226            &crate::toasty_compat::model::ModelPath::of(&column),
227        )
228        .ok()
229        .map(|field| field.name);
230        self.choice_mut().parent = Some(choice::Parent {
231            watched: parent.key().to_string(),
232            model: std::any::TypeId::of::<M>(),
233            column: field,
234            scope: Arc::new(move |value: &str| {
235                T::parse_form(value)
236                    .ok()
237                    .map(|value| column.clone().eq(value))
238            }),
239        });
240        self
241    }
242
243    /// Offers only the related rows `filter` selects, among those the source's scoped query and a
244    /// [`depends_on`](Self::depends_on) parent offer: the categories without a parent, or the
245    /// users of one role. `filter` builds the predicate for each request, so it may read the
246    /// request's user or tenant.
247    ///
248    /// ```rust
249    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
250    /// # pub struct Category {
251    /// #     #[key] #[auto] pub id: uuid::Uuid,
252    /// #     pub name: String,
253    /// #     #[index] pub parent_id: Option<uuid::Uuid>,
254    /// # }
255    /// # pub struct CategoryResource;
256    /// # impl tablo_core::Resource for CategoryResource {
257    /// #     type Model = Category;
258    /// #     type Form = tablo_core::NoForm<Category>;
259    /// # }
260    /// # use tablo_core::{Field, lens};
261    /// Field::choice(lens!(Category.parent_id))
262    ///     .relationship::<CategoryResource>()
263    ///     .options_where(|_cx| Category::fields().parent_id().is_none());
264    /// ```
265    ///
266    /// - The form, the search past the option cap and a dependent choice's fetch offer only the
267    ///   rows it selects, and a submission must name one: the server checks the key on submit and
268    ///   again inside the write's transaction, so a hand-crafted POST cannot name another row.
269    /// - A [`multiple`](Self::multiple) choice keeps the links it holds to rows the filter drops,
270    ///   since its form never offered them.
271    /// - The predicate must read the relationship's source model; one over another model fails the
272    ///   load, and the field says its options failed to load. Field access does not see the fields
273    ///   it reads: a predicate over a restricted field tells the user which rows pass it.
274    /// - Mounting refuses a filter on a choice without a relationship, and on a
275    ///   [creatable](Self::creatable) choice, whose dialog may save a record the filter drops.
276    pub fn options_where(
277        mut self,
278        filter: impl Fn(&topcoat::context::Cx) -> toasty::stmt::Expr<bool> + Send + Sync + 'static,
279    ) -> Self {
280        self.choice_mut().filter = Some(Arc::new(filter));
281        self
282    }
283
284    /// Loads options as [`relationship`](Self::relationship) does, labelling each by
285    /// `label(cx, record)` instead of the source's label: to tell apart records that share a
286    /// title. The option's record loads without its relations.
287    pub fn relationship_labelled<R>(
288        mut self,
289        label: impl Fn(&topcoat::context::Cx, &R::Model) -> String + Send + Sync + 'static,
290    ) -> Self
291    where
292        R: OptionSource + 'static,
293    {
294        self.choice_mut().relationship =
295            Some(choice::Relationship::new::<R>(label).with_custom_label());
296        self
297    }
298}