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    /// A date with a calendar (`NaiveDate`, sent as `YYYY-MM-DD`).
32    Date,
33    /// A date and a time (`type="datetime-local"`, sent as
34    /// `YYYY-MM-DDTHH:MM`).
35    DateTime,
36    /// One of a few values.
37    Select,
38    /// A yes/no checkbox (`bool`).
39    Checkbox,
40    /// A yes/no switch (`bool`).
41    Toggle,
42    /// The id of a row of another table, chosen by one of its columns.
43    BelongsTo,
44}
45
46/// One field of a resource's form: its name (the form's and the model's
47/// field), its label, its kind and how it looks. The rules are the form
48/// type's own ([`Validate`](renox::Validate)); `required` here only marks the
49/// field for people and the browser.
50///
51/// ```
52/// use renox_admin::Field;
53///
54/// let fields = vec![
55///     Field::text("name", "Name").required(),
56///     Field::select("status", "Status", [("draft", "Draft"), ("live", "Live")]).required(),
57///     Field::money("price", "Price").required(),
58///     Field::belongs_to("category_id", "Category", "categories", "name"),
59///     Field::textarea("notes", "Notes").span_full(),
60///     Field::toggle("active", "Active").default_value(true),
61/// ];
62/// # assert_eq!(fields.len(), 6);
63/// ```
64#[derive(Debug, Clone, Serialize)]
65#[non_exhaustive]
66pub struct Field {
67    name: String,
68    label: String,
69    kind: FieldKind,
70    options: Vec<(String, String)>,
71    required: bool,
72    hint: Option<String>,
73    placeholder: Option<String>,
74    prefix: Option<String>,
75    suffix: Option<String>,
76    span: Option<String>,
77    rows: u32,
78    step: Option<String>,
79    min: Option<String>,
80    max: Option<String>,
81    autocomplete: Option<String>,
82    searchable: bool,
83    default: Option<Value>,
84    on_create: bool,
85    on_edit: bool,
86    readonly_on_edit: bool,
87    #[serde(skip)]
88    relation: Option<(String, String)>,
89}
90
91impl Field {
92    fn new(name: &str, label: &str, kind: FieldKind) -> Self {
93        Self {
94            name: name.to_owned(),
95            label: label.to_owned(),
96            kind,
97            options: Vec::new(),
98            required: false,
99            hint: None,
100            placeholder: None,
101            prefix: None,
102            suffix: None,
103            span: None,
104            rows: 4,
105            step: None,
106            min: None,
107            max: None,
108            autocomplete: None,
109            searchable: false,
110            default: None,
111            on_create: true,
112            on_edit: true,
113            readonly_on_edit: false,
114            relation: None,
115        }
116    }
117
118    /// One line of text.
119    pub fn text(name: &str, label: &str) -> Self {
120        Self::new(name, label, FieldKind::Text)
121    }
122
123    /// An email address.
124    pub fn email(name: &str, label: &str) -> Self {
125        Self::new(name, label, FieldKind::Email)
126    }
127
128    /// A password. The edit page leaves it empty: make the form's field an
129    /// `Option<String>` and change the password only when one was typed.
130    pub fn password(name: &str, label: &str) -> Self {
131        let mut field = Self::new(name, label, FieldKind::Password);
132        field.autocomplete = Some("new-password".into());
133        field
134    }
135
136    /// A web address.
137    pub fn url(name: &str, label: &str) -> Self {
138        Self::new(name, label, FieldKind::Url)
139    }
140
141    /// A phone number.
142    pub fn tel(name: &str, label: &str) -> Self {
143        Self::new(name, label, FieldKind::Tel)
144    }
145
146    /// Several lines of text (`rows(n)`, 4 by default).
147    pub fn textarea(name: &str, label: &str) -> Self {
148        Self::new(name, label, FieldKind::Textarea)
149    }
150
151    /// A number (`step`, `min` and `max` limit it).
152    pub fn number(name: &str, label: &str) -> Self {
153        Self::new(name, label, FieldKind::Number)
154    }
155
156    /// An amount the model keeps in the smallest unit (cents, like the
157    /// data grid's `money` columns), with `APP_CURRENCY`'s code before it.
158    /// The form shows and takes whole units: with `USD`, `1299` shows as
159    /// `12.99` (a `0.01` step), and `12.99` is read back as `1299` before
160    /// the form's rules and [`fill`](crate::AdminResource::fill) see it
161    /// (rounded to the cent). A currency without decimals (IDR, JPY) is
162    /// as typed. Rules on the form (`min`, `max`) are in the smallest unit.
163    pub fn money(name: &str, label: &str) -> Self {
164        let mut field = Self::new(name, label, FieldKind::Money);
165        field.min = Some("0".into());
166        field
167    }
168
169    /// A date with the kit's calendar, sent as `YYYY-MM-DD` (a `NaiveDate`).
170    pub fn date(name: &str, label: &str) -> Self {
171        Self::new(name, label, FieldKind::Date)
172    }
173
174    /// A date and a time, sent as `YYYY-MM-DDTHH:MM` (a `NaiveDateTime` in
175    /// the form; Renox adds the seconds). The edit page shows the stored
176    /// moment's first 16 characters, so store UTC or a naive time.
177    pub fn datetime(name: &str, label: &str) -> Self {
178        Self::new(name, label, FieldKind::DateTime)
179    }
180
181    /// One of `options`, `(value, label)` pairs. `searchable()` adds a box
182    /// that filters them.
183    pub fn select<V: Into<String>, L: Into<String>>(
184        name: &str,
185        label: &str,
186        options: impl IntoIterator<Item = (V, L)>,
187    ) -> Self {
188        let mut field = Self::new(name, label, FieldKind::Select);
189        field.options = options
190            .into_iter()
191            .map(|(value, label)| (value.into(), label.into()))
192            .collect();
193        field
194    }
195
196    /// A checkbox: a `bool` in the form (ticked or not).
197    pub fn checkbox(name: &str, label: &str) -> Self {
198        Self::new(name, label, FieldKind::Checkbox)
199    }
200
201    /// A switch: a `bool` in the form, for a setting that is on or off.
202    pub fn toggle(name: &str, label: &str) -> Self {
203        Self::new(name, label, FieldKind::Toggle)
204    }
205
206    /// The id of a row of `table`, chosen by its `title` column: a
207    /// searchable select of `table`'s rows (the first 1,000, by `title`).
208    /// Pair it with `#[validate(exists("table", "id"))]` on the form.
209    /// `table` and `title` may only have letters, digits and `_`.
210    pub fn belongs_to(name: &str, label: &str, table: &str, title: &str) -> Self {
211        let mut field = Self::new(name, label, FieldKind::BelongsTo);
212        field.relation = Some((table.to_owned(), title.to_owned()));
213        field.searchable = true;
214        field
215    }
216
217    /// Marks the field required for people and the browser (the form's
218    /// rules decide).
219    pub fn required(mut self) -> Self {
220        self.required = true;
221        self
222    }
223
224    /// A line of help under the field.
225    pub fn hint(mut self, hint: &str) -> Self {
226        self.hint = Some(hint.to_owned());
227        self
228    }
229
230    /// Text shown in the empty field (for a select: its empty choice).
231    pub fn placeholder(mut self, placeholder: &str) -> Self {
232        self.placeholder = Some(placeholder.to_owned());
233        self
234    }
235
236    /// Text joined to the start of the field ("https://", "$").
237    pub fn prefix(mut self, prefix: &str) -> Self {
238        self.prefix = Some(prefix.to_owned());
239        self
240    }
241
242    /// Text joined to the end of the field ("kg", "%").
243    pub fn suffix(mut self, suffix: &str) -> Self {
244        self.suffix = Some(suffix.to_owned());
245        self
246    }
247
248    /// Takes the form's whole width (it has two columns on wider screens).
249    pub fn span_full(mut self) -> Self {
250        self.span = Some("full".into());
251        self
252    }
253
254    /// The lines a textarea shows.
255    pub fn rows(mut self, rows: u32) -> Self {
256        self.rows = rows;
257        self
258    }
259
260    /// A number's step (`"0.01"`, `"any"`).
261    pub fn step(mut self, step: &str) -> Self {
262        self.step = Some(step.to_owned());
263        self
264    }
265
266    /// The smallest number, or the earliest date.
267    pub fn min(mut self, min: impl ToString) -> Self {
268        self.min = Some(min.to_string());
269        self
270    }
271
272    /// The largest number, or the latest date.
273    pub fn max(mut self, max: impl ToString) -> Self {
274        self.max = Some(max.to_string());
275        self
276    }
277
278    /// The browser's `autocomplete` hint (`"off"`, `"email"`).
279    pub fn autocomplete(mut self, autocomplete: &str) -> Self {
280        self.autocomplete = Some(autocomplete.to_owned());
281        self
282    }
283
284    /// For a select: a box to type in that filters the options.
285    pub fn searchable(mut self) -> Self {
286        self.searchable = true;
287        self
288    }
289
290    /// The value the create page starts with (the edit page shows the
291    /// record's).
292    pub fn default_value(mut self, value: impl Serialize) -> Self {
293        self.default = renox::serde_json::to_value(value).ok();
294        self
295    }
296
297    /// Only on the create page.
298    pub fn only_on_create(mut self) -> Self {
299        self.on_edit = false;
300        self
301    }
302
303    /// Only on the edit page.
304    pub fn only_on_edit(mut self) -> Self {
305        self.on_create = false;
306        self
307    }
308
309    /// Shown but not changeable on the edit page (it is still sent, so the
310    /// form's rules see it).
311    pub fn readonly_on_edit(mut self) -> Self {
312        self.readonly_on_edit = true;
313        self
314    }
315
316    /// The field's name.
317    pub fn name(&self) -> &str {
318        &self.name
319    }
320
321    /// The field's kind.
322    pub fn kind(&self) -> FieldKind {
323        self.kind
324    }
325
326    pub(crate) fn shown(&self, creating: bool) -> bool {
327        if creating {
328            self.on_create
329        } else {
330            self.on_edit
331        }
332    }
333
334    pub(crate) fn relation(&self) -> Option<(&str, &str)> {
335        self.relation
336            .as_ref()
337            .map(|(table, title)| (table.as_str(), title.as_str()))
338    }
339
340    pub(crate) fn set_options(&mut self, options: Vec<(String, String)>) {
341        self.options = options;
342    }
343}
344
345/// Whether `name` is a plain SQL name: letters, digits and `_`.
346pub(crate) fn plain_name(name: &str) -> bool {
347    !name.is_empty()
348        && name.len() <= 64
349        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
350        && !name.starts_with(|c: char| c.is_ascii_digit())
351}