formars_ui/use_form.rs
1//! The `use_form` ownership/lifetime seam and context model (FU-HK-1/2/3).
2
3use formars_signals::{FormController, ValidateOn};
4use reactive_graph::owner::{expect_context, provide_context, use_context};
5
6/// Returned by [`use_form`]; the hook also provisions the controller as
7/// Leptos context so descendants can resolve it.
8///
9/// Register/mutate through `controller` — clones share the same underlying
10/// signals (`Arc`-backed), so there is exactly one source of truth per field.
11#[derive(Clone)]
12pub struct UseForm {
13 /// The constructed controller. `register*` take `&mut self`, so keep a
14 /// local `mut` binding; event-handler closures capture cheap clones.
15 pub controller: FormController,
16}
17
18/// Constructs a controller with `default_validate_on`, provides it as
19/// context (`provide_context(controller.clone())`), and returns it.
20///
21/// Call this in a component body (Leptos 0.8 bodies run once per mount, so
22/// the owned controller lives for the component lifetime).
23#[must_use]
24pub fn use_form(default_validate_on: ValidateOn) -> UseForm {
25 let controller = FormController::new(default_validate_on);
26 provide_context(controller.clone());
27 UseForm { controller }
28}
29
30/// Resolves the ancestor-provided form controller.
31///
32/// # Panics
33///
34/// Panics when no ancestor called [`use_form`] (deterministic documented
35/// behavior, FU-HK-2). Use [`try_form_controller`] for the graceful variant.
36#[must_use]
37#[track_caller]
38pub fn use_form_controller() -> FormController {
39 expect_context::<FormController>()
40}
41
42/// Graceful variant of [`use_form_controller`]: `None` when no ancestor
43/// called [`use_form`].
44#[must_use]
45pub fn try_form_controller() -> Option<FormController> {
46 use_context::<FormController>()
47}