Skip to main content

formars_signals/
field.rs

1//! Per-field state cells, handles, and validation-timing modes.
2
3use std::sync::Arc;
4
5use reactive_graph::computed::ArcMemo;
6use reactive_graph::signal::ArcRwSignal;
7use reactive_graph::traits::{Get, Set};
8
9use formars_core::error::{FieldPath, FormaIssue};
10use formars_core::schema::DynSchema;
11use formars_core::value::Value;
12
13/// When a field's validation issues become visible to the consuming UI.
14///
15/// The controller default is set at construction; individual fields override
16/// it at registration.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum ValidateOn {
19    /// Errors track every edit; visibility follows the touched/submitted gate.
20    Change,
21    /// Errors become active once the field is marked touched (the blur seam).
22    Blur,
23    /// Error visibility activates only after a submit attempt.
24    Submit,
25}
26
27/// Accessor view over one registered field's reactive cells.
28#[derive(Clone)]
29pub struct FieldHandle {
30    pub(crate) path: FieldPath,
31    pub(crate) value: ArcRwSignal<Value>,
32    pub(crate) touched: ArcRwSignal<bool>,
33    pub(crate) dirty: ArcMemo<bool>,
34    pub(crate) errors: ArcMemo<Vec<FormaIssue>>,
35    pub(crate) visible_errors: ArcMemo<Vec<FormaIssue>>,
36    pub(crate) validate_on: ValidateOn,
37}
38
39impl FieldHandle {
40    /// The field's registration path.
41    #[must_use]
42    pub fn path(&self) -> &FieldPath {
43        &self.path
44    }
45
46    /// The field's value signal — the single source of truth for this field.
47    #[must_use]
48    pub fn value(&self) -> ArcRwSignal<Value> {
49        self.value.clone()
50    }
51
52    /// Whether the field has been marked touched (blur seam).
53    #[must_use]
54    pub fn touched(&self) -> ArcRwSignal<bool> {
55        self.touched.clone()
56    }
57
58    /// True when the current value differs from the register-time snapshot.
59    #[must_use]
60    pub fn dirty(&self) -> ArcMemo<bool> {
61        self.dirty.clone()
62    }
63
64    /// Schema-derived issues for the current value, stamped with this path.
65    #[must_use]
66    pub fn errors(&self) -> ArcMemo<Vec<FormaIssue>> {
67        self.errors.clone()
68    }
69
70    /// Display-gated issues: schema issues behind the mode-dependent gate plus
71    /// live server issues for an unedited value.
72    #[must_use]
73    pub fn visible_errors(&self) -> ArcMemo<Vec<FormaIssue>> {
74        self.visible_errors.clone()
75    }
76
77    /// The effective validation-timing mode for this field.
78    #[must_use]
79    pub fn validate_on(&self) -> ValidateOn {
80        self.validate_on
81    }
82
83    /// Current value as an owned `String`, only for the `Value::String`
84    /// variant.
85    #[must_use]
86    pub fn get_str(&self) -> Option<String> {
87        self.value.get().as_str().map(str::to_owned)
88    }
89
90    /// Canonical display rendering of the current value for `<input>`
91    /// surfaces: `String` → itself; `I64`/`F64` → shortest-roundtrip
92    /// `ToString`; `Bool` → `"true"`/`"false"`; `Null`/`Array`/`Object` →
93    /// `""`.
94    ///
95    /// Non-finite `F64` values render the Rust std spellings — `"NaN"`,
96    /// `"inf"`, `"-inf"` — and these spellings re-coerce via `f64::from_str`
97    /// inside `CoercedSchema::<f64>`, so the rendered state round-trips.
98    ///
99    /// This is THE single display seam consumed by formars-ui (SSR attribute
100    /// and pushback effect alike) — never add a second coercion site.
101    #[must_use]
102    pub fn display_str(&self) -> String {
103        match self.value.get() {
104            Value::String(s) => s.to_string(),
105            Value::I64(i) => i.to_string(),
106            Value::F64(f) => f.to_string(),
107            Value::Bool(b) => b.to_string(),
108            Value::Null | Value::Array(_) | Value::Object(_) => String::new(),
109        }
110    }
111
112    /// Sets `Value::String(s)` exactly — no coercion.
113    pub fn set_str(&self, s: &str) {
114        self.value.set(Value::from(s));
115    }
116
117    /// Sets `Value::I64(v)` exactly.
118    pub fn set_i64(&self, v: i64) {
119        self.value.set(Value::I64(v));
120    }
121
122    /// Sets `Value::F64(v)` exactly.
123    pub fn set_f64(&self, v: f64) {
124        self.value.set(Value::F64(v));
125    }
126
127    /// Sets `Value::Bool(b)` exactly.
128    pub fn set_bool(&self, b: bool) {
129        self.value.set(Value::Bool(b));
130    }
131}
132
133/// Controller-owned state for one registered field.
134pub(crate) struct FieldCell {
135    pub(crate) initial: Value,
136    pub(crate) value: ArcRwSignal<Value>,
137    pub(crate) touched: ArcRwSignal<bool>,
138    pub(crate) schema: Arc<dyn DynSchema>,
139    pub(crate) validate_on: ValidateOn,
140    pub(crate) server: ArcRwSignal<Vec<FormaIssue>>,
141    pub(crate) server_baseline: ArcRwSignal<Value>,
142    pub(crate) visible_errors: ArcMemo<Vec<FormaIssue>>,
143}