reratui 1.1.0

A modern, reactive TUI framework for Rust with React-inspired hooks and components, powered by ratatui
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
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
//! Form management hooks with validation.
//!
//! This module provides React-like form hooks for managing form state,
//! validation, and field watching using the fiber architecture.
//!
//! # Example
//!
//! ```rust,ignore
//! use reratui_fiber::hooks::{use_form, use_form_context, use_watch};
//!
//! #[component]
//! fn MyForm() -> Element {
//!     let form = use_form(
//!         FormConfig::builder()
//!             .field("email", "")
//!             .field("password", "")
//!             .validator("email", Validator::required("Email is required"))
//!             .validator("email", Validator::email("Invalid email format"))
//!             .on_submit(|values| {
//!                 println!("Form submitted: {:?}", values);
//!             })
//!             .build()
//!     );
//!
//!     rsx! {
//!         <Block>
//!             <FormField field_name={"email"} />
//!         </Block>
//!     }
//! }
//!
//! #[component]
//! fn FormField(field_name: &str) -> Element {
//!     let form = use_form_context();
//!     let value = use_watch(&form, field_name);
//!     
//!     rsx! { <Text text={value} /> }
//! }
//! ```

use regex::Regex;
use std::collections::HashMap;
use std::sync::{Arc, OnceLock};

use super::{use_context, use_context_provider, use_state};
use crate::fiber_tree::with_current_fiber;

// ============================================================================
// Validator
// ============================================================================

/// Validator for form fields.
///
/// Provides common validation rules like required, min/max length, email, etc.
#[derive(Clone)]
pub struct Validator {
    #[allow(clippy::type_complexity)]
    validate_fn: Arc<dyn Fn(&str) -> Option<String> + Send + Sync>,
}

impl Validator {
    /// Create a custom validator with a validation function.
    ///
    /// The function should return `Some(error_message)` if validation fails,
    /// or `None` if validation passes.
    pub fn custom<F>(validate_fn: F) -> Self
    where
        F: Fn(&str) -> Option<String> + Send + Sync + 'static,
    {
        Self {
            validate_fn: Arc::new(validate_fn),
        }
    }

    /// Validate a value, returning an error message if validation fails.
    pub fn validate(&self, value: &str) -> Option<String> {
        (self.validate_fn)(value)
    }

    /// Required field validator.
    pub fn required(message: &'static str) -> Self {
        Self::custom(move |value| {
            if value.trim().is_empty() {
                Some(message.to_string())
            } else {
                None
            }
        })
    }

    /// Minimum length validator.
    pub fn min_length(min: usize, message: &'static str) -> Self {
        Self::custom(move |value| {
            if value.len() < min {
                Some(message.to_string())
            } else {
                None
            }
        })
    }

    /// Maximum length validator.
    pub fn max_length(max: usize, message: &'static str) -> Self {
        Self::custom(move |value| {
            if value.len() > max {
                Some(message.to_string())
            } else {
                None
            }
        })
    }

    /// Email format validator.
    pub fn email(message: &'static str) -> Self {
        static EMAIL_REGEX: OnceLock<Regex> = OnceLock::new();

        Self::custom(move |value| {
            let regex = EMAIL_REGEX.get_or_init(|| {
                Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap()
            });

            if value.is_empty() || regex.is_match(value) {
                None
            } else {
                Some(message.to_string())
            }
        })
    }

    /// URL format validator.
    pub fn url(message: &'static str) -> Self {
        static URL_REGEX: OnceLock<Regex> = OnceLock::new();

        Self::custom(move |value| {
            let regex =
                URL_REGEX.get_or_init(|| Regex::new(r"^https?://[^\s/$.?#].[^\s]*$").unwrap());

            if value.is_empty() || regex.is_match(value) {
                None
            } else {
                Some(message.to_string())
            }
        })
    }

    /// Numeric validator.
    pub fn numeric(message: &'static str) -> Self {
        Self::custom(move |value| {
            if value.is_empty() || value.parse::<f64>().is_ok() {
                None
            } else {
                Some(message.to_string())
            }
        })
    }

    /// Integer validator.
    pub fn integer(message: &'static str) -> Self {
        Self::custom(move |value| {
            if value.is_empty() || value.parse::<i64>().is_ok() {
                None
            } else {
                Some(message.to_string())
            }
        })
    }

    /// Pattern (regex) validator.
    pub fn pattern(pattern: &'static str, message: &'static str) -> Self {
        Self::custom(move |value| {
            let regex = Regex::new(pattern).unwrap();
            if value.is_empty() || regex.is_match(value) {
                None
            } else {
                Some(message.to_string())
            }
        })
    }

    /// Minimum value validator (for numeric fields).
    pub fn min(min: f64, message: &'static str) -> Self {
        Self::custom(move |value| {
            if let Ok(num) = value.parse::<f64>() {
                if num < min {
                    Some(message.to_string())
                } else {
                    None
                }
            } else {
                None
            }
        })
    }

    /// Maximum value validator (for numeric fields).
    pub fn max(max: f64, message: &'static str) -> Self {
        Self::custom(move |value| {
            if let Ok(num) = value.parse::<f64>() {
                if num > max {
                    Some(message.to_string())
                } else {
                    None
                }
            } else {
                None
            }
        })
    }

    /// Range validator (for numeric fields).
    pub fn range(min: f64, max: f64, message: &'static str) -> Self {
        Self::custom(move |value| {
            if let Ok(num) = value.parse::<f64>() {
                if num < min || num > max {
                    Some(message.to_string())
                } else {
                    None
                }
            } else {
                None
            }
        })
    }

    /// Alphanumeric validator.
    pub fn alphanumeric(message: &'static str) -> Self {
        Self::custom(move |value| {
            if value.is_empty() || value.chars().all(|c| c.is_alphanumeric()) {
                None
            } else {
                Some(message.to_string())
            }
        })
    }

    /// Alpha (letters only) validator.
    pub fn alpha(message: &'static str) -> Self {
        Self::custom(move |value| {
            if value.is_empty() || value.chars().all(|c| c.is_alphabetic()) {
                None
            } else {
                Some(message.to_string())
            }
        })
    }

    /// Matches another value validator.
    pub fn matches(other_value: String, message: &'static str) -> Self {
        Self::custom(move |value| {
            if value == other_value {
                None
            } else {
                Some(message.to_string())
            }
        })
    }
}

// ============================================================================
// Form Configuration
// ============================================================================

/// Configuration for form initialization.
#[derive(Clone)]
pub struct FormConfig {
    /// Initial values for form fields.
    pub(crate) initial_values: HashMap<String, String>,
    /// Validators for each field.
    pub(crate) validators: HashMap<String, Vec<Validator>>,
    /// Callback when form is submitted.
    pub(crate) on_submit: Arc<dyn Fn(HashMap<String, String>) + Send + Sync>,
}

impl FormConfig {
    /// Create a new FormConfig builder.
    pub fn builder() -> FormConfigBuilder {
        FormConfigBuilder::new()
    }
}

/// Builder for creating FormConfig with a fluent API.
pub struct FormConfigBuilder {
    initial_values: HashMap<String, String>,
    validators: HashMap<String, Vec<Validator>>,
    #[allow(clippy::type_complexity)]
    on_submit: Option<Arc<dyn Fn(HashMap<String, String>) + Send + Sync>>,
}

impl FormConfigBuilder {
    /// Create a new form configuration builder.
    pub fn new() -> Self {
        Self {
            initial_values: HashMap::new(),
            validators: HashMap::new(),
            on_submit: None,
        }
    }

    /// Add a field with an initial value.
    pub fn field(mut self, name: impl Into<String>, initial_value: impl Into<String>) -> Self {
        self.initial_values
            .insert(name.into(), initial_value.into());
        self
    }

    /// Add multiple fields at once.
    pub fn fields(mut self, fields: HashMap<String, String>) -> Self {
        self.initial_values.extend(fields);
        self
    }

    /// Add validators for a specific field.
    pub fn validate(mut self, field: impl Into<String>, validators: Vec<Validator>) -> Self {
        self.validators.insert(field.into(), validators);
        self
    }

    /// Add a single validator for a field.
    pub fn validator(mut self, field: impl Into<String>, validator: Validator) -> Self {
        let field = field.into();
        self.validators.entry(field).or_default().push(validator);
        self
    }

    /// Set the submit handler.
    pub fn on_submit<F>(mut self, handler: F) -> Self
    where
        F: Fn(HashMap<String, String>) + Send + Sync + 'static,
    {
        self.on_submit = Some(Arc::new(handler));
        self
    }

    /// Build the final FormConfig.
    ///
    /// # Panics
    ///
    /// Panics if `on_submit` was not set.
    pub fn build(self) -> FormConfig {
        FormConfig {
            initial_values: self.initial_values,
            validators: self.validators,
            on_submit: self.on_submit.expect(
                "on_submit handler must be set. Use build_with_default_submit() for a no-op handler.",
            ),
        }
    }

    /// Build the FormConfig with a default no-op submit handler.
    pub fn build_with_default_submit(self) -> FormConfig {
        FormConfig {
            initial_values: self.initial_values,
            validators: self.validators,
            on_submit: self.on_submit.unwrap_or_else(|| Arc::new(|_| {})),
        }
    }
}

impl Default for FormConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Form State (internal)
// ============================================================================

/// Internal form state stored in fiber hooks.
#[derive(Clone)]
pub struct FormState {
    pub values: HashMap<String, String>,
    pub errors: HashMap<String, String>,
    pub touched: HashMap<String, bool>,
    pub is_submitting: bool,
    pub is_valid: bool,
}

impl FormState {
    fn new(initial_values: HashMap<String, String>) -> Self {
        Self {
            values: initial_values,
            errors: HashMap::new(),
            touched: HashMap::new(),
            is_submitting: false,
            is_valid: true,
        }
    }
}

// ============================================================================
// Form Handle
// ============================================================================

/// Handle for interacting with form state.
///
/// Provides methods to get/set field values, validate fields, and submit the form.
#[derive(Clone)]
pub struct FormHandle {
    pub(crate) fiber_id: crate::fiber::FiberId,
    pub(crate) hook_index: usize,
    pub(crate) validators: HashMap<String, Vec<Validator>>,
    pub(crate) on_submit: Arc<dyn Fn(HashMap<String, String>) + Send + Sync>,
}

impl FormHandle {
    /// Register a field and get its registration info.
    pub fn register(&self, name: &str) -> FieldRegistration {
        FieldRegistration {
            name: name.to_string(),
            value: self.get_value(name).unwrap_or_default(),
            error: self.get_error(name),
            touched: self.is_touched(name),
        }
    }

    /// Get the current value of a field.
    pub fn get_value(&self, name: &str) -> Option<String> {
        self.with_state(|state| state.values.get(name).cloned())
    }

    /// Set the value of a field.
    pub fn set_value(&self, name: &str, value: String) {
        let name = name.to_string();
        let validators = self.validators.clone();

        self.update_state(move |state| {
            state.values.insert(name.clone(), value.clone());

            // Validate field if it has been touched
            if state.touched.get(&name).copied().unwrap_or(false) {
                if let Some(field_validators) = validators.get(&name) {
                    for validator in field_validators {
                        if let Some(error) = validator.validate(&value) {
                            state.errors.insert(name.clone(), error);
                            return;
                        }
                    }
                }
                state.errors.remove(&name);
            }
        });
    }

    /// Get the error message for a field.
    pub fn get_error(&self, name: &str) -> Option<String> {
        self.with_state(|state| state.errors.get(name).cloned())
    }

    /// Set the error for a field.
    pub fn set_error(&self, name: &str, error: Option<String>) {
        let name = name.to_string();
        self.update_state(move |state| {
            if let Some(err) = error {
                state.errors.insert(name, err);
            } else {
                state.errors.remove(&name);
            }
        });
    }

    /// Check if a field has been touched.
    pub fn is_touched(&self, name: &str) -> bool {
        self.with_state(|state| state.touched.get(name).copied().unwrap_or(false))
    }

    /// Mark a field as touched.
    pub fn set_touched(&self, name: &str, is_touched: bool) {
        let name = name.to_string();
        self.update_state(move |state| {
            state.touched.insert(name, is_touched);
        });
    }

    /// Validate a specific field.
    pub fn validate_field(&self, name: &str, value: &str) -> bool {
        if let Some(validators) = self.validators.get(name) {
            for validator in validators {
                if let Some(error) = validator.validate(value) {
                    self.set_error(name, Some(error));
                    return false;
                }
            }
        }
        self.set_error(name, None);
        true
    }

    /// Validate all fields in the form.
    pub fn validate_all(&self) -> bool {
        let values = self.get_values();
        let mut all_valid = true;

        for (name, value) in values.iter() {
            if !self.validate_field(name, value) {
                all_valid = false;
            }
        }

        self.update_state(move |state| {
            state.is_valid = all_valid;
        });

        all_valid
    }

    /// Reset the form to initial values.
    pub fn reset(&self, initial_values: HashMap<String, String>) {
        self.update_state(move |state| {
            state.values = initial_values;
            state.errors = HashMap::new();
            state.touched = HashMap::new();
            state.is_submitting = false;
            state.is_valid = true;
        });
    }

    /// Submit the form.
    pub fn submit(&self) {
        // Mark all fields as touched
        let values = self.get_values();
        let mut touched = HashMap::new();
        for name in values.keys() {
            touched.insert(name.clone(), true);
        }

        self.update_state(move |state| {
            state.touched = touched;
        });

        // Validate all fields
        if self.validate_all() {
            self.update_state(|state| {
                state.is_submitting = true;
            });

            let values = self.get_values();
            (self.on_submit)(values);

            self.update_state(|state| {
                state.is_submitting = false;
            });
        }
    }

    /// Check if the form is currently submitting.
    pub fn is_submitting(&self) -> bool {
        self.with_state(|state| state.is_submitting)
    }

    /// Check if the form is valid.
    pub fn is_valid(&self) -> bool {
        self.with_state(|state| state.is_valid)
    }

    /// Get all form values.
    pub fn get_values(&self) -> HashMap<String, String> {
        self.with_state(|state| state.values.clone())
    }

    /// Get all errors.
    pub fn get_errors(&self) -> HashMap<String, String> {
        self.with_state(|state| state.errors.clone())
    }

    /// Check if the form has any errors.
    pub fn has_errors(&self) -> bool {
        self.with_state(|state| !state.errors.is_empty())
    }

    /// Check if any field is dirty (modified from initial value).
    pub fn is_dirty(&self) -> bool {
        self.with_state(|state| !state.touched.is_empty())
    }

    // Internal helper to read state
    fn with_state<R, F: FnOnce(&FormState) -> R>(&self, f: F) -> R {
        crate::fiber_tree::with_fiber_tree(|tree| {
            let fiber = tree.get(self.fiber_id).expect("Fiber not found");
            let state = fiber
                .get_hook::<FormState>(self.hook_index)
                .expect("Form state not found");
            f(&state)
        })
        .expect("with_state must be called within a fiber context")
    }

    // Internal helper to update state
    fn update_state<F: FnOnce(&mut FormState) + Send + 'static>(&self, f: F) {
        use crate::scheduler::batch::{StateUpdate, StateUpdateKind, queue_update};

        queue_update(
            self.fiber_id,
            StateUpdate {
                hook_index: self.hook_index,
                update: StateUpdateKind::Updater(Box::new(move |any| {
                    let mut state = any
                        .downcast_ref::<FormState>()
                        .expect("Form state type mismatch")
                        .clone();
                    f(&mut state);
                    Box::new(state)
                })),
            },
        );
    }
}

// ============================================================================
// Field Registration
// ============================================================================

/// Field registration information.
#[derive(Debug, Clone)]
pub struct FieldRegistration {
    /// Field name.
    pub name: String,
    /// Current field value.
    pub value: String,
    /// Current error message, if any.
    pub error: Option<String>,
    /// Whether the field has been touched.
    pub touched: bool,
}

impl FieldRegistration {
    /// Check if the field has an error.
    pub fn has_error(&self) -> bool {
        self.error.is_some()
    }

    /// Get the error message.
    pub fn error_message(&self) -> Option<&str> {
        self.error.as_deref()
    }
}

// ============================================================================
// Form Hooks
// ============================================================================

/// Form hook for managing form state, validation, and submission.
///
/// Automatically provides the form to child components via context,
/// allowing them to access it using `use_form_context()`.
///
/// # Example
///
/// ```rust,ignore
/// use reratui_fiber::hooks::{use_form, FormConfig, Validator};
///
/// #[component]
/// fn MyForm() -> Element {
///     let form = use_form(
///         FormConfig::builder()
///             .field("email", "")
///             .field("password", "")
///             .validator("email", Validator::required("Email is required"))
///             .validator("email", Validator::email("Invalid email format"))
///             .on_submit(|values| {
///                 println!("Form submitted: {:?}", values);
///             })
///             .build()
///     );
///
///     let email_reg = form.register("email");
///
///     rsx! {
///         <Block>
///             <FormField field_name={"email"} />
///         </Block>
///     }
/// }
/// ```
pub fn use_form(config: FormConfig) -> FormHandle {
    let (fiber_id, hook_index) = with_current_fiber(|fiber| {
        let hook_index = fiber.next_hook_index();

        // Initialize form state if not already present
        if fiber.get_hook::<FormState>(hook_index).is_none() {
            fiber.set_hook(hook_index, FormState::new(config.initial_values.clone()));
        }

        (fiber.id, hook_index)
    })
    .expect("use_form must be called within a component render context");

    let handle = FormHandle {
        fiber_id,
        hook_index,
        validators: config.validators,
        on_submit: config.on_submit,
    };

    // Provide form to child components via context
    use_context_provider(|| handle.clone());

    handle
}

/// Retrieves the form context from a parent component.
///
/// This hook allows child components to access the form state without
/// having to pass it through props.
///
/// # Panics
///
/// Panics if called outside of a component that has a `use_form()` ancestor.
///
/// # Example
///
/// ```rust,ignore
/// #[component]
/// fn FormField(field_name: &str) -> Element {
///     let form = use_form_context();
///     let registration = form.register(field_name);
///     
///     rsx! {
///         <Block>
///             <Paragraph>{registration.value}</Paragraph>
///         </Block>
///     }
/// }
/// ```
pub fn use_form_context() -> FormHandle {
    use_context::<FormHandle>()
}

/// Try to retrieve the form context, returning None if not available.
pub fn try_use_form_context() -> Option<FormHandle> {
    super::try_use_context::<FormHandle>()
}

// ============================================================================
// Watch Hooks
// ============================================================================

/// Watch a single field value and re-render when it changes.
///
/// # Example
///
/// ```rust,ignore
/// #[component]
/// fn MyComponent() -> Element {
///     let form = use_form_context();
///     let email = use_watch(&form, "email");
///     
///     rsx! {
///         <Paragraph>{format!("Email: {}", email)}</Paragraph>
///     }
/// }
/// ```
pub fn use_watch(form: &FormHandle, field_name: &str) -> String {
    // Get the current value from the form's fiber state directly within the current fiber context
    let current_value = with_current_fiber(|fiber| {
        fiber
            .get_hook::<FormState>(form.hook_index)
            .map(|state| state.values.get(field_name).cloned().unwrap_or_default())
            .unwrap_or_default()
    })
    .unwrap_or_default();

    let (value, set_value) = use_state(|| current_value.clone());

    // If the form value differs from our tracked value, update it
    if current_value != value {
        set_value.set(current_value.clone());
    }

    current_value
}

/// Watch multiple field values and re-render when any of them change.
///
/// # Example
///
/// ```rust,ignore
/// #[component]
/// fn MyComponent() -> Element {
///     let form = use_form_context();
///     let values = use_watch_multiple(&form, &["email", "username"]);
///     
///     rsx! {
///         <Paragraph>{format!("Email: {}, Username: {}",
///             values.get("email").unwrap_or(&String::new()),
///             values.get("username").unwrap_or(&String::new())
///         )}</Paragraph>
///     }
/// }
/// ```
pub fn use_watch_multiple(form: &FormHandle, field_names: &[&str]) -> HashMap<String, String> {
    // Get current values from the form's fiber state directly
    let current_values: HashMap<String, String> = with_current_fiber(|fiber| {
        fiber
            .get_hook::<FormState>(form.hook_index)
            .map(|state| {
                field_names
                    .iter()
                    .map(|name| {
                        (
                            name.to_string(),
                            state.values.get(*name).cloned().unwrap_or_default(),
                        )
                    })
                    .collect()
            })
            .unwrap_or_default()
    })
    .unwrap_or_default();

    let (values, set_values) = use_state(|| current_values.clone());

    // Check if any values have changed
    if current_values != values {
        set_values.set(current_values.clone());
    }

    current_values
}

/// Watch all form values and re-render when any value changes.
///
/// # Example
///
/// ```rust,ignore
/// #[component]
/// fn FormDebugger() -> Element {
///     let form = use_form_context();
///     let all_values = use_watch_all(&form);
///     
///     rsx! {
///         <Block title={"Form Values"}>
///             {all_values.iter().map(|(key, value)| {
///                 rsx! {
///                     <Paragraph>{format!("{}: {}", key, value)}</Paragraph>
///                 }
///             })}
///         </Block>
///     }
/// }
/// ```
pub fn use_watch_all(form: &FormHandle) -> HashMap<String, String> {
    // Get current values from the form's fiber state directly
    let current_values: HashMap<String, String> = with_current_fiber(|fiber| {
        fiber
            .get_hook::<FormState>(form.hook_index)
            .map(|state| state.values.clone())
            .unwrap_or_default()
    })
    .unwrap_or_default();

    let (values, set_values) = use_state(|| current_values.clone());

    if current_values != values {
        set_values.set(current_values.clone());
    }

    current_values
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context_stack::clear_context_stack;
    use crate::fiber::FiberId;
    use crate::fiber_tree::{FiberTree, clear_fiber_tree, set_fiber_tree};

    fn setup_test_fiber() -> FiberId {
        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);
        tree.begin_render(fiber_id);
        set_fiber_tree(tree);
        fiber_id
    }

    fn cleanup_test() {
        clear_fiber_tree();
        clear_context_stack();
        crate::scheduler::batch::clear_state_batch();
    }

    fn apply_batch_and_rerender(fiber_id: FiberId) {
        crate::fiber_tree::with_fiber_tree_mut(|tree| {
            tree.end_render();
            crate::scheduler::batch::with_state_batch_mut(|batch| {
                batch.end_batch(tree);
            });
            tree.begin_render(fiber_id);
        });
    }

    // ========================================================================
    // Validator Tests
    // ========================================================================

    #[test]
    fn test_validator_required() {
        let validator = Validator::required("Field is required");

        assert!(validator.validate("").is_some());
        assert!(validator.validate("   ").is_some());
        assert!(validator.validate("value").is_none());
    }

    #[test]
    fn test_validator_min_length() {
        let validator = Validator::min_length(5, "Must be at least 5 characters");

        assert!(validator.validate("abc").is_some());
        assert!(validator.validate("abcde").is_none());
        assert!(validator.validate("abcdef").is_none());
    }

    #[test]
    fn test_validator_max_length() {
        let validator = Validator::max_length(5, "Must be at most 5 characters");

        assert!(validator.validate("abcdef").is_some());
        assert!(validator.validate("abcde").is_none());
        assert!(validator.validate("abc").is_none());
    }

    #[test]
    fn test_validator_email() {
        let validator = Validator::email("Invalid email");

        assert!(validator.validate("invalid").is_some());
        assert!(validator.validate("test@").is_some());
        assert!(validator.validate("test@example.com").is_none());
        assert!(validator.validate("user.name+tag@example.co.uk").is_none());
        assert!(validator.validate("").is_none()); // Empty is valid (use required for that)
    }

    #[test]
    fn test_validator_numeric() {
        let validator = Validator::numeric("Must be a number");

        assert!(validator.validate("abc").is_some());
        assert!(validator.validate("123").is_none());
        assert!(validator.validate("123.45").is_none());
        assert!(validator.validate("-123.45").is_none());
    }

    #[test]
    fn test_validator_range() {
        let validator = Validator::range(0.0, 100.0, "Must be between 0 and 100");

        assert!(validator.validate("-1").is_some());
        assert!(validator.validate("101").is_some());
        assert!(validator.validate("50").is_none());
        assert!(validator.validate("0").is_none());
        assert!(validator.validate("100").is_none());
    }

    #[test]
    fn test_validator_custom() {
        let validator = Validator::custom(|value| {
            if value.starts_with("test") {
                None
            } else {
                Some("Must start with 'test'".to_string())
            }
        });

        assert!(validator.validate("hello").is_some());
        assert!(validator.validate("test123").is_none());
    }

    // ========================================================================
    // FormConfig Tests
    // ========================================================================

    #[test]
    fn test_form_config_builder() {
        let config = FormConfig::builder()
            .field("email", "test@example.com")
            .field("name", "John")
            .validator("email", Validator::required("Email required"))
            .on_submit(|_| {})
            .build();

        assert_eq!(
            config.initial_values.get("email"),
            Some(&"test@example.com".to_string())
        );
        assert_eq!(config.initial_values.get("name"), Some(&"John".to_string()));
        assert!(config.validators.contains_key("email"));
    }

    #[test]
    fn test_form_config_builder_with_default_submit() {
        let config = FormConfig::builder()
            .field("email", "")
            .build_with_default_submit();

        assert!(config.initial_values.contains_key("email"));
    }

    #[test]
    #[should_panic(expected = "on_submit handler must be set")]
    fn test_form_config_builder_panics_without_submit() {
        let _ = FormConfig::builder().field("email", "").build();
    }

    // ========================================================================
    // use_form Tests
    // ========================================================================

    #[test]
    fn test_use_form_initializes_state() {
        let _fiber_id = setup_test_fiber();

        let form = use_form(
            FormConfig::builder()
                .field("email", "test@example.com")
                .field("name", "John")
                .on_submit(|_| {})
                .build(),
        );

        assert_eq!(
            form.get_value("email"),
            Some("test@example.com".to_string())
        );
        assert_eq!(form.get_value("name"), Some("John".to_string()));
        assert!(!form.is_submitting());
        assert!(form.is_valid());

        cleanup_test();
    }

    #[test]
    fn test_use_form_set_value() {
        let fiber_id = setup_test_fiber();

        let form = use_form(
            FormConfig::builder()
                .field("email", "")
                .on_submit(|_| {})
                .build(),
        );

        form.set_value("email", "new@example.com".to_string());

        // Apply batch and re-render
        apply_batch_and_rerender(fiber_id);

        // Re-create form handle to get updated state
        let form = use_form(
            FormConfig::builder()
                .field("email", "")
                .on_submit(|_| {})
                .build(),
        );

        assert_eq!(form.get_value("email"), Some("new@example.com".to_string()));

        cleanup_test();
    }

    #[test]
    fn test_use_form_touched_state() {
        let fiber_id = setup_test_fiber();

        let form = use_form(
            FormConfig::builder()
                .field("email", "")
                .on_submit(|_| {})
                .build(),
        );

        assert!(!form.is_touched("email"));

        form.set_touched("email", true);
        apply_batch_and_rerender(fiber_id);

        let form = use_form(
            FormConfig::builder()
                .field("email", "")
                .on_submit(|_| {})
                .build(),
        );

        assert!(form.is_touched("email"));

        cleanup_test();
    }

    #[test]
    fn test_use_form_validation() {
        let _fiber_id = setup_test_fiber();

        let form = use_form(
            FormConfig::builder()
                .field("email", "")
                .validator("email", Validator::required("Email is required"))
                .on_submit(|_| {})
                .build(),
        );

        // Validate empty field
        let is_valid = form.validate_field("email", "");
        assert!(!is_valid);

        // Validate non-empty field
        let is_valid = form.validate_field("email", "test@example.com");
        assert!(is_valid);

        cleanup_test();
    }

    #[test]
    fn test_use_form_register() {
        let _fiber_id = setup_test_fiber();

        let form = use_form(
            FormConfig::builder()
                .field("email", "test@example.com")
                .on_submit(|_| {})
                .build(),
        );

        let registration = form.register("email");

        assert_eq!(registration.name, "email");
        assert_eq!(registration.value, "test@example.com");
        assert!(registration.error.is_none());
        assert!(!registration.touched);

        cleanup_test();
    }

    #[test]
    fn test_use_form_reset() {
        let fiber_id = setup_test_fiber();

        let form = use_form(
            FormConfig::builder()
                .field("email", "initial@example.com")
                .on_submit(|_| {})
                .build(),
        );

        form.set_value("email", "changed@example.com".to_string());
        form.set_touched("email", true);
        apply_batch_and_rerender(fiber_id);

        let form = use_form(
            FormConfig::builder()
                .field("email", "initial@example.com")
                .on_submit(|_| {})
                .build(),
        );

        // Reset to new initial values
        let mut new_initial = HashMap::new();
        new_initial.insert("email".to_string(), "reset@example.com".to_string());
        form.reset(new_initial);

        apply_batch_and_rerender(fiber_id);

        let form = use_form(
            FormConfig::builder()
                .field("email", "initial@example.com")
                .on_submit(|_| {})
                .build(),
        );

        assert_eq!(
            form.get_value("email"),
            Some("reset@example.com".to_string())
        );
        assert!(!form.is_touched("email"));

        cleanup_test();
    }

    #[test]
    fn test_use_form_get_all_values() {
        let _fiber_id = setup_test_fiber();

        let form = use_form(
            FormConfig::builder()
                .field("email", "test@example.com")
                .field("name", "John")
                .on_submit(|_| {})
                .build(),
        );

        let values = form.get_values();

        assert_eq!(values.len(), 2);
        assert_eq!(values.get("email"), Some(&"test@example.com".to_string()));
        assert_eq!(values.get("name"), Some(&"John".to_string()));

        cleanup_test();
    }

    // ========================================================================
    // use_form_context Tests
    // ========================================================================

    #[test]
    fn test_use_form_context() {
        let _fiber_id = setup_test_fiber();

        // Create form (which provides context)
        let _form = use_form(
            FormConfig::builder()
                .field("email", "context@example.com")
                .on_submit(|_| {})
                .build(),
        );

        // Get form from context
        let form_from_context = use_form_context();

        assert_eq!(
            form_from_context.get_value("email"),
            Some("context@example.com".to_string())
        );

        cleanup_test();
    }

    #[test]
    fn test_try_use_form_context_returns_none() {
        cleanup_test(); // Ensure clean state

        let result = try_use_form_context();
        assert!(result.is_none());
    }

    // ========================================================================
    // use_watch Tests
    // ========================================================================

    #[test]
    fn test_use_watch() {
        let _fiber_id = setup_test_fiber();

        let form = use_form(
            FormConfig::builder()
                .field("email", "watch@example.com")
                .on_submit(|_| {})
                .build(),
        );

        let value = use_watch(&form, "email");

        assert_eq!(value, "watch@example.com");

        cleanup_test();
    }

    #[test]
    fn test_use_watch_multiple() {
        let _fiber_id = setup_test_fiber();

        let form = use_form(
            FormConfig::builder()
                .field("email", "test@example.com")
                .field("name", "John")
                .on_submit(|_| {})
                .build(),
        );

        let values = use_watch_multiple(&form, &["email", "name"]);

        assert_eq!(values.get("email"), Some(&"test@example.com".to_string()));
        assert_eq!(values.get("name"), Some(&"John".to_string()));

        cleanup_test();
    }

    #[test]
    fn test_use_watch_all() {
        let _fiber_id = setup_test_fiber();

        let form = use_form(
            FormConfig::builder()
                .field("email", "test@example.com")
                .field("name", "John")
                .field("age", "30")
                .on_submit(|_| {})
                .build(),
        );

        let values = use_watch_all(&form);

        assert_eq!(values.len(), 3);
        assert_eq!(values.get("email"), Some(&"test@example.com".to_string()));
        assert_eq!(values.get("name"), Some(&"John".to_string()));
        assert_eq!(values.get("age"), Some(&"30".to_string()));

        cleanup_test();
    }

    // ========================================================================
    // FieldRegistration Tests
    // ========================================================================

    #[test]
    fn test_field_registration_has_error() {
        let reg_with_error = FieldRegistration {
            name: "email".to_string(),
            value: "".to_string(),
            error: Some("Required".to_string()),
            touched: true,
        };

        let reg_without_error = FieldRegistration {
            name: "email".to_string(),
            value: "test@example.com".to_string(),
            error: None,
            touched: true,
        };

        assert!(reg_with_error.has_error());
        assert_eq!(reg_with_error.error_message(), Some("Required"));

        assert!(!reg_without_error.has_error());
        assert_eq!(reg_without_error.error_message(), None);
    }
}