cot 0.5.0

The Rust web framework for lazy developers.
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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
use std::fmt::{Debug, Display, Formatter};

use askama::filters::HtmlSafe;
/// Derive helper that implements `AsFormField` for select-like enums and common
/// collections.
///
/// Apply this together with [`SelectChoice`] to your enum to enable using it
/// directly as a form field (`SelectField<T>`) and as multi-select via common
/// collections (`Vec<T>`, `VecDeque<T>`, `LinkedList<T>`, `HashSet<T>`, and
/// `indexmap::IndexSet<T>`).
///
/// # Examples
///
/// ```
/// use cot::form::fields::{SelectAsFormField, SelectChoice, SelectField, SelectMultipleField};
///
/// #[derive(SelectChoice, SelectAsFormField, Debug, Clone, PartialEq, Eq, Hash)]
/// enum Status {
///     Draft,
///     Published,
///     Archived,
/// }
///
/// // `Status` works with `SelectField<Status>` and `SelectMultipleField<Status>`.
/// ```
pub use cot_macros::SelectAsFormField;
/// Derive the [`SelectChoice`] trait for an enum.
///
/// This macro automatically implements the [`SelectChoice`] trait for enums,
/// allowing them to be used with [`SelectField`] and [`SelectMultipleField`]
/// form fields. The macro generates implementations for all required methods
/// based on the enum variants.
///
/// # Requirements
///
/// - The type must be an enum (not a struct or union)
/// - The enum must have at least one variant
/// - All variants must be unit variants (no associated data)
///
/// # Default Behavior
///
/// By default, the macro uses the variant name for both the ID and display
/// name:
/// - `id()` returns the variant name as a string
/// - `to_string()` returns the variant name as a string
/// - `from_str()` matches the variant name (case-sensitive)
/// - `default_choices()` returns all variants in declaration order
///
/// # Attributes
///
/// You can customize the behavior using the `#[select_choice(...)]` attribute
/// on individual enum variants:
///
/// ## `id`
///
/// Override the ID used for this variant in form submissions and HTML.
///
/// ```
/// use cot::form::fields::SelectChoice;
///
/// #[derive(SelectChoice, Debug, PartialEq)]
/// enum Status {
///     #[select_choice(id = "draft")]
///     Draft,
///     #[select_choice(id = "published")]
///     Published,
/// }
///
/// assert_eq!(Status::Draft.id(), "draft");
/// assert_eq!(Status::Published.id(), "published");
/// ```
///
/// ## `name`
///
/// Override the display name shown to users in the select dropdown.
///
/// ```
/// use cot::form::fields::SelectChoice;
///
/// #[derive(SelectChoice, Debug, PartialEq)]
/// enum Priority {
///     #[select_choice(name = "Low Priority")]
///     Low,
///     #[select_choice(name = "High Priority")]
///     High,
/// }
///
/// assert_eq!(Priority::Low.to_string(), "Low Priority");
/// assert_eq!(Priority::High.to_string(), "High Priority");
/// ```
///
/// # Error Cases
///
/// The macro will fail to compile if:
///
/// - The type is not an enum
/// - The enum has no variants
/// - Any variant has associated data (non-unit variants)
///
/// ```compile_fail
/// use cot_macros::SelectChoice;
///
/// // This will fail - structs are not supported
/// #[derive(SelectChoice)]
/// struct NotAnEnum {
///     field: String,
/// }
/// ```
///
/// ```compile_fail
/// use cot_macros::SelectChoice;
///
/// // This will fail - empty enums are not supported
/// #[derive(SelectChoice)]
/// enum EmptyEnum {}
/// ```
///
/// ```compile_fail
/// use cot_macros::SelectChoice;
///
/// // This will fail - only unit variants are supported
/// #[derive(SelectChoice)]
/// enum EnumWithData {
///     Unit,
///     WithData(String),
///     WithFields { field: i32 },
/// }
/// ```
///
/// [`SelectChoice`]: cot::form::fields::SelectChoice
/// [`SelectField`]: cot::form::fields::SelectField
/// [`SelectMultipleField`]: cot::form::fields::SelectMultipleField
pub use cot_macros::SelectChoice;
use indexmap::IndexSet;

use crate::form::fields::impl_form_field;
use crate::form::{
    FormField, FormFieldOptions, FormFieldValidationError, FormFieldValue, FormFieldValueError,
};
use crate::html::HtmlTag;

macro_rules! impl_as_form_field_mult_collection {
    (($($generics:tt)+) => $collection:ty, $element:ty $(where $($where_clause:tt)+)?) => {
        impl<$($generics)+> crate::form::AsFormField for $collection
        $(where $($where_clause)+)?
        {
            type Type = crate::form::fields::SelectMultipleField<$element>;

            fn clean_value(
                field: &Self::Type,
            ) -> Result<Self, crate::form::FormFieldValidationError> {
                let values = crate::form::fields::check_required_multiple(field)?;
                values.iter().map(|id| <$element>::from_str(id)).collect()
            }

            fn to_field_value(&self) -> String {
                String::new()
            }
        }
    };
    (() => $collection:ty, $element:ty $(where $($where_clause:tt)+)?) => {
        impl crate::form::AsFormField for $collection
        $(where $($where_clause)+)?
        {
            type Type = crate::form::fields::SelectMultipleField<$element>;

            fn clean_value(
                field: &Self::Type,
            ) -> Result<Self, crate::form::FormFieldValidationError> {
                let values = crate::form::fields::check_required_multiple(field)?;
                values.iter().map(|id| <$element>::from_str(id)).collect()
            }

            fn to_field_value(&self) -> String {
                String::new()
            }
        }
    };
}

pub(crate) use impl_as_form_field_mult_collection;

impl_form_field!(SelectField, SelectFieldOptions, "a dropdown list", T: SelectChoice + Send);

/// Custom options for a [`SelectField`].
#[derive(Debug, Clone)]
pub struct SelectFieldOptions<T> {
    /// The list of available choices for the select field.
    /// If not set, the default choices from [`SelectChoice::default_choices`]
    /// will be used.
    pub choices: Option<Vec<T>>,
    /// Custom text for the empty option when the field is not required.
    /// If not set, "—" will be used as the default empty option text.
    /// If the field is required, no empty option will be displayed, unless
    /// this is set explicitly.
    pub none_option: Option<String>,
}

impl<T> Default for SelectFieldOptions<T> {
    fn default() -> Self {
        Self {
            choices: None,
            none_option: None,
        }
    }
}

impl<T: SelectChoice + Send> Display for SelectField<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        const DEFAULT_NONE_OPTION: &str = "—";

        let value = if let Some(value) = self.value.clone() {
            IndexSet::from([value])
        } else {
            IndexSet::new()
        };

        let none_option = if let Some(none_option) = &self.custom_options.none_option {
            Some(none_option.as_str())
        } else if self.options.required {
            None
        } else {
            Some(DEFAULT_NONE_OPTION)
        };
        render_select(
            f,
            self,
            false,
            none_option,
            None,
            self.custom_options.choices.as_ref(),
            &value,
        )
    }
}

impl<T: SelectChoice + Send> HtmlSafe for SelectField<T> {}

/// A form field for a multiple-choice select box.
///
/// This field allows users to select multiple values from a predefined list of
/// choices. Unlike [`SelectField`], this field can accept multiple selections
/// and renders as a multi-select HTML element.
#[derive(Debug)]
pub struct SelectMultipleField<T> {
    options: FormFieldOptions,
    custom_options: SelectMultipleFieldOptions<T>,
    value: IndexSet<String>,
}

impl<T> SelectMultipleField<T> {
    /// Returns an iterator over the selected values as string slices.
    pub fn values(&self) -> impl Iterator<Item = &str> {
        self.value.iter().map(AsRef::as_ref)
    }
}

impl<T: SelectChoice + Send> FormField for SelectMultipleField<T> {
    type CustomOptions = SelectMultipleFieldOptions<T>;

    fn with_options(options: FormFieldOptions, custom_options: Self::CustomOptions) -> Self {
        Self {
            options,
            custom_options,
            value: IndexSet::new(),
        }
    }

    fn options(&self) -> &FormFieldOptions {
        &self.options
    }

    fn value(&self) -> Option<&str> {
        None
    }

    async fn set_value(&mut self, field: FormFieldValue<'_>) -> Result<(), FormFieldValueError> {
        self.value.insert(field.into_text().await?);
        Ok(())
    }
}

/// Custom options for a [`SelectMultipleField`].
#[derive(Debug, Clone)]
pub struct SelectMultipleFieldOptions<T> {
    /// The list of available choices for the multi-select field.
    /// If not set, the default choices from [`SelectChoice::default_choices`]
    /// will be used.
    pub choices: Option<Vec<T>>,
    /// The number of visible options in the select box.
    /// Sets the [`size`] attribute on the HTML select element.
    /// If not set, the browser's default size will be used.
    ///
    /// [`size`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/size
    pub size: Option<u32>,
}

impl<T> Default for SelectMultipleFieldOptions<T> {
    fn default() -> Self {
        Self {
            choices: None,
            size: None,
        }
    }
}

impl<T: SelectChoice + Send> Display for SelectMultipleField<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        render_select(
            f,
            self,
            true,
            None,
            self.custom_options.size,
            self.custom_options.choices.as_ref(),
            &self.value,
        )
    }
}

impl<T: SelectChoice + Send> HtmlSafe for SelectMultipleField<T> {}

fn render_select<T: FormField, S: SelectChoice>(
    f: &mut Formatter<'_>,
    field: &T,
    multiple: bool,
    empty_option: Option<&str>,
    size: Option<u32>,
    choices: Option<&Vec<S>>,
    selected: &IndexSet<String>,
) -> std::fmt::Result {
    let mut tag: HtmlTag = HtmlTag::new("select");
    tag.attr("name", field.id());
    tag.attr("id", field.id());
    if multiple {
        tag.bool_attr("multiple");
    }
    if field.options().required {
        tag.bool_attr("required");
    }

    if let Some(size) = size {
        tag.attr("size", size.to_string());
    }

    if let Some(empty_option) = empty_option {
        tag.push_tag(
            HtmlTag::new("option")
                .attr("value", "")
                .push_str(empty_option),
        );
    }

    let choices = if let Some(choices) = choices {
        choices
    } else {
        &S::default_choices()
    };
    for choice in choices {
        let mut child = HtmlTag::new("option");
        child
            .attr("value", choice.id())
            .push_str(choice.to_string());
        if selected.contains(&choice.id()) {
            child.bool_attr("selected");
        }
        tag.push_tag(child);
    }

    write!(f, "{}", tag.render())
}

pub(crate) fn check_required_multiple<T>(
    field: &SelectMultipleField<T>,
) -> Result<&IndexSet<String>, FormFieldValidationError> {
    if field.value.is_empty() {
        Err(FormFieldValidationError::Required)
    } else {
        Ok(&field.value)
    }
}

impl_as_form_field_mult_collection!((T: SelectChoice + Send) => ::std::vec::Vec<T>, T);
impl_as_form_field_mult_collection!(
    (T: SelectChoice + Send) => ::std::collections::VecDeque<T>,
    T
);
impl_as_form_field_mult_collection!(
    (T: SelectChoice + Send) => ::std::collections::LinkedList<T>,
    T
);
impl_as_form_field_mult_collection!(
    (
        T: SelectChoice + Eq + ::std::hash::Hash + Send,
        S: ::std::hash::BuildHasher + Default
    ) => ::std::collections::HashSet<T, S>,
    T
);
impl_as_form_field_mult_collection!(
    (T: SelectChoice + Eq + ::std::hash::Hash + Send) => ::indexmap::IndexSet<T>,
    T
);

/// A trait for types that can be used as choices in select fields.
///
/// This trait enables types to be used with [`SelectField`] and
/// [`SelectMultipleField`], providing the necessary methods for converting
/// between string representations and the actual type values.
///
/// # Examples
///
/// ```
/// use cot::form::FormFieldValidationError;
/// use cot::form::fields::SelectChoice;
///
/// #[derive(Debug, Clone, PartialEq)]
/// enum Status {
///     Draft,
///     Published,
///     Archived,
/// }
///
/// impl SelectChoice for Status {
///     fn default_choices() -> Vec<Self> {
///         vec![Self::Draft, Self::Published, Self::Archived]
///     }
///
///     fn from_str(s: &str) -> Result<Self, FormFieldValidationError> {
///         match s {
///             "draft" => Ok(Self::Draft),
///             "published" => Ok(Self::Published),
///             "archived" => Ok(Self::Archived),
///             _ => Err(FormFieldValidationError::invalid_value(s.to_owned())),
///         }
///     }
///
///     fn id(&self) -> String {
///         match self {
///             Self::Draft => "draft".to_string(),
///             Self::Published => "published".to_string(),
///             Self::Archived => "archived".to_string(),
///         }
///     }
///
///     fn to_string(&self) -> String {
///         match self {
///             Self::Draft => "Draft".to_string(),
///             Self::Published => "Published".to_string(),
///             Self::Archived => "Archived".to_string(),
///         }
///     }
/// }
///
/// assert_eq!(Status::from_str("draft").unwrap(), Status::Draft);
/// assert_eq!(Status::Draft.id(), "draft");
/// assert_eq!(Status::Draft.to_string(), "Draft");
/// ```
pub trait SelectChoice {
    /// Returns the default list of choices for this type.
    ///
    /// This method is called when no explicit choices are provided to a select
    /// field. The default implementation returns an empty vector.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::form::fields::SelectChoice;
    ///
    /// #[derive(Debug, Clone)]
    /// enum Color {
    ///     Red,
    ///     Green,
    ///     Blue,
    /// }
    ///
    /// impl SelectChoice for Color {
    ///     fn default_choices() -> Vec<Self> {
    ///         vec![Self::Red, Self::Green, Self::Blue]
    ///     }
    /// #
    /// #     fn from_str(_: &str) -> Result<Self, cot::form::FormFieldValidationError> {
    /// #         unimplemented!()
    /// #     }
    /// #     fn id(&self) -> String {
    /// #         unimplemented!()
    /// #     }
    /// #     fn to_string(&self) -> String {
    /// #         unimplemented!()
    /// #     }
    /// }
    ///
    /// assert_eq!(Color::default_choices().len(), 3);
    /// ```
    #[must_use]
    fn default_choices() -> Vec<Self>
    where
        Self: Sized,
    {
        vec![]
    }

    /// Converts a string representation to the choice type.
    ///
    /// This method is used during form processing to convert submitted form
    /// values back into the appropriate choice type.
    ///
    /// # Errors
    ///
    /// If the string does not match any valid choice, this method should return
    /// a `FormFieldValidationError` indicating the invalid value.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::form::FormFieldValidationError;
    /// use cot::form::fields::SelectChoice;
    ///
    /// #[derive(Debug, Clone, PartialEq)]
    /// enum Size {
    ///     Small,
    ///     Medium,
    ///     Large,
    /// }
    ///
    /// impl SelectChoice for Size {
    ///     fn from_str(s: &str) -> Result<Self, FormFieldValidationError> {
    ///         match s {
    ///             "small" => Ok(Self::Small),
    ///             "medium" => Ok(Self::Medium),
    ///             "large" => Ok(Self::Large),
    ///             _ => Err(FormFieldValidationError::invalid_value(s.to_owned())),
    ///         }
    ///     }
    /// #
    /// #     fn id(&self) -> String {
    /// #         unimplemented!()
    /// #     }
    /// #     fn to_string(&self) -> String {
    /// #         unimplemented!()
    /// #     }
    /// }
    ///
    /// assert_eq!(Size::from_str("small").unwrap(), Size::Small);
    /// assert!(Size::from_str("invalid").is_err());
    /// ```
    fn from_str(s: &str) -> Result<Self, FormFieldValidationError>
    where
        Self: Sized;

    /// Returns the unique identifier for this choice.
    ///
    /// This value is used as the `value` attribute in HTML option elements
    /// and should be unique among all choices for a given type.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::form::fields::SelectChoice;
    ///
    /// #[derive(Debug)]
    /// enum Priority {
    ///     Low,
    ///     High,
    /// }
    ///
    /// impl SelectChoice for Priority {
    ///     fn id(&self) -> String {
    ///         match self {
    ///             Self::Low => "low".to_string(),
    ///             Self::High => "high".to_string(),
    ///         }
    ///     }
    /// #
    /// #     fn from_str(_: &str) -> Result<Self, cot::form::FormFieldValidationError> {
    /// #         unimplemented!()
    /// #     }
    /// #     fn to_string(&self) -> String {
    /// #         unimplemented!()
    /// #     }
    /// }
    ///
    /// assert_eq!(Priority::Low.id(), "low");
    /// assert_eq!(Priority::High.id(), "high");
    /// ```
    fn id(&self) -> String;

    /// Returns the human-readable display text for this choice.
    ///
    /// This text is shown to users in the option elements and should be
    /// descriptive and user-friendly.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::form::fields::SelectChoice;
    ///
    /// #[derive(Debug)]
    /// enum Status {
    ///     Active,
    ///     Inactive,
    /// }
    ///
    /// impl SelectChoice for Status {
    ///     fn to_string(&self) -> String {
    ///         match self {
    ///             Self::Active => "Currently Active".to_string(),
    ///             Self::Inactive => "Currently Inactive".to_string(),
    ///         }
    ///     }
    /// #
    /// #     fn from_str(_: &str) -> Result<Self, cot::form::FormFieldValidationError> {
    /// #         unimplemented!()
    /// #     }
    /// #     fn id(&self) -> String {
    /// #         unimplemented!()
    /// #     }
    /// }
    ///
    /// assert_eq!(Status::Active.to_string(), "Currently Active");
    /// ```
    fn to_string(&self) -> String;
}

#[cfg(test)]
mod tests {
    use std::collections::{HashSet, LinkedList, VecDeque};

    use indexmap::IndexSet;

    use super::*;
    use crate::form::AsFormField;

    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
    enum TestChoice {
        Option1,
        Option2,
        Option3,
    }

    impl SelectChoice for TestChoice {
        fn default_choices() -> Vec<Self> {
            vec![Self::Option1, Self::Option2, Self::Option3]
        }

        fn from_str(s: &str) -> Result<Self, FormFieldValidationError> {
            match s {
                "opt1" => Ok(Self::Option1),
                "opt2" => Ok(Self::Option2),
                "opt3" => Ok(Self::Option3),
                _ => Err(FormFieldValidationError::invalid_value(s.to_owned())),
            }
        }

        fn id(&self) -> String {
            match self {
                Self::Option1 => "opt1".to_string(),
                Self::Option2 => "opt2".to_string(),
                Self::Option3 => "opt3".to_string(),
            }
        }

        fn to_string(&self) -> String {
            match self {
                Self::Option1 => "Option 1".to_string(),
                Self::Option2 => "Option 2".to_string(),
                Self::Option3 => "Option 3".to_string(),
            }
        }
    }

    #[test]
    fn select_field_render_default() {
        let field = SelectField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "test_select".to_owned(),
                name: "test_select".to_owned(),
                required: false,
            },
            SelectFieldOptions::default(),
        );
        let html = field.to_string();

        assert!(html.contains("<select"));
        assert!(html.contains("name=\"test_select\""));
        assert!(html.contains("id=\"test_select\""));
        assert!(!html.contains("required"));
        assert!(html.contains("—")); // default empty option
        assert!(html.contains("Option 1"));
        assert!(html.contains("Option 2"));
        assert!(html.contains("Option 3"));
        assert!(html.contains("value=\"opt1\""));
        assert!(html.contains("value=\"opt2\""));
        assert!(html.contains("value=\"opt3\""));
    }

    #[test]
    fn select_field_render_required() {
        let field = SelectField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "test_select".to_owned(),
                name: "test_select".to_owned(),
                required: true,
            },
            SelectFieldOptions::default(),
        );
        let html = field.to_string();

        assert!(html.contains("required"));
        assert!(!html.contains("—")); // no empty option for required field
    }

    #[test]
    fn select_field_render_custom_none_option() {
        let field = SelectField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "test_select".to_owned(),
                name: "test_select".to_owned(),
                required: false,
            },
            SelectFieldOptions {
                choices: None,
                none_option: Some("Please select...".to_string()),
            },
        );
        let html = field.to_string();

        assert!(html.contains("Please select..."));
        assert!(!html.contains("—"));
    }

    #[test]
    fn select_field_render_custom_choices() {
        let field = SelectField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "test_select".to_owned(),
                name: "test_select".to_owned(),
                required: false,
            },
            SelectFieldOptions {
                choices: Some(vec![TestChoice::Option1, TestChoice::Option3]),
                none_option: None,
            },
        );
        let html = field.to_string();

        assert!(html.contains("Option 1"));
        assert!(!html.contains("Option 2")); // not in custom choices
        assert!(html.contains("Option 3"));
    }

    #[cot::test]
    async fn select_field_with_value() {
        let mut field = SelectField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "test_select".to_owned(),
                name: "test_select".to_owned(),
                required: false,
            },
            SelectFieldOptions::default(),
        );

        field
            .set_value(FormFieldValue::new_text("opt2"))
            .await
            .unwrap();
        let html = field.to_string();

        assert!(html.contains("<option value=\"opt2\" selected>Option 2</option>"));
    }

    #[test]
    fn select_multiple_field_render_default() {
        let field = SelectMultipleField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "test_multi".to_owned(),
                name: "test_multi".to_owned(),
                required: false,
            },
            SelectMultipleFieldOptions::default(),
        );
        let html = field.to_string();

        assert!(html.contains("<select"));
        assert!(html.contains("multiple"));
        assert!(html.contains("name=\"test_multi\""));
        assert!(html.contains("id=\"test_multi\""));
        assert!(!html.contains("required"));
        assert!(html.contains("Option 1"));
        assert!(html.contains("Option 2"));
        assert!(html.contains("Option 3"));
    }

    #[test]
    fn select_multiple_field_render_with_size() {
        let field = SelectMultipleField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "test_multi".to_owned(),
                name: "test_multi".to_owned(),
                required: false,
            },
            SelectMultipleFieldOptions {
                choices: None,
                size: Some(5),
            },
        );
        let html = field.to_string();

        assert!(html.contains("size=\"5\""));
    }

    #[test]
    fn select_multiple_field_render_required() {
        let field = SelectMultipleField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "test_multi".to_owned(),
                name: "test_multi".to_owned(),
                required: true,
            },
            SelectMultipleFieldOptions::default(),
        );
        let html = field.to_string();

        assert!(html.contains("required"));
    }

    #[cot::test]
    async fn select_multiple_field_with_values() {
        let mut field = SelectMultipleField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "test_multi".to_owned(),
                name: "test_multi".to_owned(),
                required: false,
            },
            SelectMultipleFieldOptions::default(),
        );

        field
            .set_value(FormFieldValue::new_text("opt1"))
            .await
            .unwrap();
        field
            .set_value(FormFieldValue::new_text("opt3"))
            .await
            .unwrap();

        let html = field.to_string();
        assert!(html.contains("<option value=\"opt1\" selected>Option 1</option>"));
        assert!(html.contains("<option value=\"opt3\" selected>Option 3</option>"));
        assert!(!html.contains("<option value=\"opt2\" selected>"));

        let values: Vec<&str> = field.values().collect();
        assert_eq!(values.len(), 2);
        assert!(values.contains(&"opt1"));
        assert!(values.contains(&"opt3"));
    }

    #[test]
    fn select_choice_default_choices() {
        let choices = TestChoice::default_choices();
        assert_eq!(choices.len(), 3);
        assert_eq!(choices[0], TestChoice::Option1);
        assert_eq!(choices[1], TestChoice::Option2);
        assert_eq!(choices[2], TestChoice::Option3);
    }

    #[test]
    fn select_choice_from_str_invalid() {
        let result = TestChoice::from_str("invalid");
        assert!(result.is_err());
        if let Err(FormFieldValidationError::InvalidValue(value)) = result {
            assert_eq!(value, "invalid");
        } else {
            panic!("Expected InvalidValue error");
        }
    }

    #[test]
    fn check_required_multiple_empty() {
        let field = SelectMultipleField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "test".to_owned(),
                name: "test".to_owned(),
                required: true,
            },
            SelectMultipleFieldOptions::default(),
        );

        let result = check_required_multiple(&field);
        assert_eq!(result, Err(FormFieldValidationError::Required));
    }

    #[cot::test]
    async fn check_required_multiple_with_values() {
        let mut field = SelectMultipleField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "test".to_owned(),
                name: "test".to_owned(),
                required: true,
            },
            SelectMultipleFieldOptions::default(),
        );

        field
            .set_value(FormFieldValue::new_text("opt1"))
            .await
            .unwrap();
        let result = check_required_multiple(&field);
        assert!(result.is_ok());

        let values = result.unwrap();
        assert_eq!(values.len(), 1);
        assert!(values.contains("opt1"));
    }

    #[cot::test]
    async fn select_multiple_field_values_iterator() {
        let mut field = SelectMultipleField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "test".to_owned(),
                name: "test".to_owned(),
                required: false,
            },
            SelectMultipleFieldOptions::default(),
        );

        let values: Vec<&str> = field.values().collect();
        assert!(values.is_empty());

        field
            .set_value(FormFieldValue::new_text("opt2"))
            .await
            .unwrap();
        field
            .set_value(FormFieldValue::new_text("opt1"))
            .await
            .unwrap();
        field
            .set_value(FormFieldValue::new_text("opt2"))
            .await
            .unwrap(); // duplicate should be ignored

        let values: Vec<&str> = field.values().collect();
        assert_eq!(values.len(), 2); // IndexSet should deduplicate
        assert!(values.contains(&"opt1"));
        assert!(values.contains(&"opt2"));
    }

    #[cot::test]
    async fn vec_as_form_field_clean_value() {
        let mut field = SelectMultipleField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "choices".to_owned(),
                name: "choices".to_owned(),
                required: true,
            },
            SelectMultipleFieldOptions::default(),
        );

        field
            .set_value(FormFieldValue::new_text("opt1"))
            .await
            .unwrap();
        field
            .set_value(FormFieldValue::new_text("opt3"))
            .await
            .unwrap();

        let values = Vec::<TestChoice>::clean_value(&field).unwrap();
        assert_eq!(values, vec![TestChoice::Option1, TestChoice::Option3]);
    }

    #[cot::test]
    async fn vec_as_form_field_required_empty() {
        let field = SelectMultipleField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "choices".to_owned(),
                name: "choices".to_owned(),
                required: true,
            },
            SelectMultipleFieldOptions::default(),
        );

        let result = Vec::<TestChoice>::clean_value(&field);
        assert_eq!(result, Err(FormFieldValidationError::Required));
    }

    #[cot::test]
    async fn vec_as_form_field_invalid_value() {
        let mut field = SelectMultipleField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "choices".to_owned(),
                name: "choices".to_owned(),
                required: false,
            },
            SelectMultipleFieldOptions::default(),
        );

        field
            .set_value(FormFieldValue::new_text("opt1"))
            .await
            .unwrap();
        field
            .set_value(FormFieldValue::new_text("bad"))
            .await
            .unwrap();

        let result = Vec::<TestChoice>::clean_value(&field);
        assert!(matches!(
            result,
            Err(FormFieldValidationError::InvalidValue(value)) if value == "bad"
        ));
    }

    #[test]
    fn vec_as_form_field_to_field_value() {
        let items = vec![TestChoice::Option1, TestChoice::Option2];
        assert_eq!(items.to_field_value(), "");
    }

    #[cot::test]
    async fn vec_deque_as_form_field_clean_value() {
        let mut field = SelectMultipleField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "choices".to_owned(),
                name: "choices".to_owned(),
                required: false,
            },
            SelectMultipleFieldOptions::default(),
        );

        field
            .set_value(FormFieldValue::new_text("opt2"))
            .await
            .unwrap();
        field
            .set_value(FormFieldValue::new_text("opt1"))
            .await
            .unwrap();

        let mut values = VecDeque::<TestChoice>::clean_value(&field).unwrap();
        assert_eq!(values.pop_front(), Some(TestChoice::Option2));
        assert_eq!(values.pop_back(), Some(TestChoice::Option1));
    }

    #[cot::test]
    async fn linked_list_as_form_field_clean_value() {
        let mut field = SelectMultipleField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "choices".to_owned(),
                name: "choices".to_owned(),
                required: false,
            },
            SelectMultipleFieldOptions::default(),
        );

        field
            .set_value(FormFieldValue::new_text("opt3"))
            .await
            .unwrap();

        let mut values = LinkedList::<TestChoice>::clean_value(&field).unwrap();
        assert_eq!(values.pop_front(), Some(TestChoice::Option3));
        assert!(values.is_empty());
    }

    #[cot::test]
    async fn hash_set_as_form_field_clean_value() {
        let mut field = SelectMultipleField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "choices".to_owned(),
                name: "choices".to_owned(),
                required: false,
            },
            SelectMultipleFieldOptions::default(),
        );

        field
            .set_value(FormFieldValue::new_text("opt1"))
            .await
            .unwrap();
        field
            .set_value(FormFieldValue::new_text("opt1"))
            .await
            .unwrap();
        field
            .set_value(FormFieldValue::new_text("opt2"))
            .await
            .unwrap();

        let values = HashSet::<TestChoice>::clean_value(&field).unwrap();
        assert_eq!(values.len(), 2);
        assert!(values.contains(&TestChoice::Option1));
        assert!(values.contains(&TestChoice::Option2));
    }

    #[cot::test]
    async fn index_set_as_form_field_preserves_order() {
        let mut field = SelectMultipleField::<TestChoice>::with_options(
            FormFieldOptions {
                id: "choices".to_owned(),
                name: "choices".to_owned(),
                required: false,
            },
            SelectMultipleFieldOptions::default(),
        );

        field
            .set_value(FormFieldValue::new_text("opt2"))
            .await
            .unwrap();
        field
            .set_value(FormFieldValue::new_text("opt3"))
            .await
            .unwrap();
        field
            .set_value(FormFieldValue::new_text("opt2"))
            .await
            .unwrap();

        let values = IndexSet::<TestChoice>::clean_value(&field).unwrap();
        let mut iter = values.iter();
        assert_eq!(iter.next(), Some(&TestChoice::Option2));
        assert_eq!(iter.next(), Some(&TestChoice::Option3));
        assert_eq!(iter.next(), None);
    }

    #[derive(SelectChoice, SelectAsFormField, Debug, Clone, PartialEq, Eq, Hash)]
    enum DerivedStatus {
        #[select_choice(id = "draft", name = "Draft")]
        Draft,
        #[select_choice(id = "published", name = "Published")]
        Published,
        #[select_choice(id = "archived", name = "Archived")]
        Archived,
    }

    #[test]
    fn select_as_form_field_render() {
        let field = SelectField::<DerivedStatus>::with_options(
            FormFieldOptions {
                id: "status".to_owned(),
                name: "status".to_owned(),
                required: false,
            },
            SelectFieldOptions::default(),
        );
        let html = field.to_string();

        assert!(html.contains("<select"));
        assert!(html.contains("name=\"status\""));
        assert!(html.contains("id=\"status\""));
        assert!(html.contains("value=\"draft\""));
        assert!(html.contains("value=\"published\""));
        assert!(html.contains("value=\"archived\""));
        assert!(html.contains("Draft"));
        assert!(html.contains("Published"));
        assert!(html.contains("Archived"));
    }

    #[cot::test]
    async fn select_as_form_field_clean_value_valid() {
        let mut field = SelectField::<DerivedStatus>::with_options(
            FormFieldOptions {
                id: "status".to_owned(),
                name: "status".to_owned(),
                required: true,
            },
            SelectFieldOptions::default(),
        );

        field
            .set_value(FormFieldValue::new_text("published"))
            .await
            .unwrap();

        let value = DerivedStatus::clean_value(&field).unwrap();
        assert_eq!(value, DerivedStatus::Published);
    }

    #[cot::test]
    async fn select_as_form_field_clean_value_required_empty() {
        let mut field = SelectField::<DerivedStatus>::with_options(
            FormFieldOptions {
                id: "status".to_owned(),
                name: "status".to_owned(),
                required: true,
            },
            SelectFieldOptions::default(),
        );

        field.set_value(FormFieldValue::new_text("")).await.unwrap();

        let result = DerivedStatus::clean_value(&field);
        assert_eq!(result, Err(FormFieldValidationError::Required));
    }

    #[cot::test]
    async fn select_as_form_field_clean_value_invalid() {
        let mut field = SelectField::<DerivedStatus>::with_options(
            FormFieldOptions {
                id: "status".to_owned(),
                name: "status".to_owned(),
                required: false,
            },
            SelectFieldOptions::default(),
        );

        field
            .set_value(FormFieldValue::new_text("not-a-valid-id"))
            .await
            .unwrap();

        let result = DerivedStatus::clean_value(&field);
        assert!(matches!(
            result,
            Err(FormFieldValidationError::InvalidValue(value)) if value == "not-a-valid-id"
        ));
    }

    #[test]
    fn select_as_form_field_to_field_value() {
        assert_eq!(DerivedStatus::Draft.to_field_value(), "Draft");
        assert_eq!(DerivedStatus::Published.to_field_value(), "Published");
    }
}