Skip to main content

adam_web_ui/binding/
widgets.rs

1//! Adapts model-independent controls to exact, instance-owned cell bindings.
2//!
3//! Use [`EditNumber`], [`EditText`], [`CheckBox`] and [`EditSlider`] inside
4//! [`crate::components::Theme`]. Controls report errors; only the host restores.
5use super::*;
6use crate::{
7    components::{Checkbox, Input, Label, NumericEditor, NumericSlider},
8    input::InputError,
9};
10use ::dioxus::prelude::*;
11use dioxus_primitives::checkbox::CheckboxState;
12use std::rc::Rc;
13
14/// Selects an editor capability without consulting a cell's source direction.
15#[derive(Clone, Copy, PartialEq)]
16enum Editor {
17    Number,
18    Text,
19    Bool,
20}
21
22/// Checks scalar capability and editor type, including read-only output displays.
23fn check(view: &CellView, editor: Editor) -> Result<(), BindingError> {
24    if !view.codec_supported {
25        return Err(BindingError::UnsupportedCodec(view.key.clone()));
26    }
27    let compatible = match editor {
28        Editor::Number => view.number_kind.is_some(),
29        Editor::Bool => view.is_bool,
30        Editor::Text => !view.is_bool && view.number_kind.is_none(),
31    };
32    if compatible {
33        Ok(())
34    } else {
35        Err(BindingError::IncompatibleEditor(view.key.clone()))
36    }
37}
38
39/// Renders and reports one explicit binding/configuration error per mounted error.
40#[component]
41fn ConfigurationError(bind: CellBinding, error: BindingError) -> Element {
42    let message = error.to_string();
43    use_effect(move || bind.report(HostRejection::Binding(error.clone())));
44    rsx! { div { role: "alert", class: "adam-binding-error", "{message}" } }
45}
46
47/// Renders the checked failure without silently hiding an incorrectly configured control.
48fn failure(bind: CellBinding, error: BindingError) -> Element {
49    rsx! { ConfigurationError { key: "{bind.identity()}:{error}", bind, error } }
50}
51
52/// Returns a distinct stable ID for this mounted control, even for the same binding.
53fn use_control_id(bind: &CellBinding) -> String {
54    let allocation = use_hook(|| Rc::new(()));
55    format!(
56        "adam-cell-{}-{:p}",
57        bind.identity(),
58        Rc::as_ptr(&allocation)
59    )
60}
61
62/// Binds an exact localized numeric editor to a named numeric cell.
63///
64/// Drafts and native composition remain owned by [`NumericEditor`]. Only
65/// complete user aspirations submit; synchronization and blur never write.
66///
67/// - Complexity: Publication lookup plus numeric control transition costs.
68///
69/// # Examples
70/// See [`use_sheet`] for `EditNumber { bind: sheet.cell("x") }`.
71#[component]
72pub fn EditNumber(
73    bind: CellBinding,
74    #[props(default)] label: String,
75    #[props(default)] class: String,
76    #[props(default)] style: String,
77    #[props(default)] locale: Option<String>,
78    #[props(default = "1".into())] step: String,
79) -> Element {
80    numeric(bind, label, class, style, locale, step, false)
81}
82
83/// Binds slider and exact numeric entry without clamping aspirations in the widget.
84///
85/// Range changes display the model value, not a locally clamped value. A
86/// read-only cell renders as a read-only number field without a slider.
87///
88/// - Complexity: Publication lookup plus numeric/slider transition costs.
89///
90/// # Examples
91/// Inside a scope initialized by [`use_sheet`],
92/// `rsx! { EditSlider { bind: sheet.cell("bounded") } }` uses its live range.
93#[component]
94pub fn EditSlider(
95    bind: CellBinding,
96    #[props(default)] label: String,
97    #[props(default)] class: String,
98    #[props(default)] style: String,
99    #[props(default)] locale: Option<String>,
100    #[props(default = "1".into())] step: String,
101) -> Element {
102    numeric(bind, label, class, style, locale, step, true)
103}
104
105/// Selects one checked numeric implementation and keys it by model installation.
106///
107/// - Complexity: O(named cells + label/style bytes) plus child rendering.
108fn numeric(
109    bind: CellBinding,
110    label: String,
111    class: String,
112    style: String,
113    locale: Option<String>,
114    step: String,
115    slider: bool,
116) -> Element {
117    let label = bind.label(label);
118    let view = match bind
119        .view()
120        .and_then(|view| check(&view, Editor::Number).map(|_| view))
121    {
122        Ok(view) => view,
123        Err(error) => return failure(bind, error),
124    };
125    // Dioxus reconciles keys in dynamic fragments, not a lone static child.
126    rsx! { for (bind, label, class, style, locale, step) in
127        std::iter::once((bind, label, class, style, locale, step)) {
128        NumericBinding { key: "{bind.identity()}", bind, label, class, style, locale, step,
129            slider, kind: view.number_kind.expect("checked numeric capability") }
130    } }
131}
132
133/// Owns reactive controlled projections for exactly one numeric installation.
134#[component]
135fn NumericBinding(
136    bind: CellBinding,
137    label: String,
138    class: String,
139    style: String,
140    locale: Option<String>,
141    step: String,
142    slider: bool,
143    kind: crate::input::NumberKind,
144) -> Element {
145    let id = use_control_id(&bind);
146    let label = bind.label(label);
147    let tracked = bind.clone();
148    let view = use_memo(move || tracked.view());
149    let value = use_memo(move || view.read().as_ref().ok().map(|view| view.text.clone()));
150    let range = use_memo(move || {
151        view.read()
152            .as_ref()
153            .ok()
154            .and_then(|view| view.range.clone())
155    });
156    let disabled = use_memo(move || {
157        view.read()
158            .as_ref()
159            .map_or(true, |view| view.flags.disabled && !view.flags.readonly)
160    });
161    let readonly = use_memo(move || view.read().as_ref().is_ok_and(|view| view.flags.readonly));
162    let invalid = use_memo(move || view.read().as_ref().map_or(true, |view| view.flags.invalid));
163    let errors = bind.clone();
164    let on_value = EventHandler::new(move |value: Option<String>| {
165        if let Some(value) = value {
166            bind.submit(value);
167        }
168    });
169    let on_error =
170        EventHandler::new(move |error: InputError| errors.report(HostRejection::Input(error)));
171    rsx! { div { class, style,
172        if slider && !readonly() {
173            NumericSlider { id, label, value, range, kind, step, disabled, readonly, invalid,
174                locale, optional: false, on_value, on_error }
175        } else {
176            NumericEditor { id, label, value, range, kind, step, disabled, readonly, invalid,
177                locale, optional: false, on_value, on_error }
178        }
179    } }
180}
181
182/// Binds exact scalar text without numeric coercion or synchronization writes.
183///
184/// Conversion and type failures render/report explicitly. Programmatic updates
185/// replace displayed text without submitting another transaction.
186///
187/// - Complexity: O(named cells + text/label/style bytes) per render or edit.
188///
189/// # Examples
190/// Inside a scope initialized by [`use_sheet`],
191/// `rsx! { EditText { bind: sheet.cell("title"), label: "Title" } }`.
192#[component]
193pub fn EditText(
194    bind: CellBinding,
195    #[props(default)] label: String,
196    #[props(default)] class: String,
197    #[props(default)] style: String,
198) -> Element {
199    let id = use_control_id(&bind);
200    let label = bind.label(label);
201    let view = match bind
202        .view()
203        .and_then(|view| check(&view, Editor::Text).map(|_| view))
204    {
205        Ok(view) => view,
206        Err(error) => return failure(bind, error),
207    };
208    rsx! { div { class, style,
209        Label { html_for: id.clone(), "{label}" }
210        for bind in std::iter::once(bind) {
211            Input { key: "{bind.identity()}", id: id.clone(), value: view.text.clone(),
212                disabled: view.flags.disabled && !view.flags.readonly,
213                readonly: view.flags.readonly, "aria-invalid": view.flags.invalid.to_string(),
214                oninput: move |event: FormEvent| bind.submit(event.value()),
215            }
216        }
217    } }
218}
219
220/// Binds a controlled Boolean without guessing its value from a click or stale display.
221///
222/// Rejected edits retire their model installation; explicit host restoration
223/// remounts controls so native and primitive checked state return to acceptance.
224///
225/// - Complexity: O(named cells + label/style bytes) per render or edit.
226///
227/// # Examples
228/// Inside a scope initialized by [`use_sheet`],
229/// `rsx! { CheckBox { bind: sheet.cell("enabled"), label: "Enabled" } }`.
230#[component]
231pub fn CheckBox(
232    bind: CellBinding,
233    #[props(default)] label: String,
234    #[props(default)] class: String,
235    #[props(default)] style: String,
236) -> Element {
237    let id = use_control_id(&bind);
238    let label = bind.label(label);
239    let view = match bind
240        .view()
241        .and_then(|view| check(&view, Editor::Bool).map(|_| view))
242    {
243        Ok(view) => view,
244        Err(error) => return failure(bind, error),
245    };
246    let checked = if view.text == "true" {
247        CheckboxState::Checked
248    } else {
249        CheckboxState::Unchecked
250    };
251    rsx! { div { class, style,
252        for bind in std::iter::once(bind) {
253            Checkbox { key: "{bind.identity()}", id: id.clone(), checked,
254                aria_label: label.clone(), "aria-invalid": view.flags.invalid.to_string(),
255                disabled: view.flags.disabled || view.flags.readonly,
256                on_checked_change: move |state: CheckboxState| bind.submit((state == CheckboxState::Checked).to_string()),
257            }
258        }
259        Label { html_for: id, "{label}" }
260    } }
261}