ridstack-form 0.1.0

End-to-End Type-safe form handling for Dioxus applications
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
use crate::prelude::{
    AsyncValidators, FieldStateProvider, GetFieldRegistry, GetFormState, ValidateOn, Validators,
};
use crate::{form::*, traits::*};
use dioxus::core::Task;
use dioxus::prelude::*;
use either::Either;
use std::pin::Pin;
use std::time::Duration;
use std::{
    collections::{BTreeSet, HashSet},
    error::Error,
    hash::Hash,
    marker::PhantomData,
};

/// You'll get this from the component prop of the [Field].
///
///  [FieldApi] gives you all the handlers and values of a specific field.
/// You can use this info to create components for field.
/// This is type-safe and you can target specific [PrimitiveFieldValue] to get your component to
/// work on that.
/// Example:
/// This component works only to [FieldValue]s having [PrimitiveFieldValue] type as [String].
/// ``` rust, no_run
///
/// #[component]
/// fn TextField<TForm, TField>(
///     #[props(optional)] id: String,
///     field_api: ReadSignal<FieldApi<TForm, TField>>,
///     #[props(extends=GlobalAttributes,extends=input)] attributes: Vec<Attribute>,
/// ) -> Element
/// where
///     TForm: FieldStateProvider<TField>,
///     TField: Clone + PartialEq + 'static,
///     TForm::FieldValue: FieldValue<PrimitiveValue = String>,
/// {
///     rsx! {
///         label{
///             r#for: &id
///         }
///         input{
///             id,
///             value: field_api().value(),
///             onblur: field_api.peek().handlers().on_blur(),
///             oninput: move|evt|{
///                 let _ = field_api.peek().handlers().on_input()(Either::Right(evt.value()));
///
///             },
///             ..attributes
///         }
///         div{if let Some(err) = (field_api().state().errors)().get(0){
///
///             p{
///                 {err.error_value()}
///             }
///         }
///         }
///     }
/// }
///
/// ```
#[derive(Clone, PartialEq)]
pub struct FieldApi<TForm, TField>
where
    TForm: FieldStateProvider<TField>,
    TField: Clone + PartialEq + 'static,
{
    pub(crate) state:
        FieldApiState<<TForm::FieldValue as FieldValue>::PrimitiveValue, TForm::FieldError>,
    // form_state: Rc<FormState>,
    name: &'static str,
    handlers: FieldHandlers<<TForm::FieldValue as FieldValue>::PrimitiveValue>,
    pub value: ReadSignal<String>,
}

/// This provides errors of the specific type of [FieldValue] specified in [FieldStateProvider].
///
/// By default all the errors are sorted according to [Ord] implementation. They are also dedupped.
/// You'll get the errors arranged in ascending order. So while applying [Ord],
///  it's a good choice to make higher priority errors lesser
/// than lower priority errors to prevent rearranging.
#[derive(Clone, PartialEq)]
pub struct FieldErrors<TFieldError: FieldError> {
    pub(crate) errors: ReadSignal<Vec<TFieldError>>,
}

/// This provides all the errors of a field in [String] form.
///
/// By default all the errors are sorted according to [Ord] implementation. They are also dedupped.
/// You'll get the errors arranged in ascending order. So while applying [Ord],
///  it's a good choice to make higher priority errors lesser
/// than lower priority errors to prevent rearranging.
#[derive(Clone, PartialEq)]
pub struct RawFieldErrors {
    pub(crate) errors: ReadSignal<Vec<String>>,
}

impl<TForm: FieldStateProvider<TField>, TField: Clone + PartialEq + 'static>
    FieldApi<TForm, TField>
{
    pub fn state(
        &self,
    ) -> &FieldApiState<
        <<TForm as FieldStateProvider<TField>>::FieldValue as FieldValue>::PrimitiveValue,
        <TForm as FieldStateProvider<TField>>::FieldError,
    > {
        &self.state
    }

    pub fn name(&self) -> &'static str {
        self.name
    }

    pub fn handlers(
        &self,
    ) -> &FieldHandlers<
        <<TForm as FieldStateProvider<TField>>::FieldValue as FieldValue>::PrimitiveValue,
    > {
        &self.handlers
    }

    pub fn value(&self) -> String {
        (self.value)()
    }
}

/// This contains the field handlers required for updating the
/// state of the field.
/// You'll get this struct from the [FieldApi].
/// It's advised to use .peek() to prevent accidental updates.
/// Example:
/// ``` rust, no_run
/// onblur: field_api.peek().handlers().on_blur(),
/// oninput: move|evt|{
/// let _ = field_api.peek().handlers().on_input()(Either::Right(evt.value()));
/// },
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct FieldHandlers<TFieldValue: PrimitiveFieldValue> {
    on_blur: EventHandler<FocusEvent>,
    /// This takes an Either input as you can provide both the
    /// raw [String] input or if you get direct [PrimitiveFieldValue], you may insert
    /// that also.
    /// A typical use-case where [PrimitiveFieldValue] input may be needed is in the use
    /// of select components. As rust is type-safe by default, often instead of raw-strings
    /// we get objects which can be directly passed here.
    on_input: EventHandler<Either<String, TFieldValue>>,
}

impl<TFieldValue: PrimitiveFieldValue> FieldHandlers<TFieldValue> {
    pub fn on_blur(&self) -> Callback<Event<FocusData>, ()> {
        self.on_blur
    }

    pub fn on_input(&self) -> Callback<Either<String, TFieldValue>> {
        self.on_input
    }
}

/// This contains all the info about the field.
#[derive(Clone, Store)]
pub struct FieldState<TFieldValue: FieldValue, TFieldError: FieldError> {
    pub data: TFieldValue,
    pub is_dirty: bool,
    is_sync_validating: bool,
    pub is_validating: bool,
    pub is_touched: bool,
    pub errors: Vec<TFieldError>,
    pub validators: Validators<TFieldValue, TFieldError>,
    pub async_validators: AsyncValidators<TFieldValue, TFieldError>,
    pub validate_on: ValidateOn,
    validate_counter: u8,
}

#[store(pub)]
impl<Lens, TFieldValue: FieldValue, TFieldError: FieldError>
    Store<FieldState<TFieldValue, TFieldError>, Lens>
{
    // runs sync validators, sorts and dedups the errors and inserts them into the vec
    fn validate(&mut self) {
        let mut sync_errs = vec![];
        self.is_sync_validating().set(true);
        for validator in &*self.validators().peek() {
            if let Err(err) = validator.validate(&*self.data().peek()) {
                sync_errs.push(err);
            }
        }
        // self.errors().set(sync_errs);
        self.is_sync_validating().set(false);
        self.errors().with_mut(|errors| {
            *errors = sync_errs;
            errors.sort_unstable();
            errors.dedup();
        });
    }

    // runs async validators, sorts and dedups the errors and inserts them into the vec
    fn async_validate(&mut self) -> Pin<Box<impl Future<Output = ()>>> {
        *self.validate_counter().write() += 1;
        let async_validation_counter = *self.validate_counter().peek();
        Box::pin(async move {
            self.is_validating().set(true);
            for validator in &*self.async_validators().peek() {
                if let Err(err) = validator.validate(&*self.data().peek()).await {
                    if async_validation_counter == *self.validate_counter().peek()
                        && let Err(idx) = self.errors().read().binary_search(&err)
                    {
                        self.errors().insert(idx, err)
                    }
                }
            }
            self.is_validating().set(false);
        })
    }

    /// Checks whether this field is ready to be submitted.
    /// This fn is used by macros to generate code for
    /// [CalculateCanSubmit] trait.
    fn can_submit(&self) -> bool {
        !(!self.errors().peek().is_empty()
            || *self.is_sync_validating().peek()
            || *self.is_validating().peek())
    }
}

impl<TFieldValue, TFieldError> Default for FieldState<TFieldValue, TFieldError>
where
    TFieldValue: FieldValue,
    TFieldError: FieldError,
{
    fn default() -> Self {
        Self {
            is_validating: false,
            data: TFieldValue::default(),
            errors: Vec::with_capacity(0),
            is_dirty: false,
            is_touched: false,
            is_sync_validating: false,
            validate_on: ValidateOn::All,
            validators: vec![],
            async_validators: vec![],
            validate_counter: 0,
        }
    }
}

/// This is a hook. So it must be called at the top level
#[inline(always)]
pub fn use_init_field_state<T: FieldValue, TFieldError: FieldError>()
-> Store<FieldState<T, TFieldError>> {
    use_store(Default::default)
}

/// This is the state provided by [FieldApi].
/// If you get this from [Field] component prop, then the [FieldApi] will be
/// wrapped in a ReadSignal. So always use
/// fieldApi().state or fieldApi.read().state
#[derive(Clone, PartialEq)]
pub struct FieldApiState<TFieldValue: PrimitiveFieldValue, TFieldError: FieldError> {
    pub data: ReadSignal<TFieldValue>,
    pub is_validating: ReadSignal<bool>,
    pub is_dirty: ReadSignal<bool>,
    pub is_touched: ReadSignal<bool>,
    pub is_pristine: ReadSignal<bool>,
    pub is_default_value: ReadSignal<bool>,
    pub errors: ReadSignal<Vec<TFieldError>>,
}

/// If you've used `GenForm` macro, the macro will create
/// an fn over this and remove all generics except TField,
/// as [Field] component needs generics in direct usage.
///
///
/// The main component required for accessing, managing handling fields.
#[component]
pub fn Field<TForm, TField>(
    component: Callback<FieldApi<TForm::FieldRegistry, TField>, Element>,
    field: TField,
    #[props(optional)] validate_on: ValidateOn,
    #[props(optional, default = Vec::with_capacity(0))] validators: Validators<
        <TForm::FieldRegistry as FieldStateProvider<TField>>::FieldValue,
        <TForm::FieldRegistry as FieldStateProvider<TField>>::FieldError,
    >,
    #[props(optional, default = Vec::with_capacity(0))] async_validators: AsyncValidators<
        <TForm::FieldRegistry as FieldStateProvider<TField>>::FieldValue,
        <TForm::FieldRegistry as FieldStateProvider<TField>>::FieldError,
    >,
    #[props(optional)] __phantom_ctx: PhantomData<TForm>,
) -> Element
where
    TForm::FieldRegistry: FieldStateProvider<TField> + Clone + PartialEq,
    TForm: GetFieldRegistry + GetFormState,
    TField: Clone + PartialEq + 'static,
{
    let ctx = use_form::<TForm>();
    let field_registry = ctx.get_field_registry();
    let mut async_validate_task = use_signal::<Option<Task>>(|| None);
    let mut should_debounce = use_signal(|| true);
    let mut is_async_validating = use_signal(|| false);
    let mut field_state = field_registry.get_field_state(&field);
    let field_name = use_memo(move || field_registry.name(&field));
    let mut form_state = ctx.get_form_state();
    let mut revision = use_signal(|| 0usize);
    let mut value = use_signal(|| {
        <TForm::FieldRegistry as FieldStateProvider<TField>>::FieldValue::default()
            .to_string_value()
    });
    let mut is_default_value = use_signal(|| true);

    let mut is_pristine = use_signal(|| true);

    // TODO: try to make primitive field value take ref.
    let primitive_data = use_memo(move || field_state.data().read().to_primitive_field_value());

    let validate_fn = use_callback(move |_: PhantomData<bool>| {
        // let async_validator = async_validator.clone();

        field_state.is_dirty().set(true);
        field_state.is_touched().set(true);
        field_state.validate();
        #[cfg(feature = "validify")]
        {
            use validify::Validify;
            let validify_res = ctx.validate();
            if let Err(errs) = validify_res {
                let mut val_errs = errs
                    .field_errors()
                    .iter()
                    .filter_map(|e| {
                        use validify::ValidationError;

                        if let ValidationError::Field {
                            field: err_field, ..
                        } = e
                            && err_field.is_some_and(|val| val == field_name())
                        {
                            return <TForm::FieldRegistry as FieldStateProvider<TField>>::FieldError::option_from((*e).clone());
                        }
                        None
                    })
                    .collect::<Vec<_>>();
                err_snapshot.append(&mut val_errs);
            }
        }
        // err_snapshot.sort();
        // err_snapshot.dedup();
        // *field_state.errors().write() = err_snapshot;
    });
    let on_input = move |val: Either<String, <<TForm::FieldRegistry as FieldStateProvider<TField>>::FieldValue as FieldValue>::PrimitiveValue>| {
        match val {
            Either::Left(v) => {
                value.set(v);
                let data = match <TForm::FieldRegistry as FieldStateProvider<TField>>::FieldValue::from_str(
                    &*value.read(),
                )
                .map_err(|err| <TForm::FieldRegistry as FieldStateProvider<TField>>::FieldError::from(err))
                {
                    Ok(res) => res,
                    Err(err) => {
                        is_default_value.set(true);
                        field_state.errors().with_mut(move |e| {
                            e.push(err);
                        });
                        <TForm::FieldRegistry as FieldStateProvider<TField>>::FieldValue::default()
                    }
                };
                field_state.data().set(data)
            }
            Either::Right(v) => {
                field_state.data().set(v.into());
            }
        }

        if matches!(validate_on, ValidateOn::All | ValidateOn::Input) {
            async_validate_task.with_mut(|t| {
                if let Some(task) = t {
                    task.cancel();
                    *t = None;
                }
            });
            should_debounce.set(true);
            let task = spawn(async_validate(field_state.into(), should_debounce()));
            async_validate_task.set(Some(task));
            validate_fn(PhantomData);
        }
    };
    let on_blur = move |_| {
        field_state.is_touched().set(true);
        is_pristine.set(false);
        async move {
            if matches!(validate_on, ValidateOn::All | ValidateOn::Blur) {
                async_validate_task.with_mut(|t| {
                    if let Some(task) = t {
                        task.cancel();
                        *t = None;
                    }
                });
                should_debounce.set(false);
                validate_fn(PhantomData);
                let task = spawn(async_validate(field_state.into(), should_debounce()));
                async_validate_task.set(Some(task));
            }
        }
    };
    let field_api = FieldApi {
        name: field_name(),
        handlers: FieldHandlers::<<<TForm::FieldRegistry as FieldStateProvider<TField>>::FieldValue as FieldValue>::PrimitiveValue> {
            on_blur: EventHandler::new(on_blur),
            on_input: EventHandler::new(on_input),
        },
        state: FieldApiState {
            data: ReadSignal::new(primitive_data),
            is_dirty: ReadSignal::new(field_state.is_dirty()),
            is_touched: ReadSignal::new(field_state.is_touched()),
            is_validating: ReadSignal::new(field_state.is_validating()),
            is_default_value: ReadSignal::new(is_default_value),
            is_pristine: ReadSignal::new(is_pristine),
        errors: ReadSignal::new(field_state.errors()),
        },
        value: ReadSignal::new(value),
    };

    let raw_field_errors = use_memo(move || {
        (*field_state.errors().read())
            .iter()
            .map(|e| e.custom_message().unwrap_or_else(|| e.to_string()))
            .collect::<Vec<_>>()
    });
    let raw_field_errors = use_memo(move || RawFieldErrors {
        errors: ReadSignal::new(raw_field_errors),
    });

    use_effect(move || {
        let validators = validators.clone();
        let async_validators = async_validators.clone();
        field_state.validators().with_mut(|e| {
            for validator in validators {
                if let Err(idx) = e.binary_search(&validator) {
                    e.insert(idx, validator)
                }
            }
        });
        field_state.async_validators().with_mut(|e| {
            for validator in async_validators {
                if let Err(idx) = e.binary_search(&validator) {
                    e.insert(idx, validator)
                }
            }
        });
        field_state.validate_on().set(validate_on);
    });

    use_context_provider(move || raw_field_errors());

    rsx! {
        {component(field_api)}
    }
}

async fn async_validate<TFieldValue: FieldValue, TFieldError: FieldError>(
    mut field_state: Store<FieldState<TFieldValue, TFieldError>>,
    should_debounce: bool,
) {
    if should_debounce {
        tokio::time::sleep(Duration::from_millis(350)).await;
    }
    field_state.async_validate().await;
}