Skip to main content

day_pieces/
sources.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Input adapters that let a constructor accept a plain value, a `Signal`, or a closure
5//! interchangeably: `IntoText`/`TextSource` (text), `IntoFraction`/`FractionSource` (0–1 numbers),
6//! `Binding` (two-way bindings), and `IntoFocusBinding` (focus state).
7
8use std::rc::Rc;
9
10use day_core::*;
11use day_reactive::{Signal, bind_seeded};
12use day_spec::props::*;
13
14// ---------------------------------------------------------------------------
15// Text sources (§12.2's IntoText, M1 subset; Fluent joins at M6)
16// ---------------------------------------------------------------------------
17
18pub enum TextSource {
19    Static(String),
20    Dyn(Rc<dyn Fn() -> String>),
21}
22
23// Clone so nav can keep a page title's source alongside its resolved snapshot: the live source
24// re-resolves on locale change and feeds `NavPatch::Title` (docs/navigation.md).
25impl Clone for TextSource {
26    fn clone(&self) -> Self {
27        match self {
28            TextSource::Static(s) => TextSource::Static(s.clone()),
29            TextSource::Dyn(f) => TextSource::Dyn(f.clone()),
30        }
31    }
32}
33
34impl TextSource {
35    pub fn initial(&self) -> String {
36        match self {
37            TextSource::Static(s) => s.clone(),
38            TextSource::Dyn(f) => day_reactive::untrack(|| f()),
39        }
40    }
41    /// Resolve the current text, tracked: inside a reactive computation this subscribes to
42    /// whatever the source reads (a `Signal`, or the locale behind a localized string). The
43    /// nav host derive effects rely on this so native rows retitle on locale change.
44    pub(crate) fn resolve(&self) -> String {
45        match self {
46            TextSource::Static(s) => s.clone(),
47            TextSource::Dyn(f) => f(),
48        }
49    }
50    /// Install the text binding for a realized node (no-op for static text).
51    pub(crate) fn bind_to(
52        self,
53        node: RNode,
54        make_patch: impl Fn(String) -> Box<dyn std::any::Any> + 'static,
55        affects_size: bool,
56    ) {
57        if let TextSource::Dyn(f) = self {
58            let seed = day_reactive::untrack(|| f());
59            bind_seeded(
60                seed,
61                move || f(),
62                move |t: &String| {
63                    let patch = make_patch(t.clone());
64                    with_tree(|tr| tr.patch(node, patch, affects_size));
65                },
66            );
67        }
68    }
69}
70
71/// Disjoint-marker conversion (the coherent form of §12.2's IntoText):
72/// literals, `String`, `Signal<String>`, and closures all convert, each under its own marker.
73pub trait IntoText<M> {
74    fn into_text(self) -> TextSource;
75}
76
77pub struct StaticMark;
78pub struct SignalMark;
79pub struct FnMark;
80/// Marker for an already-converted [`TextSource`].
81pub struct SourceMark;
82
83impl IntoText<SourceMark> for TextSource {
84    fn into_text(self) -> TextSource {
85        self
86    }
87}
88
89/// A focus-binding target for [`Decorate::focused`](crate::decorators::Decorate::focused) (docs/focus.md): either a `Signal<bool>`
90/// (one control) or a `(Signal<Option<K>>, K)` pair (one control of a group sharing a signal).
91/// The two-marker split is the same E0119 dodge as [`IntoText`].
92pub trait IntoFocusBinding<M> {
93    /// Split into (desired-focus tracked read, native-change write-back).
94    #[allow(clippy::type_complexity)]
95    fn into_focus_binding(self) -> (Box<dyn Fn() -> bool>, Box<dyn Fn(bool)>);
96}
97
98pub struct FocusBoolMark;
99pub struct FocusGroupMark;
100
101impl IntoFocusBinding<FocusBoolMark> for Signal<bool> {
102    fn into_focus_binding(self) -> (Box<dyn Fn() -> bool>, Box<dyn Fn(bool)>) {
103        (Box::new(move || self.get()), Box::new(move |f| self.set(f)))
104    }
105}
106
107impl<K: Copy + PartialEq + 'static> IntoFocusBinding<FocusGroupMark> for (Signal<Option<K>>, K) {
108    fn into_focus_binding(self) -> (Box<dyn Fn() -> bool>, Box<dyn Fn(bool)>) {
109        let (sig, key) = self;
110        (
111            Box::new(move || sig.get() == Some(key)),
112            Box::new(move |f| {
113                if f {
114                    sig.set(Some(key));
115                } else if sig.get_untracked() == Some(key) {
116                    // Only clear if the signal still names this control. When focus moved to a
117                    // sibling, the paired gain (dispatched first, docs/focus.md) already wrote
118                    // the new value and the group signal never passes through `None`.
119                    sig.set(None);
120                }
121            }),
122        )
123    }
124}
125
126impl IntoText<StaticMark> for &str {
127    fn into_text(self) -> TextSource {
128        TextSource::Static(self.to_owned())
129    }
130}
131impl IntoText<StaticMark> for String {
132    fn into_text(self) -> TextSource {
133        TextSource::Static(self)
134    }
135}
136impl IntoText<SignalMark> for Signal<String> {
137    fn into_text(self) -> TextSource {
138        TextSource::Dyn(Rc::new(move || self.get()))
139    }
140}
141impl<F, S> IntoText<FnMark> for F
142where
143    F: Fn() -> S + 'static,
144    S: Into<String>,
145{
146    fn into_text(self) -> TextSource {
147        TextSource::Dyn(Rc::new(move || self().into()))
148    }
149}
150
151// ---------------------------------------------------------------------------
152// Fraction sources: the read-only numeric analogue of TextSource, for `progress`.
153// ---------------------------------------------------------------------------
154
155pub enum FractionSource {
156    Static(f64),
157    Dyn(Rc<dyn Fn() -> f64>),
158}
159
160impl FractionSource {
161    /// Untracked seed value, clamped to `0.0..=1.0`.
162    pub fn initial(&self) -> f64 {
163        let v = match self {
164            FractionSource::Static(v) => *v,
165            FractionSource::Dyn(f) => day_reactive::untrack(|| f()),
166        };
167        v.clamp(0.0, 1.0)
168    }
169    /// Install the fraction binding (no-op for static values). Writes are clamped so a
170    /// backend never sees an out-of-range fraction.
171    pub(crate) fn bind_to(self, node: RNode) {
172        if let FractionSource::Dyn(f) = self {
173            let seed = day_reactive::untrack(|| f()).clamp(0.0, 1.0);
174            bind_seeded(
175                seed,
176                move || f().clamp(0.0, 1.0),
177                move |v: &f64| {
178                    with_tree(|tr| tr.patch(node, Box::new(ProgressPatch::Value(Some(*v))), false));
179                },
180            );
181        }
182    }
183}
184
185/// Disjoint-marker conversion (like [`IntoText`]) so `progress(_)` accepts a constant `f64`,
186/// a `Signal<f64>`, or a closure. Reuses the same marker types.
187pub trait IntoFraction<M> {
188    fn into_fraction(self) -> FractionSource;
189}
190
191impl IntoFraction<StaticMark> for f64 {
192    fn into_fraction(self) -> FractionSource {
193        FractionSource::Static(self)
194    }
195}
196impl IntoFraction<SignalMark> for Signal<f64> {
197    fn into_fraction(self) -> FractionSource {
198        FractionSource::Dyn(Rc::new(move || self.get()))
199    }
200}
201impl<F> IntoFraction<FnMark> for F
202where
203    F: Fn() -> f64 + 'static,
204{
205    fn into_fraction(self) -> FractionSource {
206        FractionSource::Dyn(Rc::new(self))
207    }
208}
209
210// ---------------------------------------------------------------------------
211// Two-way binding surface (§5.3)
212// ---------------------------------------------------------------------------
213
214// The trait moved down to day-reactive and took its shipped name (`Binding`, read/write/peek)
215// in the same pass (2026-08-22), so day-model can implement it for `Field` with every dependency
216// pointing downward; re-exported here so piece code needs no extra import.
217pub use day_reactive::Binding;