Skip to main content

renox_admin/
field.rs

1//! A resource's form fields: what [`AdminResource::fields`] returns, drawn
2//! on the create and edit pages with the UI kit's field macros.
3//!
4//! [`AdminResource::fields`]: crate::AdminResource::fields
5
6use renox::serde_json::Value;
7use serde::Serialize;
8
9/// What a [`Field`] asks for, which decides the kit macro that draws it.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
11#[serde(rename_all = "snake_case")]
12#[non_exhaustive]
13pub enum FieldKind {
14    /// One line of text.
15    Text,
16    /// An email address (`type="email"`).
17    Email,
18    /// A password: never filled in from the record.
19    Password,
20    /// A web address (`type="url"`).
21    Url,
22    /// A phone number (`type="tel"`).
23    Tel,
24    /// Several lines of text.
25    Textarea,
26    /// A number (`type="number"`).
27    Number,
28    /// An amount kept in the currency's smallest unit, shown and typed in
29    /// whole units, with the currency's code before it.
30    Money,
31    /// An exact quantity (`Quantity<S>`), shown and typed as a decimal with
32    /// the scale's digits and, with [`Field::unit_from`], the record's unit
33    /// after it.
34    Quantity,
35    /// A date with a calendar (`NaiveDate`, sent as `YYYY-MM-DD`).
36    Date,
37    /// A date and a time (`type="datetime-local"`, sent as
38    /// `YYYY-MM-DDTHH:MM`).
39    DateTime,
40    /// One of a few values.
41    Select,
42    /// A yes/no checkbox (`bool`).
43    Checkbox,
44    /// A yes/no switch (`bool`).
45    Toggle,
46    /// The id of a row of another table, chosen by one of its columns.
47    BelongsTo,
48}
49
50/// One field of a resource's form: its name (the form's and the model's
51/// field), its label, its kind and how it looks. The rules are the form
52/// type's own ([`Validate`](renox::Validate)); `required` here only marks the
53/// field for people and the browser.
54///
55/// ```
56/// use renox_admin::Field;
57///
58/// let fields = vec![
59///     Field::text("name", "Name").required(),
60///     Field::select("status", "Status", [("draft", "Draft"), ("live", "Live")]).required(),
61///     Field::money("price", "Price").required(),
62///     Field::belongs_to("category_id", "Category", "categories", "name"),
63///     Field::textarea("notes", "Notes").span_full(),
64///     Field::toggle("active", "Active").default_value(true),
65/// ];
66/// # assert_eq!(fields.len(), 6);
67/// ```
68#[derive(Debug, Clone, Serialize)]
69#[non_exhaustive]
70pub struct Field {
71    name: String,
72    label: String,
73    kind: FieldKind,
74    options: Vec<(String, String)>,
75    required: bool,
76    hint: Option<String>,
77    placeholder: Option<String>,
78    prefix: Option<String>,
79    suffix: Option<String>,
80    span: Option<String>,
81    rows: u32,
82    step: Option<String>,
83    min: Option<String>,
84    max: Option<String>,
85    autocomplete: Option<String>,
86    searchable: bool,
87    default: Option<Value>,
88    on_create: bool,
89    on_edit: bool,
90    readonly_on_edit: bool,
91    scale: u32,
92    #[serde(skip)]
93    currency_from: Option<String>,
94    #[serde(skip)]
95    unit_from: Option<String>,
96    #[serde(skip)]
97    relation: Option<(String, String)>,
98}
99
100impl Field {
101    fn new(name: &str, label: &str, kind: FieldKind) -> Self {
102        Self {
103            name: name.to_owned(),
104            label: label.to_owned(),
105            kind,
106            options: Vec::new(),
107            required: false,
108            hint: None,
109            placeholder: None,
110            prefix: None,
111            suffix: None,
112            span: None,
113            rows: 4,
114            step: None,
115            min: None,
116            max: None,
117            autocomplete: None,
118            searchable: false,
119            default: None,
120            on_create: true,
121            on_edit: true,
122            readonly_on_edit: false,
123            scale: 0,
124            currency_from: None,
125            unit_from: None,
126            relation: None,
127        }
128    }
129
130    /// One line of text.
131    pub fn text(name: &str, label: &str) -> Self {
132        Self::new(name, label, FieldKind::Text)
133    }
134
135    /// An email address.
136    pub fn email(name: &str, label: &str) -> Self {
137        Self::new(name, label, FieldKind::Email)
138    }
139
140    /// A password. The edit page leaves it empty: make the form's field an
141    /// `Option<String>` and change the password only when one was typed.
142    pub fn password(name: &str, label: &str) -> Self {
143        let mut field = Self::new(name, label, FieldKind::Password);
144        field.autocomplete = Some("new-password".into());
145        field
146    }
147
148    /// A web address.
149    pub fn url(name: &str, label: &str) -> Self {
150        Self::new(name, label, FieldKind::Url)
151    }
152
153    /// A phone number.
154    pub fn tel(name: &str, label: &str) -> Self {
155        Self::new(name, label, FieldKind::Tel)
156    }
157
158    /// Several lines of text (`rows(n)`, 4 by default).
159    pub fn textarea(name: &str, label: &str) -> Self {
160        Self::new(name, label, FieldKind::Textarea)
161    }
162
163    /// A number (`step`, `min` and `max` limit it).
164    pub fn number(name: &str, label: &str) -> Self {
165        Self::new(name, label, FieldKind::Number)
166    }
167
168    /// An amount the model keeps in the smallest unit (cents, like the
169    /// data grid's `money` columns), with `APP_CURRENCY`'s code before it.
170    /// The form shows and takes whole units: with `USD`, `1299` shows as
171    /// `12.99` (a `0.01` step), and `12.99` is read back as `1299` before
172    /// the form's rules and [`fill`](crate::AdminResource::fill) see it
173    /// (rounded to the cent). A currency without decimals (IDR, JPY) is
174    /// as typed. Rules on the form (`min`, `max`) are in the smallest unit.
175    pub fn money(name: &str, label: &str) -> Self {
176        let mut field = Self::new(name, label, FieldKind::Money);
177        field.min = Some("0".into());
178        field
179    }
180
181    /// For a `money` field: the amount is in the currency the record keeps
182    /// in its `key` field (an ISO 4217 code such as `total_currency`, the
183    /// `<field>_currency` column of a `#[model(money)]` field), which the
184    /// resource also lists as a field (a [`select`](Self::select) of codes,
185    /// say). The edit page shows the amount in whole units with that
186    /// currency's decimals and code, the create page uses the currency
187    /// field's [default value](Self::default_value), and the posted amount
188    /// is read with the decimals of the currency posted with it. Without it
189    /// the field uses `APP_CURRENCY`.
190    ///
191    /// ```
192    /// use renox_admin::Field;
193    ///
194    /// let fields = vec![
195    ///     Field::money("total", "Total").currency_from("total_currency"),
196    ///     Field::select("total_currency", "Currency", [("USD", "USD"), ("JPY", "JPY")])
197    ///         .default_value("USD"),
198    /// ];
199    /// # assert_eq!(fields.len(), 2);
200    /// ```
201    pub fn currency_from(mut self, key: &str) -> Self {
202        if self.kind == FieldKind::Money && plain_name(key) {
203            self.currency_from = Some(key.to_owned());
204        }
205        self
206    }
207
208    /// An exact quantity (a `Quantity<S>` field of the model, kept as a
209    /// scaled integer and serialized as the decimal text `"2.500"`). The
210    /// form shows and takes that decimal text (`<rx-input type="quantity">`,
211    /// stepping by the scale's last digit); the form's field is a
212    /// `Quantity<S>` (or a `String`) and no conversion is needed. Set the
213    /// scale with [`scale`](Self::scale) and the record's unit with
214    /// [`unit_from`](Self::unit_from).
215    ///
216    /// ```
217    /// use renox_admin::Field;
218    ///
219    /// let stock = Field::quantity("stock", "Stock").scale(3).unit_from("stock_unit");
220    /// # let _ = stock;
221    /// ```
222    pub fn quantity(name: &str, label: &str) -> Self {
223        Self::new(name, label, FieldKind::Quantity)
224    }
225
226    /// For a `quantity` field: the decimals of its `Quantity<SCALE>`, `3`
227    /// for thousandths (at most 9, 0 by default). It sets the input's step.
228    /// Other fields ignore it.
229    pub fn scale(mut self, scale: u32) -> Self {
230        if self.kind == FieldKind::Quantity {
231            self.scale = scale.min(9);
232        }
233        self
234    }
235
236    /// For a `quantity` field: the quantity is in the unit the record keeps
237    /// in its `key` field (a code such as `stock_unit`), which the resource
238    /// also lists as a field (a [`select`](Self::select) of codes, say). The
239    /// edit page shows that unit after the input, the create page uses the
240    /// unit field's [default value](Self::default_value). Without it the
241    /// field has no unit.
242    ///
243    /// ```
244    /// use renox_admin::Field;
245    ///
246    /// let fields = vec![
247    ///     Field::quantity("stock", "Stock").scale(3).unit_from("stock_unit"),
248    ///     Field::select("stock_unit", "Unit", [("kg", "kg"), ("g", "g")])
249    ///         .default_value("kg"),
250    /// ];
251    /// # assert_eq!(fields.len(), 2);
252    /// ```
253    pub fn unit_from(mut self, key: &str) -> Self {
254        if self.kind == FieldKind::Quantity && plain_name(key) {
255            self.unit_from = Some(key.to_owned());
256        }
257        self
258    }
259
260    /// A date with the kit's calendar, sent as `YYYY-MM-DD` (a `NaiveDate`).
261    pub fn date(name: &str, label: &str) -> Self {
262        Self::new(name, label, FieldKind::Date)
263    }
264
265    /// A date and a time, sent as `YYYY-MM-DDTHH:MM` (a `NaiveDateTime` in
266    /// the form; Renox adds the seconds). The edit page shows the stored
267    /// moment's first 16 characters, so store UTC or a naive time.
268    pub fn datetime(name: &str, label: &str) -> Self {
269        Self::new(name, label, FieldKind::DateTime)
270    }
271
272    /// One of `options`, `(value, label)` pairs. `searchable()` adds a box
273    /// that filters them.
274    pub fn select<V: Into<String>, L: Into<String>>(
275        name: &str,
276        label: &str,
277        options: impl IntoIterator<Item = (V, L)>,
278    ) -> Self {
279        let mut field = Self::new(name, label, FieldKind::Select);
280        field.options = options
281            .into_iter()
282            .map(|(value, label)| (value.into(), label.into()))
283            .collect();
284        field
285    }
286
287    /// A checkbox: a `bool` in the form (ticked or not).
288    pub fn checkbox(name: &str, label: &str) -> Self {
289        Self::new(name, label, FieldKind::Checkbox)
290    }
291
292    /// A switch: a `bool` in the form, for a setting that is on or off.
293    pub fn toggle(name: &str, label: &str) -> Self {
294        Self::new(name, label, FieldKind::Toggle)
295    }
296
297    /// The id of a row of `table`, chosen by its `title` column: a
298    /// searchable select of `table`'s rows (the first 1,000, by `title`).
299    /// Pair it with `#[validate(exists("table", "id"))]` on the form.
300    /// `table` and `title` may only have letters, digits and `_`.
301    pub fn belongs_to(name: &str, label: &str, table: &str, title: &str) -> Self {
302        let mut field = Self::new(name, label, FieldKind::BelongsTo);
303        field.relation = Some((table.to_owned(), title.to_owned()));
304        field.searchable = true;
305        field
306    }
307
308    /// Marks the field required for people and the browser (the form's
309    /// rules decide).
310    pub fn required(mut self) -> Self {
311        self.required = true;
312        self
313    }
314
315    /// A line of help under the field.
316    pub fn hint(mut self, hint: &str) -> Self {
317        self.hint = Some(hint.to_owned());
318        self
319    }
320
321    /// Text shown in the empty field (for a select: its empty choice).
322    pub fn placeholder(mut self, placeholder: &str) -> Self {
323        self.placeholder = Some(placeholder.to_owned());
324        self
325    }
326
327    /// Text joined to the start of the field ("https://", "$").
328    pub fn prefix(mut self, prefix: &str) -> Self {
329        self.prefix = Some(prefix.to_owned());
330        self
331    }
332
333    /// Text joined to the end of the field ("kg", "%").
334    pub fn suffix(mut self, suffix: &str) -> Self {
335        self.suffix = Some(suffix.to_owned());
336        self
337    }
338
339    /// Takes the form's whole width (it has two columns on wider screens).
340    pub fn span_full(mut self) -> Self {
341        self.span = Some("full".into());
342        self
343    }
344
345    /// The lines a textarea shows.
346    pub fn rows(mut self, rows: u32) -> Self {
347        self.rows = rows;
348        self
349    }
350
351    /// A number's step (`"0.01"`, `"any"`).
352    pub fn step(mut self, step: &str) -> Self {
353        self.step = Some(step.to_owned());
354        self
355    }
356
357    /// The smallest number, or the earliest date.
358    pub fn min(mut self, min: impl ToString) -> Self {
359        self.min = Some(min.to_string());
360        self
361    }
362
363    /// The largest number, or the latest date.
364    pub fn max(mut self, max: impl ToString) -> Self {
365        self.max = Some(max.to_string());
366        self
367    }
368
369    /// The browser's `autocomplete` hint (`"off"`, `"email"`).
370    pub fn autocomplete(mut self, autocomplete: &str) -> Self {
371        self.autocomplete = Some(autocomplete.to_owned());
372        self
373    }
374
375    /// For a select: a box to type in that filters the options.
376    pub fn searchable(mut self) -> Self {
377        self.searchable = true;
378        self
379    }
380
381    /// The value the create page starts with (the edit page shows the
382    /// record's).
383    pub fn default_value(mut self, value: impl Serialize) -> Self {
384        self.default = renox::serde_json::to_value(value).ok();
385        self
386    }
387
388    /// Only on the create page.
389    pub fn only_on_create(mut self) -> Self {
390        self.on_edit = false;
391        self
392    }
393
394    /// Only on the edit page.
395    pub fn only_on_edit(mut self) -> Self {
396        self.on_create = false;
397        self
398    }
399
400    /// Shown but not changeable on the edit page (it is still sent, so the
401    /// form's rules see it). On a settings page
402    /// ([`Admin::settings`](crate::Admin::settings)) the stored value is kept
403    /// whatever is sent, so seeded values can be shown without being
404    /// editable.
405    pub fn readonly_on_edit(mut self) -> Self {
406        self.readonly_on_edit = true;
407        self
408    }
409
410    /// The field's name.
411    pub fn name(&self) -> &str {
412        &self.name
413    }
414
415    /// The field's kind.
416    pub fn kind(&self) -> FieldKind {
417        self.kind
418    }
419
420    pub(crate) fn currency_column(&self) -> Option<&str> {
421        self.currency_from.as_deref()
422    }
423
424    pub(crate) fn unit_column(&self) -> Option<&str> {
425        self.unit_from.as_deref()
426    }
427
428    pub(crate) fn default_text(&self) -> Option<&str> {
429        self.default.as_ref().and_then(Value::as_str)
430    }
431
432    pub(crate) fn is_readonly_on_edit(&self) -> bool {
433        self.readonly_on_edit
434    }
435
436    pub(crate) fn shown(&self, creating: bool) -> bool {
437        if creating {
438            self.on_create
439        } else {
440            self.on_edit
441        }
442    }
443
444    pub(crate) fn relation(&self) -> Option<(&str, &str)> {
445        self.relation
446            .as_ref()
447            .map(|(table, title)| (table.as_str(), title.as_str()))
448    }
449
450    pub(crate) fn set_options(&mut self, options: Vec<(String, String)>) {
451        self.options = options;
452    }
453
454    pub(crate) fn label_text(&self) -> &str {
455        &self.label
456    }
457
458    pub(crate) fn has_placeholder(&self) -> bool {
459        self.placeholder.is_some()
460    }
461
462    pub(crate) fn is_required(&self) -> bool {
463        self.required
464    }
465
466    pub(crate) fn min_text(&self) -> Option<&str> {
467        self.min.as_deref()
468    }
469
470    pub(crate) fn max_text(&self) -> Option<&str> {
471        self.max.as_deref()
472    }
473
474    pub(crate) fn choices(&self) -> &[(String, String)] {
475        &self.options
476    }
477
478    /// Runs the field's words (label, hint, placeholder, affixes and the
479    /// choices' labels) through `translate`.
480    pub(crate) fn translate(&mut self, translate: &dyn Fn(&str) -> String) {
481        self.label = translate(&self.label);
482        for text in [
483            &mut self.hint,
484            &mut self.placeholder,
485            &mut self.prefix,
486            &mut self.suffix,
487        ]
488        .into_iter()
489        .flatten()
490        {
491            *text = translate(text);
492        }
493        for (_, label) in &mut self.options {
494            *label = translate(label);
495        }
496    }
497}
498
499/// Whether `name` is a plain SQL name: letters, digits and `_`.
500pub(crate) fn plain_name(name: &str) -> bool {
501    !name.is_empty()
502        && name.len() <= 64
503        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
504        && !name.starts_with(|c: char| c.is_ascii_digit())
505}