renox-admin 1.3.1

An admin panel generated from a Renox app's models: lists, forms, filters, bulk actions and exports.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! A resource's form fields: what [`AdminResource::fields`] returns, drawn
//! on the create and edit pages with the UI kit's field macros.
//!
//! [`AdminResource::fields`]: crate::AdminResource::fields

use renox::serde_json::Value;
use serde::Serialize;

/// What a [`Field`] asks for, which decides the kit macro that draws it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum FieldKind {
    /// One line of text.
    Text,
    /// An email address (`type="email"`).
    Email,
    /// A password: never filled in from the record.
    Password,
    /// A web address (`type="url"`).
    Url,
    /// A phone number (`type="tel"`).
    Tel,
    /// Several lines of text.
    Textarea,
    /// A number (`type="number"`).
    Number,
    /// An amount kept in the currency's smallest unit, shown and typed in
    /// whole units, with the currency's code before it.
    Money,
    /// An exact quantity (`Quantity<S>`), shown and typed as a decimal with
    /// the scale's digits and, with [`Field::unit_from`], the record's unit
    /// after it.
    Quantity,
    /// A date with a calendar (`NaiveDate`, sent as `YYYY-MM-DD`).
    Date,
    /// A date and a time (`type="datetime-local"`, sent as
    /// `YYYY-MM-DDTHH:MM`).
    DateTime,
    /// One of a few values.
    Select,
    /// A yes/no checkbox (`bool`).
    Checkbox,
    /// A yes/no switch (`bool`).
    Toggle,
    /// The id of a row of another table, chosen by one of its columns.
    BelongsTo,
}

/// One field of a resource's form: its name (the form's and the model's
/// field), its label, its kind and how it looks. The rules are the form
/// type's own ([`Validate`](renox::Validate)); `required` here only marks the
/// field for people and the browser.
///
/// ```
/// use renox_admin::Field;
///
/// let fields = vec![
///     Field::text("name", "Name").required(),
///     Field::select("status", "Status", [("draft", "Draft"), ("live", "Live")]).required(),
///     Field::money("price", "Price").required(),
///     Field::belongs_to("category_id", "Category", "categories", "name"),
///     Field::textarea("notes", "Notes").span_full(),
///     Field::toggle("active", "Active").default_value(true),
/// ];
/// # assert_eq!(fields.len(), 6);
/// ```
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct Field {
    name: String,
    label: String,
    kind: FieldKind,
    options: Vec<(String, String)>,
    required: bool,
    hint: Option<String>,
    placeholder: Option<String>,
    prefix: Option<String>,
    suffix: Option<String>,
    span: Option<String>,
    rows: u32,
    step: Option<String>,
    min: Option<String>,
    max: Option<String>,
    autocomplete: Option<String>,
    searchable: bool,
    default: Option<Value>,
    on_create: bool,
    on_edit: bool,
    readonly_on_edit: bool,
    scale: u32,
    #[serde(skip)]
    currency_from: Option<String>,
    #[serde(skip)]
    unit_from: Option<String>,
    #[serde(skip)]
    relation: Option<(String, String)>,
}

impl Field {
    fn new(name: &str, label: &str, kind: FieldKind) -> Self {
        Self {
            name: name.to_owned(),
            label: label.to_owned(),
            kind,
            options: Vec::new(),
            required: false,
            hint: None,
            placeholder: None,
            prefix: None,
            suffix: None,
            span: None,
            rows: 4,
            step: None,
            min: None,
            max: None,
            autocomplete: None,
            searchable: false,
            default: None,
            on_create: true,
            on_edit: true,
            readonly_on_edit: false,
            scale: 0,
            currency_from: None,
            unit_from: None,
            relation: None,
        }
    }

    /// One line of text.
    pub fn text(name: &str, label: &str) -> Self {
        Self::new(name, label, FieldKind::Text)
    }

    /// An email address.
    pub fn email(name: &str, label: &str) -> Self {
        Self::new(name, label, FieldKind::Email)
    }

    /// A password. The edit page leaves it empty: make the form's field an
    /// `Option<String>` and change the password only when one was typed.
    pub fn password(name: &str, label: &str) -> Self {
        let mut field = Self::new(name, label, FieldKind::Password);
        field.autocomplete = Some("new-password".into());
        field
    }

    /// A web address.
    pub fn url(name: &str, label: &str) -> Self {
        Self::new(name, label, FieldKind::Url)
    }

    /// A phone number.
    pub fn tel(name: &str, label: &str) -> Self {
        Self::new(name, label, FieldKind::Tel)
    }

    /// Several lines of text (`rows(n)`, 4 by default).
    pub fn textarea(name: &str, label: &str) -> Self {
        Self::new(name, label, FieldKind::Textarea)
    }

    /// A number (`step`, `min` and `max` limit it).
    pub fn number(name: &str, label: &str) -> Self {
        Self::new(name, label, FieldKind::Number)
    }

    /// An amount the model keeps in the smallest unit (cents, like the
    /// data grid's `money` columns), with `APP_CURRENCY`'s code before it.
    /// The form shows and takes whole units: with `USD`, `1299` shows as
    /// `12.99` (a `0.01` step), and `12.99` is read back as `1299` before
    /// the form's rules and [`fill`](crate::AdminResource::fill) see it
    /// (rounded to the cent). A currency without decimals (IDR, JPY) is
    /// as typed. Rules on the form (`min`, `max`) are in the smallest unit.
    pub fn money(name: &str, label: &str) -> Self {
        let mut field = Self::new(name, label, FieldKind::Money);
        field.min = Some("0".into());
        field
    }

    /// For a `money` field: the amount is in the currency the record keeps
    /// in its `key` field (an ISO 4217 code such as `total_currency`, the
    /// `<field>_currency` column of a `#[model(money)]` field), which the
    /// resource also lists as a field (a [`select`](Self::select) of codes,
    /// say). The edit page shows the amount in whole units with that
    /// currency's decimals and code, the create page uses the currency
    /// field's [default value](Self::default_value), and the posted amount
    /// is read with the decimals of the currency posted with it. Without it
    /// the field uses `APP_CURRENCY`.
    ///
    /// ```
    /// use renox_admin::Field;
    ///
    /// let fields = vec![
    ///     Field::money("total", "Total").currency_from("total_currency"),
    ///     Field::select("total_currency", "Currency", [("USD", "USD"), ("JPY", "JPY")])
    ///         .default_value("USD"),
    /// ];
    /// # assert_eq!(fields.len(), 2);
    /// ```
    pub fn currency_from(mut self, key: &str) -> Self {
        if self.kind == FieldKind::Money && plain_name(key) {
            self.currency_from = Some(key.to_owned());
        }
        self
    }

    /// An exact quantity (a `Quantity<S>` field of the model, kept as a
    /// scaled integer and serialized as the decimal text `"2.500"`). The
    /// form shows and takes that decimal text (`<rx-input type="quantity">`,
    /// stepping by the scale's last digit); the form's field is a
    /// `Quantity<S>` (or a `String`) and no conversion is needed. Set the
    /// scale with [`scale`](Self::scale) and the record's unit with
    /// [`unit_from`](Self::unit_from).
    ///
    /// ```
    /// use renox_admin::Field;
    ///
    /// let stock = Field::quantity("stock", "Stock").scale(3).unit_from("stock_unit");
    /// # let _ = stock;
    /// ```
    pub fn quantity(name: &str, label: &str) -> Self {
        Self::new(name, label, FieldKind::Quantity)
    }

    /// For a `quantity` field: the decimals of its `Quantity<SCALE>`, `3`
    /// for thousandths (at most 9, 0 by default). It sets the input's step.
    /// Other fields ignore it.
    pub fn scale(mut self, scale: u32) -> Self {
        if self.kind == FieldKind::Quantity {
            self.scale = scale.min(9);
        }
        self
    }

    /// For a `quantity` field: the quantity is in the unit the record keeps
    /// in its `key` field (a code such as `stock_unit`), which the resource
    /// also lists as a field (a [`select`](Self::select) of codes, say). The
    /// edit page shows that unit after the input, the create page uses the
    /// unit field's [default value](Self::default_value). Without it the
    /// field has no unit.
    ///
    /// ```
    /// use renox_admin::Field;
    ///
    /// let fields = vec![
    ///     Field::quantity("stock", "Stock").scale(3).unit_from("stock_unit"),
    ///     Field::select("stock_unit", "Unit", [("kg", "kg"), ("g", "g")])
    ///         .default_value("kg"),
    /// ];
    /// # assert_eq!(fields.len(), 2);
    /// ```
    pub fn unit_from(mut self, key: &str) -> Self {
        if self.kind == FieldKind::Quantity && plain_name(key) {
            self.unit_from = Some(key.to_owned());
        }
        self
    }

    /// A date with the kit's calendar, sent as `YYYY-MM-DD` (a `NaiveDate`).
    pub fn date(name: &str, label: &str) -> Self {
        Self::new(name, label, FieldKind::Date)
    }

    /// A date and a time, sent as `YYYY-MM-DDTHH:MM` (a `NaiveDateTime` in
    /// the form; Renox adds the seconds). The edit page shows the stored
    /// moment's first 16 characters, so store UTC or a naive time.
    pub fn datetime(name: &str, label: &str) -> Self {
        Self::new(name, label, FieldKind::DateTime)
    }

    /// One of `options`, `(value, label)` pairs. `searchable()` adds a box
    /// that filters them.
    pub fn select<V: Into<String>, L: Into<String>>(
        name: &str,
        label: &str,
        options: impl IntoIterator<Item = (V, L)>,
    ) -> Self {
        let mut field = Self::new(name, label, FieldKind::Select);
        field.options = options
            .into_iter()
            .map(|(value, label)| (value.into(), label.into()))
            .collect();
        field
    }

    /// A checkbox: a `bool` in the form (ticked or not).
    pub fn checkbox(name: &str, label: &str) -> Self {
        Self::new(name, label, FieldKind::Checkbox)
    }

    /// A switch: a `bool` in the form, for a setting that is on or off.
    pub fn toggle(name: &str, label: &str) -> Self {
        Self::new(name, label, FieldKind::Toggle)
    }

    /// The id of a row of `table`, chosen by its `title` column: a
    /// searchable select of `table`'s rows (the first 1,000, by `title`).
    /// Pair it with `#[validate(exists("table", "id"))]` on the form.
    /// `table` and `title` may only have letters, digits and `_`.
    pub fn belongs_to(name: &str, label: &str, table: &str, title: &str) -> Self {
        let mut field = Self::new(name, label, FieldKind::BelongsTo);
        field.relation = Some((table.to_owned(), title.to_owned()));
        field.searchable = true;
        field
    }

    /// Marks the field required for people and the browser (the form's
    /// rules decide).
    pub fn required(mut self) -> Self {
        self.required = true;
        self
    }

    /// A line of help under the field.
    pub fn hint(mut self, hint: &str) -> Self {
        self.hint = Some(hint.to_owned());
        self
    }

    /// Text shown in the empty field (for a select: its empty choice).
    pub fn placeholder(mut self, placeholder: &str) -> Self {
        self.placeholder = Some(placeholder.to_owned());
        self
    }

    /// Text joined to the start of the field ("https://", "$").
    pub fn prefix(mut self, prefix: &str) -> Self {
        self.prefix = Some(prefix.to_owned());
        self
    }

    /// Text joined to the end of the field ("kg", "%").
    pub fn suffix(mut self, suffix: &str) -> Self {
        self.suffix = Some(suffix.to_owned());
        self
    }

    /// Takes the form's whole width (it has two columns on wider screens).
    pub fn span_full(mut self) -> Self {
        self.span = Some("full".into());
        self
    }

    /// The lines a textarea shows.
    pub fn rows(mut self, rows: u32) -> Self {
        self.rows = rows;
        self
    }

    /// A number's step (`"0.01"`, `"any"`).
    pub fn step(mut self, step: &str) -> Self {
        self.step = Some(step.to_owned());
        self
    }

    /// The smallest number, or the earliest date.
    pub fn min(mut self, min: impl ToString) -> Self {
        self.min = Some(min.to_string());
        self
    }

    /// The largest number, or the latest date.
    pub fn max(mut self, max: impl ToString) -> Self {
        self.max = Some(max.to_string());
        self
    }

    /// The browser's `autocomplete` hint (`"off"`, `"email"`).
    pub fn autocomplete(mut self, autocomplete: &str) -> Self {
        self.autocomplete = Some(autocomplete.to_owned());
        self
    }

    /// For a select: a box to type in that filters the options.
    pub fn searchable(mut self) -> Self {
        self.searchable = true;
        self
    }

    /// The value the create page starts with (the edit page shows the
    /// record's).
    pub fn default_value(mut self, value: impl Serialize) -> Self {
        self.default = renox::serde_json::to_value(value).ok();
        self
    }

    /// Only on the create page.
    pub fn only_on_create(mut self) -> Self {
        self.on_edit = false;
        self
    }

    /// Only on the edit page.
    pub fn only_on_edit(mut self) -> Self {
        self.on_create = false;
        self
    }

    /// Shown but not changeable on the edit page (it is still sent, so the
    /// form's rules see it). On a settings page
    /// ([`Admin::settings`](crate::Admin::settings)) the stored value is kept
    /// whatever is sent, so seeded values can be shown without being
    /// editable.
    pub fn readonly_on_edit(mut self) -> Self {
        self.readonly_on_edit = true;
        self
    }

    /// The field's name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The field's kind.
    pub fn kind(&self) -> FieldKind {
        self.kind
    }

    pub(crate) fn currency_column(&self) -> Option<&str> {
        self.currency_from.as_deref()
    }

    pub(crate) fn unit_column(&self) -> Option<&str> {
        self.unit_from.as_deref()
    }

    pub(crate) fn default_text(&self) -> Option<&str> {
        self.default.as_ref().and_then(Value::as_str)
    }

    pub(crate) fn is_readonly_on_edit(&self) -> bool {
        self.readonly_on_edit
    }

    pub(crate) fn shown(&self, creating: bool) -> bool {
        if creating {
            self.on_create
        } else {
            self.on_edit
        }
    }

    pub(crate) fn relation(&self) -> Option<(&str, &str)> {
        self.relation
            .as_ref()
            .map(|(table, title)| (table.as_str(), title.as_str()))
    }

    pub(crate) fn set_options(&mut self, options: Vec<(String, String)>) {
        self.options = options;
    }

    pub(crate) fn label_text(&self) -> &str {
        &self.label
    }

    pub(crate) fn has_placeholder(&self) -> bool {
        self.placeholder.is_some()
    }

    pub(crate) fn is_required(&self) -> bool {
        self.required
    }

    pub(crate) fn min_text(&self) -> Option<&str> {
        self.min.as_deref()
    }

    pub(crate) fn max_text(&self) -> Option<&str> {
        self.max.as_deref()
    }

    pub(crate) fn choices(&self) -> &[(String, String)] {
        &self.options
    }

    /// Runs the field's words (label, hint, placeholder, affixes and the
    /// choices' labels) through `translate`.
    pub(crate) fn translate(&mut self, translate: &dyn Fn(&str) -> String) {
        self.label = translate(&self.label);
        for text in [
            &mut self.hint,
            &mut self.placeholder,
            &mut self.prefix,
            &mut self.suffix,
        ]
        .into_iter()
        .flatten()
        {
            *text = translate(text);
        }
        for (_, label) in &mut self.options {
            *label = translate(label);
        }
    }
}

/// Whether `name` is a plain SQL name: letters, digits and `_`.
pub(crate) fn plain_name(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= 64
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
        && !name.starts_with(|c: char| c.is_ascii_digit())
}