formars-ui 0.1.0

Leptos 0.8 companion crate for formars-signals: use_form hook, <Form> submit wrapper, <TextField>.
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
//! `<Form>` submit wrapper and outcome mapping.

use formars_signals::{FormController, FormSnapshot, FormaError, SubmitError};
use leptos::callback::Callback;
use leptos::prelude::*;
use leptos::task::spawn_local;
use reactive_graph::traits::Update;
use std::future::Future;

/// Mirrors [`SubmitError`] arms plus success, delivered to the caller's
/// `on_outcome` callback.
#[derive(Clone, Debug)]
pub enum SubmitOutcome<T, E> {
    /// The handler resolved `Ok(t)`.
    Success(T),
    /// The handler ran and failed with its own error. The caller MAY map
    /// payloads back with [`FormController::apply_server_errors`].
    HandlerError(E),
    /// Whole-form sync validation rejected the form BEFORE the handler was
    /// constructed. Per-field `visible_errors` already reflect violations;
    /// `<Form>` performs no additional error injection.
    ValidationFailed(FormaError),
}

/// Routes a composed submit result into the caller-facing outcome enum.
/// Pure: no reactivity, no allocation beyond the payload move.
pub(crate) fn map_outcome<T, E>(result: Result<T, SubmitError<E>>) -> SubmitOutcome<T, E> {
    match result {
        Ok(t) => SubmitOutcome::Success(t),
        Err(SubmitError::Validation(e)) => SubmitOutcome::ValidationFailed(e),
        Err(SubmitError::Handler(e)) => SubmitOutcome::HandlerError(e),
    }
}

/// Total guard-acquisition attempts: 1 initial + 7 retries under transient
/// `RwLock` contention (`None` misreports).
pub(crate) const BEGIN_ATTEMPT_MAX_TRIES: usize = 8;

/// Begins one submit attempt: the in-flight guard (defensive double-submit
/// shield complementing the reactively disabled button) followed by the
/// synchronous `submitted` flip that activates visibility gates BEFORE any
/// async work (FU-FM-2). Returns `false` when an attempt is already running.
///
/// Acquisition is an atomic CAS over `is_submitting`, retried up to
/// [`BEGIN_ATTEMPT_MAX_TRIES`] under transient `RwLock` contention (`None`
/// results): the signal's internal write lock is held across read+write, so
/// among arbitrarily many concurrent callers (the controller is `Sync`)
/// EXACTLY ONE observes `false` and flips it; every loser observes `true`,
/// returns `false` IMMEDIATELY — definitive losses never spend retry budget —
/// with no flag write and no notified reactive write. The `submitted` flip
/// happens only for the unique winner, AFTER acquisition.
///
/// `is_submitting` flips true SYNCHRONOUSLY here — not on the composed
/// future's first poll — so two same-tick submit events cannot both pass the
/// guard. The controller's drop guard (engaged when the future first polls)
/// resets the flag exactly once, on every exit path including cancellation.
///
/// # First-poll engagement and scheduler pairing
///
/// Because the [`SubmittingGuard`] engages only at the composed future's
/// FIRST poll (not at composition time), a scheduler that composes the future
/// but drops it BEFORE the first poll leaves `is_submitting` stuck `true` —
/// the reset never runs. `spawn_local` is the documented safe pairing: it
/// always polls the futures it accepts, so the guard engages immediately on
/// every spawned attempt.
pub(crate) fn begin_attempt(controller: &FormController) -> bool {
    let mut acquired = None;
    for _ in 0..BEGIN_ATTEMPT_MAX_TRIES {
        match controller.is_submitting().try_maybe_update(|in_flight| {
            if *in_flight {
                (false, false)
            } else {
                *in_flight = true;
                (true, true)
            }
        }) {
            Some(result) => {
                acquired = Some(result);
                break;
            }
            None => std::thread::yield_now(),
        }
    }
    // None = RwLock `WouldBlock` contention misreport for Arc-backed storage
    // (never disposal); retried up to the bounded BEGIN_ATTEMPT_MAX_TRIES
    // budget before degrading to not-acquired, so exhaustion still surfaces
    // as "attempt rejected".
    if acquired.unwrap_or(false) {
        controller.submitted().set(true);
        true
    } else {
        false
    }
}

/// Drives one attempt's composed future to its caller-facing outcome:
/// sync validation gate (handler never built on failure), snapshot,
/// `is_submitting` bracketing across all paths, then [`map_outcome`].
pub(crate) async fn finish_attempt<T, E, F, Fut>(
    controller: &FormController,
    handler: F,
) -> SubmitOutcome<T, E>
where
    T: 'static,
    E: 'static,
    F: FnOnce(FormSnapshot) -> Fut,
    Fut: Future<Output = Result<T, E>>,
{
    let result = controller.on_submit(handler).await;
    map_outcome(result)
}

/// Encapsulates async form submission over a [`FormController`].
///
/// Per attempt: `prevent_default()` first, then the in-flight guard, the
/// synchronous `submitted` flip, and the deliberately non-`Send` composed
/// future driven via `spawn_local` (client-local task; NEVER tokio::spawn).
///
/// # SSR exclusion (v0)
///
/// Markup may render server-side, but submit execution is client-path only:
/// `spawn_local` requires a local-task executor unavailable on server
/// threads, and the composed future is intentionally not `Send`, so it can
/// never be tokio-spawned.
#[component]
// reason: typed-builder consumes props by value; component fns are never called directly
#[allow(
    clippy::needless_pass_by_value,
    reason = "leptos typed-builder prop convention"
)]
pub fn Form<T, E, F, Fut>(
    controller: FormController,
    #[prop(into)] on_outcome: Callback<SubmitOutcome<T, E>>,
    on_submit: F,
    #[prop(optional)] submit_label: Option<String>,
    children: Children,
) -> impl IntoView
where
    T: 'static,
    E: 'static,
    F: Fn(FormSnapshot) -> Fut + Clone + 'static,
    Fut: Future<Output = Result<T, E>> + 'static,
{
    let ctrl_for_button = controller.clone();
    view! {
        <form on:submit=move |ev| {
            ev.prevent_default();
            if !begin_attempt(&controller) {
                return;
            }
            // each attempt passes a fresh clone of the persistent `Fn`
            // into a fresh composed future
                let handler = on_submit.clone();
                let outcome_cb = on_outcome;
                let ctrl = controller.clone();
            spawn_local(async move {
                let outcome = finish_attempt(&ctrl, handler).await;
                outcome_cb.run(outcome);
            });
        }>
            {children()}
            {move || {
                submit_label.clone().map(|label| {
                    let is_submitting = ctrl_for_button.is_submitting();
                    view! {
                        <button type="submit" disabled=move || is_submitting.get()>
                            {label}
                        </button>
                    }
                })
            }}
        </form>
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use formars_signals::{FieldPath, IssueCode};
    use std::borrow::Cow;

    /// Budget contract (spec Domain 1): 8 = 1 initial attempt + 7 retries,
    /// spent ONLY on transient `None` (`RwLock` contention misreports).
    #[test]
    fn begin_attempt_budget_is_exactly_eight_total_attempts() {
        assert_eq!(
            BEGIN_ATTEMPT_MAX_TRIES, 8,
            "8 = 1 initial attempt + 7 retries under transient contention"
        );
    }

    fn sample_error() -> FormaError {
        FormaError {
            issues: vec![formars_signals::FormaIssue {
                path: FieldPath::key("email"),
                code: IssueCode::Min,
                message: Cow::Borrowed("too short"),
                params: Vec::new(),
            }],
        }
    }

    #[test]
    fn ok_maps_to_success_preserving_payload() {
        let mapped: SubmitOutcome<u32, String> = map_outcome(Ok(7u32));
        assert!(
            matches!(mapped, SubmitOutcome::Success(7)),
            "Ok must map to Success carrying the payload"
        );
    }

    #[test]
    fn validation_error_maps_to_validation_failed_with_payload() {
        let mapped: SubmitOutcome<(), FormaError> =
            map_outcome(Err(SubmitError::Validation(sample_error())));
        match mapped {
            SubmitOutcome::ValidationFailed(e) => {
                assert_eq!(e.issues.len(), 1, "validation payload must be preserved");
                assert_eq!(e.issues[0].path, FieldPath::key("email"));
            }
            other => panic!("expected ValidationFailed, got {other:?}"),
        }
    }

    #[test]
    fn handler_error_maps_to_handler_error_preserving_e() {
        let mapped: SubmitOutcome<(), FormaError> =
            map_outcome(Err(SubmitError::Handler(sample_error())));
        match mapped {
            SubmitOutcome::HandlerError(e) => {
                assert_eq!(e.issues.len(), 1, "handler error payload E preserved");
            }
            other => panic!("expected HandlerError, got {other:?}"),
        }
    }
}

/// FU-FM-2/3/5 glue-level tests over the composed future, driven by
/// `block_on` — mirroring exactly what `<Form>`'s submit handler does
/// (native-only; `spawn_local` itself is exercised on the wasm target).
#[cfg(test)]
mod glue {
    use super::*;
    use formars_core::prelude::*;
    use formars_signals::ValidateOn;
    use futures::executor::block_on;
    use reactive_graph::traits::Get;
    use std::cell::RefCell;
    use std::rc::Rc;

    fn controller_with_invalid_email() -> FormController {
        let mut c = FormController::new(ValidateOn::Submit);
        c.register(FieldPath::key("email"), Box::new(string().min(8).email()))
            .unwrap();
        c.field(&FieldPath::key("email")).unwrap().set_str("ab");
        c
    }

    fn controller_with_valid_email() -> FormController {
        let mut c = FormController::new(ValidateOn::Submit);
        c.register(FieldPath::key("email"), Box::new(string().min(8).email()))
            .unwrap();
        c.field(&FieldPath::key("email"))
            .unwrap()
            .set_str("user@example.com");
        c
    }

    /// The exact two-step sequence `<Form>` performs per attempt (extracted
    /// so native tests drive the real code path).
    fn form_attempt<T, E, F, Fut>(
        controller: &FormController,
        handler: F,
    ) -> impl Future<Output = SubmitOutcome<T, E>>
    where
        T: 'static,
        E: 'static,
        F: FnOnce(FormSnapshot) -> Fut,
        Fut: Future<Output = Result<T, E>>,
    {
        let proceed = begin_attempt(controller);
        let ctrl = controller.clone();
        async move {
            if proceed {
                finish_attempt(&ctrl, handler).await
            } else {
                unreachable!("fresh controllers are never mid-submit")
            }
        }
    }

    #[test]
    fn fm2_submitted_flip_precedes_future() {
        let controller = controller_with_valid_email();
        let observed = Rc::new(RefCell::new(None));
        let obs = observed.clone();
        let view = controller.clone();
        block_on(form_attempt(&controller, move |_snap| {
            *obs.borrow_mut() = Some(view.submitted().get());
            async { Ok::<(), std::convert::Infallible>(()) }
        }));
        assert_eq!(
            *observed.borrow(),
            Some(true),
            "`submitted` must read true at the first handler await point"
        );
        assert!(controller.submitted().get());
    }

    #[test]
    fn fm3_non_send_handler_accepted() {
        let controller = controller_with_valid_email();
        // Rc-backed non-Send state captured by the handler future.
        let state = Rc::new(RefCell::new(String::from("local")));
        let captured = state.clone();
        let outcome = block_on(finish_attempt(&controller, move |_snap| {
            let captured = captured.clone();
            async move {
                captured.borrow_mut().push_str("-done");
                Ok::<String, std::convert::Infallible>(captured.borrow().clone())
            }
        }));
        match outcome {
            SubmitOutcome::Success(s) => assert_eq!(s, "local-done"),
            other => panic!("non-Send handler must complete, got {other:?}"),
        }
        assert_eq!(state.borrow().as_str(), "local-done");
    }

    #[test]
    fn fm5_invalid_blocks_handler() {
        let controller = controller_with_invalid_email();
        let invoked = Rc::new(RefCell::new(false));
        let flag = invoked.clone();
        let outcome = block_on(finish_attempt(&controller, move |_snap| {
            flag.replace(true); // proof-of-invocation marker
            async { Ok::<(), std::convert::Infallible>(()) }
        }));
        assert!(
            matches!(outcome, SubmitOutcome::ValidationFailed(_)),
            "validation failure must surface as ValidationFailed"
        );
        assert!(
            !*invoked.borrow(),
            "handler must never be constructed when validation fails"
        );
    }

    #[test]
    fn fm5_valid_brackets_is_submitting_on_success_and_error() {
        for expect_ok in [true, false] {
            let controller = controller_with_valid_email();
            let during = Rc::new(RefCell::new(None));
            let d = during.clone();
            let c2 = controller.clone();
            let outcome = block_on(finish_attempt(&controller, move |_snap| {
                let d = d.clone();
                let c3 = c2.clone();
                async move {
                    d.replace(Some(c3.is_submitting().get()));
                    if expect_ok {
                        Ok::<(), String>(())
                    } else {
                        Err(String::from("boom"))
                    }
                }
            }));
            assert_eq!(
                *during.borrow(),
                Some(true),
                "is_submitting true while handler pending"
            );
            assert!(
                !controller.is_submitting().get(),
                "bracket closes after settle"
            );
            if expect_ok {
                assert!(matches!(outcome, SubmitOutcome::Success(())));
            } else {
                assert!(
                    matches!(&outcome, SubmitOutcome::HandlerError(e) if e == "boom"),
                    "handler error path must also close the bracket"
                );
            }
        }
    }

    #[test]
    fn fm5_success_surfaced_once_through_callback() {
        let controller = controller_with_valid_email();
        let collected: std::sync::Arc<std::sync::Mutex<Vec<SubmitOutcome<(), String>>>> =
            std::sync::Arc::default();
        let sink = collected.clone();
        let on_outcome = Callback::new(move |o: SubmitOutcome<(), String>| {
            sink.lock().unwrap().push(o);
        });
        // Exactly what <Form>'s spawned task does:
        let outcome = block_on(finish_attempt(&controller, |_snap| async {
            Ok::<(), String>(())
        }));
        on_outcome.run(outcome);
        let got = collected.lock().unwrap();
        assert_eq!(got.len(), 1, "success delivered exactly once");
        assert!(matches!(got[0], SubmitOutcome::Success(())));
    }

    #[test]
    fn guard_rejects_second_synchronous_attempt() {
        // Two submit events in the same tick: the first flips `is_submitting`
        // synchronously inside begin_attempt (before any future is polled),
        // so the second must be rejected.
        let controller = controller_with_valid_email();
        assert!(begin_attempt(&controller), "first attempt proceeds");
        assert!(
            !begin_attempt(&controller),
            "second same-tick attempt must be rejected"
        );
        assert!(controller.is_submitting().get());
        // Driving the composed future still resets the flag exactly once.
        let outcome: SubmitOutcome<(), std::convert::Infallible> =
            block_on(finish_attempt(&controller, |_snap| async { Ok(()) }));
        assert!(matches!(outcome, SubmitOutcome::Success(())));
        assert!(
            !controller.is_submitting().get(),
            "drop guard closes the bracket after the attempt settles"
        );
    }

    #[test]
    fn guard_rejects_attempt_while_in_flight() {
        use reactive_graph::traits::Set;
        let controller = controller_with_valid_email();
        // Simulate mid-flight state set from elsewhere; begin_attempt must
        // observe it and reject the attempt.
        controller.is_submitting().set(true);
        assert!(
            !begin_attempt(&controller),
            "in-flight guard must reject attempts while submitting"
        );
    }

    /// Losing callers leave NO trace: a rejected attempt neither flips
    /// `submitted` nor disturbs the winner's in-flight acquisition.
    #[test]
    fn cas_loser_leaves_no_trace() {
        use reactive_graph::traits::Set;
        let controller = controller_with_valid_email();
        controller.is_submitting().set(true);
        assert!(!begin_attempt(&controller), "loser must be rejected");
        assert!(
            !controller.submitted().get(),
            "`submitted` byte-identical after the loser: still false"
        );
        assert!(
            controller.is_submitting().get(),
            "in-flight flag unchanged by the loser"
        );
    }

    /// Cross-thread CAS pin (spec Domain 3): T threads × R rounds, every
    /// round start synchronized on a barrier, ZERO sleeps. Exactly ONE
    /// caller may win `begin_attempt` per round; the unique winner settles
    /// via the real `finish_attempt` path so the flag restores through the
    /// actual drop-guard between rounds. Deterministic assertion under ANY
    /// interleaving: either the acquisition is atomic or the per-round
    /// counts expose the TOCTOU.
    ///
    /// Two barriers per round keep the accounting airtight: `started`
    /// releases the round together, and `attempted` guarantees every thread
    /// has contested THIS round before the winner settles — without it, a
    /// fast winner's drop-guard reset could leak into a lagging contender's
    /// same-round attempt (an artifact of the harness, not of the CAS).
    #[test]
    fn cas_exactly_one_winner_per_round_across_threads() {
        use std::sync::{Arc, Barrier, Mutex};

        const THREADS: usize = 8;
        const ROUNDS: usize = 16;

        let controller = Arc::new(controller_with_valid_email());
        let winners: Arc<Mutex<Vec<usize>>> = Arc::default();
        let started = Arc::new(Barrier::new(THREADS));
        let attempted = Arc::new(Barrier::new(THREADS));

        let workers: Vec<_> = (0..THREADS)
            .map(|_| {
                let controller = controller.clone();
                let winners = winners.clone();
                let started = started.clone();
                let attempted = attempted.clone();
                std::thread::spawn(move || {
                    for round in 0..ROUNDS {
                        started.wait();
                        // Losers perform NOTHING after receiving false.
                        if begin_attempt(&controller) {
                            winners.lock().unwrap().push(round);
                            // THE WINNER settles only after every contender
                            // has contested this round, through the real
                            // drop-guard path so the flag restores strictly
                            // between rounds.
                            attempted.wait();
                            let outcome: SubmitOutcome<(), std::convert::Infallible> =
                                block_on(finish_attempt(&controller, |_snap| async { Ok(()) }));
                            assert!(
                                matches!(outcome, SubmitOutcome::Success(())),
                                "winner's attempt must settle cleanly"
                            );
                        } else {
                            attempted.wait();
                        }
                    }
                })
            })
            .collect();
        for worker in workers {
            worker.join().expect("no worker panics");
        }

        let wins = winners.lock().unwrap().clone();
        let mut per_round = [0usize; ROUNDS];
        for round in &wins {
            per_round[*round] += 1;
        }
        assert!(
            per_round.iter().all(|&count| count == 1),
            "exactly ONE winner per round required; got {per_round:?} \
             (total {} over {ROUNDS} rounds)",
            wins.len()
        );
        assert_eq!(wins.len(), ROUNDS, "exactly R winners across R rounds");
        assert!(
            !controller.is_submitting().get(),
            "flag fully restored after join"
        );
    }
}