lariv-rs 0.1.0

Compile-time plugin web application framework built on Axum, SeaORM, Maud, and HTMX
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
//! Attribute-macro-backed HTML forms: [`HtmlForm`] + [`FormWidget`].
//!
//! Define a `*Form` struct with `#[html_form]` to get compile-time field specs,
//! generated `{Form}Field` / `{Form}Flag` enums, Maud rendering via [`FormWidget`],
//! and multipart parsing via [`HtmlForm::from_multipart`].
//!
//! For urlencoded POST handlers use [`HtmlFormBody`] instead of [`axum::Form`]
//! so many-to-many fields (`Vec<i64>`) with repeated HTML names deserialize correctly.
//!
//! # When to use
//!
//! Use for create/edit wizards, credentials forms, and query filters where the
//! same struct drives both HTML and submission parsing. Hand-built pages can use
//! [`crate::components::input`] directly instead.
//!
//! ```rust,ignore
//! #[derive(Default)]
//! #[html_form(action = "/users", enctype = "multipart/form-data")]
//! struct UserForm {
//!     #[widget(Text)]
//!     name: String,
//!     #[widget(Email)]
//!     email: String,
//! }
//!
//! // Handler: UserForm::from_multipart(multipart).await
//! // GET page: UserForm::render_inputs(&ctx)
//! ```

pub mod extract;
pub mod multipart;
pub mod upload;
pub mod urlencoded;
pub mod widgets;

use std::{borrow::Cow, collections::HashMap, fmt, marker::PhantomData, ops::Deref, str::FromStr};

use axum::extract::Multipart;
use maud::{Markup, html};
use serde::{Deserialize, Deserializer};

use crate::components::{ManyToManyItem, container_error, container_row};

pub use extract::HtmlFormBody;
pub use lariv_rs_macros::html_form;
pub use multipart::{MultipartParts, collect_multipart};
pub use upload::{Upload, UploadedFile};
pub use urlencoded::{UrlencodedFields, deserialize_urlencoded};
pub use widgets::*;

/// Errors from multipart collection / form assembly.
#[derive(Debug, thiserror::Error)]
pub enum FormError {
    #[error("multipart: {0}")]
    Multipart(String),
    #[error("upload spool: {0}")]
    Spool(String),
    #[error("deserialize: {0}")]
    Deserialize(String),
    #[error("{0}")]
    Validation(String),
}

/// Preprocess integer/decimal form input: trim and strip thousands separators (`,`).
pub fn preprocess_numeric_form_value(s: &str) -> std::borrow::Cow<'_, str> {
    let s = s.trim();
    if s.contains(',') {
        std::borrow::Cow::Owned(s.chars().filter(|&c| c != ',').collect())
    } else {
        std::borrow::Cow::Borrowed(s)
    }
}

/// HTML forms send empty inputs as `""`; serde's `Option<i64>` rejects that.
pub fn empty_str_as_none<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
    D: Deserializer<'de>,
    T: FromStr,
    T::Err: fmt::Display,
{
    let s = Option::<String>::deserialize(deserializer)?;
    match s.as_deref().map(preprocess_numeric_form_value) {
        None => Ok(None),
        Some(s) if s.is_empty() => Ok(None),
        Some(s) => T::from_str(s.as_ref())
            .map(Some)
            .map_err(serde::de::Error::custom),
    }
}

/// Empty string → `0` for non-optional integer form fields (FK pickers).
pub fn empty_str_as_i64<'de, D>(deserializer: D) -> Result<i64, D::Error>
where
    D: Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    let s = preprocess_numeric_form_value(&s);
    if s.is_empty() {
        Ok(0)
    } else {
        s.parse().map_err(serde::de::Error::custom)
    }
}

/// HTML forms send one value (`Tags=1`) or many (`Tags=1&Tags=2`) for the same key.
pub fn form_vec_string<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
    D: Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum OneOrMany {
        One(String),
        Many(Vec<String>),
    }

    match Option::<OneOrMany>::deserialize(deserializer)? {
        None => Ok(vec![]),
        Some(OneOrMany::One(s)) => {
            let s = s.trim();
            if s.is_empty() {
                Ok(vec![])
            } else {
                Ok(vec![s.to_string()])
            }
        }
        Some(OneOrMany::Many(items)) => Ok(items
            .into_iter()
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect()),
    }
}

/// HTML checkbox: absent or empty → `false`; `on` / `true` / `1` → `true`.
pub fn form_checkbox_bool<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
    D: Deserializer<'de>,
{
    let s = Option::<String>::deserialize(deserializer)?;
    Ok(matches!(
        s.as_deref().map(str::trim),
        Some("on") | Some("true") | Some("1") | Some("yes")
    ))
}

/// JSON/WebSocket: number or numeric string → `i64` (missing → `0`).
pub fn json_flex_i64<'de, D>(deserializer: D) -> Result<i64, D::Error>
where
    D: Deserializer<'de>,
{
    use serde_json::Value;

    match Option::<Value>::deserialize(deserializer)? {
        None | Some(Value::Null) => Ok(0),
        Some(Value::Number(n)) => Ok(n.as_i64().unwrap_or(0)),
        Some(Value::String(s)) => Ok(s.trim().parse().unwrap_or(0)),
        _ => Ok(0),
    }
}

/// JSON/WebSocket: array, single number/string, or absent → `Vec<i64>`.
pub fn json_flex_vec_i64<'de, D>(deserializer: D) -> Result<Vec<i64>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde_json::Value;

    match Option::<Value>::deserialize(deserializer)? {
        None | Some(Value::Null) => Ok(vec![]),
        Some(Value::String(s)) => {
            let s = s.trim();
            if s.is_empty() {
                Ok(vec![])
            } else {
                Ok(s.parse().ok().into_iter().collect())
            }
        }
        Some(Value::Number(n)) => Ok(n.as_i64().into_iter().collect()),
        Some(Value::Array(arr)) => Ok(arr
            .iter()
            .filter_map(|item| match item {
                Value::Number(n) => n.as_i64(),
                Value::String(s) => s.trim().parse().ok(),
                _ => None,
            })
            .collect()),
        _ => Ok(vec![]),
    }
}

/// HTML forms send one value (`Tags=1`) or many (`Tags=1&Tags=2`) for the same key.
pub fn form_vec_i64<'de, D>(deserializer: D) -> Result<Vec<i64>, D::Error>
where
    D: Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum OneOrMany {
        One(String),
        Many(Vec<String>),
    }

    match Option::<OneOrMany>::deserialize(deserializer)? {
        None => Ok(vec![]),
        Some(OneOrMany::One(s)) => parse_form_vec_i64(&s).map_err(serde::de::Error::custom),
        Some(OneOrMany::Many(items)) => {
            let mut out = Vec::new();
            for s in items {
                out.extend(parse_form_vec_i64(&s).map_err(serde::de::Error::custom)?);
            }
            Ok(out)
        }
    }
}

fn parse_form_vec_i64(s: &str) -> Result<Vec<i64>, String> {
    let s = preprocess_numeric_form_value(s);
    if s.is_empty() {
        return Ok(vec![]);
    }
    s.parse::<i64>().map(|n| vec![n]).map_err(|e| e.to_string())
}

/// Compile-time HTML input name for a form field (generated per `#[html_form]` struct).
pub trait FormFieldKey: Copy {
    fn html_name(self) -> &'static str;
    fn display_key(self) -> &'static str {
        self.html_name()
    }
    fn choices_key(self) -> &'static str {
        self.html_name()
    }
    /// Picker `target_input` query param — same as [`Self::html_name`].
    fn target_input(self) -> &'static str {
        self.html_name()
    }
}

/// Server-side visibility / conditional flag (generated from `when` / `required_unless`).
pub trait FormFlagKey: Copy {
    fn as_str(self) -> &'static str;
}

/// Placeholder for tagged enum forms without flat field lists.
#[derive(Debug, Clone, Copy)]
pub enum NoFormFields {}

impl FormFieldKey for NoFormFields {
    fn html_name(self) -> &'static str {
        match self {}
    }
}

/// Placeholder for forms without conditional flags.
#[derive(Debug, Clone, Copy)]
pub enum NoFormFlags {}

impl FormFlagKey for NoFormFlags {
    fn as_str(self) -> &'static str {
        match self {}
    }
}

/// Type-safe builder for [`FormCtx`] — use [`FormCtx::form`] and field keys from the
/// generated `{Form}Field` / `{Form}Flag` enums.
pub struct FormCtxBuilder<'a, F: HtmlForm> {
    ctx: FormCtx<'a>,
    _form: PhantomData<F>,
}

impl<'a, F: HtmlForm> FormCtxBuilder<'a, F> {
    pub fn value(mut self, field: impl FormFieldKey, value: impl Into<Cow<'a, str>>) -> Self {
        self.ctx = self.ctx.set_value(field.html_name(), value);
        self
    }

    pub fn checked(mut self, field: impl FormFieldKey, checked: bool) -> Self {
        self.ctx = self.ctx.set_checked(field.html_name(), checked);
        self
    }

    pub fn error(mut self, field: impl FormFieldKey, error: Option<&'a str>) -> Self {
        self.ctx = self.ctx.set_error(field.display_key(), error);
        self
    }

    pub fn flag(mut self, flag: F::Flag, on: bool) -> Self {
        self.ctx = self.ctx.set_flag(flag.as_str(), on);
        self
    }

    pub fn choices(mut self, field: impl FormFieldKey, choices: &'a [(String, String)]) -> Self {
        self.ctx = self.ctx.set_choices(field.choices_key(), choices);
        self
    }

    pub fn m2m(mut self, field: impl FormFieldKey, items: &'a [ManyToManyItem]) -> Self {
        self.ctx = self.ctx.set_m2m(field.html_name(), items);
        self
    }

    pub fn list(mut self, field: impl FormFieldKey, items: &'a [String]) -> Self {
        self.ctx = self.ctx.set_list(field.html_name(), items);
        self
    }

    pub fn display(mut self, field: impl FormFieldKey, display: &'a str) -> Self {
        self.ctx = self.ctx.set_display(field.display_key(), display);
        self
    }

    pub fn url(mut self, field: impl FormFieldKey, url: &'a str) -> Self {
        self.ctx = self.ctx.set_url(field.html_name(), url);
        self
    }

    pub fn label(mut self, field: impl FormFieldKey, label: &'a str) -> Self {
        self.ctx = self.ctx.set_label(field.html_name(), label);
        self
    }

    pub fn hint(mut self, field: impl FormFieldKey, hint: &'a str) -> Self {
        self.ctx = self.ctx.set_hint(field.html_name(), hint);
        self
    }

    pub fn x_data(mut self, data: &'a str) -> Self {
        self.ctx = self.ctx.set_x_data(data);
        self
    }

    pub fn lock_kind(mut self, locked: bool) -> Self {
        self.ctx = self.ctx.set_lock_kind(locked);
        self
    }

    /// Set the tagged enum discriminant for forms with a [`Kind`] widget.
    pub fn kind<K: HtmlKind>(mut self, value: &'a str) -> Self {
        self.ctx = self.ctx.set_value(K::kind_tag(), value);
        self
    }

    pub fn into_ctx(self) -> FormCtx<'a> {
        self.ctx
    }
}

impl<'a, F: HtmlForm> Deref for FormCtxBuilder<'a, F> {
    type Target = FormCtx<'a>;

    fn deref(&self) -> &Self::Target {
        &self.ctx
    }
}

impl<'a, F: HtmlForm> From<FormCtxBuilder<'a, F>> for FormCtx<'a> {
    fn from(builder: FormCtxBuilder<'a, F>) -> Self {
        builder.ctx
    }
}

/// One widget implementation — stock ([`widgets`]) and app widgets use this trait.
///
/// Implement for custom field types; reference the type in `#[widget(MyWidget)]`.
pub trait FormWidget {
    fn render(ctx: &FormCtx<'_>, field: &FieldRender<'_>) -> Markup;
}

/// Per-field view passed to [`FormWidget::render`].
pub struct FieldRender<'a> {
    pub name: &'a str,
    pub label: &'a str,
    pub value: &'a str,
    pub required: bool,
    pub spec: &'a FieldSpec,
}

/// Compile-time description of one form field (generated by `#[html_form]`).
pub struct FieldSpec {
    pub name: &'static str,
    pub label: &'static str,
    pub required: bool,
    pub row: Option<&'static str>,
    /// Server-side visibility flag (`FormCtx::flag`).
    pub when: Option<&'static str>,
    pub required_unless: Option<&'static str>,
    /// Alpine.js `x-model` binding (typically on checkboxes).
    pub model: Option<&'static str>,
    /// Alpine.js expression for client-side `x-show` (requires [`FormCtx::x_data`]).
    /// Inactive fields are also disabled so required controls skip HTML5 validation.
    pub show: Option<&'static str>,
    pub url: Option<&'static str>,
    pub swap_key: Option<&'static str>,
    pub display_key: Option<&'static str>,
    pub error_key: Option<&'static str>,
    pub choices_key: Option<&'static str>,
    pub placeholder: Option<&'static str>,
    /// Tooltip copy shown beside the field label (see [`crate::components::label_hint`]).
    pub hint: Option<&'static str>,
    pub rows: Option<u32>,
    pub multiple: bool,
    pub accept: Option<&'static str>,
    pub render: fn(&FormCtx<'_>, &FieldRender<'_>) -> Markup,
}

/// One variant of a tagged [`HtmlKind`] enum form.
pub struct KindVariantSpec {
    pub value: &'static str,
    pub label: &'static str,
    pub fields: &'static [FieldSpec],
}

/// Tagged enum forms: discriminant radios + per-variant fields.
///
/// Use when one form shape depends on a selected kind (e.g. payment method).
pub trait HtmlKind: HtmlForm {
    fn kind_tag() -> &'static str;
    /// Alpine / JS property for `x-model` (camelCase).
    fn kind_model() -> &'static str;
    fn variants() -> &'static [KindVariantSpec];
}

/// Request `*Form` types that expose field specs for rendering and multipart submit.
///
/// Generated by `#[html_form]`; call [`Self::render_inputs`] on GET and
/// [`Self::from_multipart`] on POST.
pub trait HtmlForm: Sized {
    /// Generated `{Self}Field` enum — use with [`FormCtx::form`].
    type Field: FormFieldKey;
    /// Generated `{Self}Flag` enum for `when` / `required_unless` attrs.
    type Flag: FormFlagKey;

    /// Parsed submission type (`Upload` → [`UploadedFile`]).
    type Submit;

    fn field_specs() -> &'static [FieldSpec];

    fn file_field_names() -> &'static [&'static str] {
        &[]
    }

    fn multi_file_field_names() -> &'static [&'static str] {
        &[]
    }

    fn assemble_submit(parts: MultipartParts) -> Result<Self::Submit, FormError>;

    fn render_inputs(ctx: &FormCtx<'_>) -> Markup {
        render_field_specs(Self::field_specs(), ctx)
    }

    fn from_multipart(
        multipart: Multipart,
    ) -> impl std::future::Future<Output = Result<Self::Submit, FormError>> + Send {
        async move {
            let parts = collect_multipart(
                multipart,
                Self::file_field_names(),
                Self::multi_file_field_names(),
            )
            .await?;
            Self::assemble_submit(parts)
        }
    }

    /// Deserialize `application/x-www-form-urlencoded` bodies (supports duplicate keys).
    fn from_urlencoded(body: &[u8]) -> Result<Self, FormError>
    where
        Self: serde::de::DeserializeOwned,
    {
        urlencoded::deserialize_urlencoded(body)
    }
}

/// Runtime values, errors, and flags for rendering a form.
///
/// Construct only via [`FormCtx::form`] and its [`FormCtxBuilder`].
#[derive(Default)]
pub struct FormCtx<'a> {
    values: HashMap<&'a str, Cow<'a, str>>,
    checked: HashMap<&'a str, bool>,
    errors: HashMap<&'a str, &'a str>,
    flags: HashMap<&'a str, bool>,
    choices: HashMap<&'a str, &'a [(String, String)]>,
    m2m: HashMap<&'a str, &'a [ManyToManyItem]>,
    lists: HashMap<&'a str, &'a [String]>,
    displays: HashMap<&'a str, &'a str>,
    urls: HashMap<&'a str, &'a str>,
    labels: HashMap<&'a str, &'a str>,
    hints: HashMap<&'a str, &'a str>,
    /// Alpine.js `x-data` object literal wrapping the rendered inputs.
    x_data: Option<&'a str>,
    kind_locked: bool,
}

impl FormCtx<'_> {
    /// Start a type-safe builder keyed to `F`'s generated field / flag enums.
    pub fn form<'a, F: HtmlForm>() -> FormCtxBuilder<'a, F> {
        FormCtxBuilder {
            ctx: FormCtx::default(),
            _form: PhantomData,
        }
    }
}

impl<'a> FormCtx<'a> {
    pub(crate) fn set_value(mut self, name: &'a str, value: impl Into<Cow<'a, str>>) -> Self {
        self.values.insert(name, value.into());
        self
    }

    pub(crate) fn set_checked(mut self, name: &'a str, checked: bool) -> Self {
        self.checked.insert(name, checked);
        self
    }

    pub(crate) fn set_error(mut self, key: &'a str, error: Option<&'a str>) -> Self {
        if let Some(msg) = error.filter(|m| !m.is_empty()) {
            self.errors.insert(key, msg);
        }
        self
    }

    pub(crate) fn set_flag(mut self, key: &'a str, on: bool) -> Self {
        self.flags.insert(key, on);
        self
    }

    pub(crate) fn set_choices(mut self, key: &'a str, choices: &'a [(String, String)]) -> Self {
        self.choices.insert(key, choices);
        self
    }

    pub(crate) fn set_m2m(mut self, name: &'a str, items: &'a [ManyToManyItem]) -> Self {
        self.m2m.insert(name, items);
        self
    }

    pub(crate) fn set_list(mut self, name: &'a str, items: &'a [String]) -> Self {
        self.lists.insert(name, items);
        self
    }

    pub(crate) fn set_display(mut self, key: &'a str, display: &'a str) -> Self {
        self.displays.insert(key, display);
        self
    }

    pub(crate) fn set_url(mut self, name: &'a str, url: &'a str) -> Self {
        self.urls.insert(name, url);
        self
    }

    pub(crate) fn set_label(mut self, name: &'a str, label: &'a str) -> Self {
        self.labels.insert(name, label);
        self
    }

    pub(crate) fn set_hint(mut self, name: &'a str, hint: &'a str) -> Self {
        self.hints.insert(name, hint);
        self
    }

    pub(crate) fn set_x_data(mut self, data: &'a str) -> Self {
        self.x_data = Some(data);
        self
    }

    pub(crate) fn set_lock_kind(mut self, locked: bool) -> Self {
        self.kind_locked = locked;
        self
    }

    pub fn kind_locked(&self) -> bool {
        self.kind_locked
    }

    pub fn flag_on(&self, key: &str) -> bool {
        self.flags.get(key).copied().unwrap_or(false)
    }

    pub fn value_of(&self, name: &str) -> &str {
        self.values.get(name).map(|c| c.as_ref()).unwrap_or("")
    }

    pub fn checked_of(&self, name: &str) -> bool {
        self.checked.get(name).copied().unwrap_or(false)
    }

    pub fn label_of(&self, spec: &FieldSpec) -> &str {
        self.labels.get(spec.name).copied().unwrap_or(spec.label)
    }

    pub fn hint_of(&self, spec: &FieldSpec) -> Option<&str> {
        self.hints
            .get(spec.name)
            .copied()
            .or(spec.hint)
            .filter(|h| !h.is_empty())
    }

    pub fn url_of(&self, spec: &FieldSpec) -> &str {
        self.urls.get(spec.name).copied().or(spec.url).unwrap_or("")
    }

    pub fn display_of(&self, key: &str) -> &str {
        self.displays
            .get(key)
            .copied()
            .or_else(|| self.values.get(key).map(|c| c.as_ref()))
            .unwrap_or("")
    }

    pub fn choices_of(&self, key: &str) -> &[(String, String)] {
        self.choices.get(key).copied().unwrap_or(&[])
    }

    pub fn m2m_of(&self, name: &str) -> &[ManyToManyItem] {
        self.m2m.get(name).copied().unwrap_or(&[])
    }

    pub fn list_of(&self, name: &str) -> &[String] {
        self.lists.get(name).copied().unwrap_or(&[])
    }

    pub fn error_of(&self, spec: &FieldSpec) -> Option<&str> {
        let key = spec.error_key.unwrap_or(spec.name);
        self.errors.get(key).copied()
    }
}

/// Render a tagged [`HtmlKind`] enum (radios + variant fields).
///
/// Called by the `Kind` widget; rarely invoked directly.
///
/// Inactive variants are wrapped in a `<fieldset>` that Alpine disables while
/// hidden. That keeps required controls (e.g. file uploads) out of HTML5
/// constraint validation so the browser does not fail with
/// "invalid form control … is not focusable" when another kind is selected.
pub fn render_kind<K: HtmlKind>(ctx: &FormCtx<'_>, field: &FieldRender<'_>) -> Markup {
    let tag = K::kind_tag();
    let model = K::kind_model();
    let selected = {
        let v = ctx.value_of(field.name);
        if v.is_empty() { ctx.value_of(tag) } else { v }
    };
    let selected = if selected.is_empty() {
        K::variants().first().map(|v| v.value).unwrap_or("")
    } else {
        selected
    };

    if ctx.kind_locked() {
        let mut out = Markup::default();
        for variant in K::variants() {
            if variant.value == selected {
                out = html! { (out) (render_field_specs(variant.fields, ctx)) };
            }
        }
        return out;
    }

    let options: Vec<crate::components::InputRadioOption<'_>> = K::variants()
        .iter()
        .map(|v| crate::components::InputRadioOption {
            value: v.value,
            label: v.label,
            checked: v.value == selected,
        })
        .collect();
    let radios = crate::components::input_radio_group(crate::components::InputRadioGroup {
        label: if field.label.is_empty() {
            ""
        } else {
            field.label
        },
        name: tag,
        options: &options,
        attrs: crate::components::HtmlAttrs::new().set("x-model", model),
        ..Default::default()
    });

    let mut body = radios;
    for variant in K::variants() {
        let expr = format!("{model} === '{}'", variant.value);
        let inactive = format!("!({expr})");
        let fields = render_field_specs(variant.fields, ctx);
        body = html! {
            (body)
            fieldset class="border-0 p-0 m-0 min-w-0" x-show=(expr) x-bind:disabled=(inactive) {
                (fields)
            }
        };
    }

    let x_data = format!("{{ {model}: '{selected}' }}");
    html! {
        div x-data=(x_data) {
            (body)
        }
    }
}

/// Render field specs with optional row grouping and Alpine wrapper.
pub fn render_field_specs(specs: &[FieldSpec], ctx: &FormCtx<'_>) -> Markup {
    let visible: Vec<&FieldSpec> = specs.iter().filter(|s| is_visible(s, ctx)).collect();
    let mut out = Markup::default();
    let mut i = 0;
    while i < visible.len() {
        let spec = visible[i];
        if let Some(row_id) = spec.row {
            let start = i;
            i += 1;
            while i < visible.len() && visible[i].row == Some(row_id) {
                i += 1;
            }
            let group = &visible[start..i];
            let n = group.len();
            let class = format!("grid grid-cols-1 gap-1 @md:grid-cols-{n}");
            let cells = html! {
                @for s in group.iter() {
                    (render_one(s, ctx))
                }
            };
            out = html! { (out) (container_row(&class, cells)) };
        } else {
            out = html! { (out) (render_one(spec, ctx)) };
            i += 1;
        }
    }
    match ctx.x_data {
        Some(data) => html! {
            div x-data=(data) {
                (out)
            }
        },
        None => out,
    }
}

fn is_visible(spec: &FieldSpec, ctx: &FormCtx<'_>) -> bool {
    match spec.when {
        Some(flag) => ctx.flag_on(flag),
        None => true,
    }
}

/// Whether a field is required given `required_unless` flags.
pub fn field_required(spec: &FieldSpec, ctx: &FormCtx<'_>) -> bool {
    if let Some(flag) = spec.required_unless {
        return !ctx.flag_on(flag);
    }
    spec.required
}

fn render_one(spec: &FieldSpec, ctx: &FormCtx<'_>) -> Markup {
    let required = field_required(spec, ctx);
    let field = FieldRender {
        name: spec.name,
        label: ctx.label_of(spec),
        value: ctx.value_of(spec.name),
        required,
        spec,
    };
    let markup = (spec.render)(ctx, &field);
    let wrapped = container_error(ctx.error_of(spec), markup);
    match spec.show {
        Some(expr) => {
            let inactive = format!("!({expr})");
            html! {
                fieldset class="border-0 p-0 m-0 min-w-0" x-show=(expr) x-bind:disabled=(inactive) {
                    (wrapped)
                }
            }
        }
        None => wrapped,
    }
}

#[cfg(test)]
mod tests {
    use super::{FormCtx, UrlencodedFields, form_vec_i64, form_vec_string};
    use serde::Deserialize;

    #[test]
    fn form_vec_string_accepts_single_urlencoded_value() {
        let form: ModelsForm =
            serde_json::from_value(serde_json::json!({"models": "tallies"})).expect("single model");
        assert_eq!(form.models, vec!["tallies".to_string()]);
    }

    #[test]
    fn form_vec_string_accepts_multiple_urlencoded_values() {
        let form: ModelsForm = serde_json::from_value(serde_json::json!({
            "models": ["tallies", "tot_school_sessions"]
        }))
        .expect("multiple models");
        assert_eq!(
            form.models,
            vec!["tallies".to_string(), "tot_school_sessions".to_string()]
        );
    }

    #[derive(Debug, Deserialize)]
    struct ModelsForm {
        #[serde(default, rename = "models", deserialize_with = "form_vec_string")]
        models: Vec<String>,
    }

    #[derive(Debug, Deserialize)]
    struct TagsForm {
        #[serde(rename = "Tags", default, deserialize_with = "form_vec_i64")]
        tags: Vec<i64>,
    }

    #[test]
    fn preprocess_numeric_form_value_strips_commas() {
        assert_eq!(
            super::preprocess_numeric_form_value("1,234").as_ref(),
            "1234"
        );
        assert_eq!(
            super::preprocess_numeric_form_value(" 1,234.50 ").as_ref(),
            "1234.50"
        );
        assert_eq!(super::preprocess_numeric_form_value("42").as_ref(), "42");
    }

    #[test]
    fn empty_str_as_i64_strips_commas() {
        #[derive(Debug, Deserialize)]
        struct NumForm {
            #[serde(deserialize_with = "super::empty_str_as_i64")]
            n: i64,
        }
        let form: NumForm =
            serde_json::from_value(serde_json::json!({"n": "1,234"})).expect("comma int");
        assert_eq!(form.n, 1234);
    }

    #[test]
    fn form_vec_i64_accepts_single_urlencoded_value() {
        let form: TagsForm =
            serde_json::from_value(serde_json::json!({"Tags": "1"})).expect("single tag");
        assert_eq!(form.tags, vec![1]);
    }

    #[test]
    fn form_vec_i64_accepts_multiple_urlencoded_values() {
        let form: TagsForm =
            serde_json::from_value(serde_json::json!({"Tags": ["1", "2"]})).expect("multiple tags");
        assert_eq!(form.tags, vec![1, 2]);
    }

    #[test]
    fn form_vec_i64_accepts_urlencoded_fields() {
        let mut fields = UrlencodedFields::default();
        fields.push("Tags", "1");
        let form: TagsForm = fields.deserialize().expect("urlencoded fields");
        assert_eq!(form.tags, vec![1]);
    }

    #[test]
    fn display_of_falls_back_to_value_map() {
        let ctx = FormCtx::default().set_value("parent_display", "Cash");
        assert_eq!(ctx.display_of("parent_display"), "Cash");
    }

    #[test]
    fn display_of_prefers_display_map() {
        let ctx = FormCtx::default()
            .set_value("parent_display", "wrong")
            .set_display("parent_display", "Cash");
        assert_eq!(ctx.display_of("parent_display"), "Cash");
    }
}