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    #[must_use]
36    pub fn initial(&self) -> String {
37        match self {
38            TextSource::Static(s) => s.clone(),
39            TextSource::Dyn(f) => day_reactive::untrack(|| f()),
40        }
41    }
42    /// Resolve the current text, tracked: inside a reactive computation this subscribes to
43    /// whatever the source reads (a `Signal`, or the locale behind a localized string). The
44    /// nav host derive effects rely on this so native rows retitle on locale change.
45    pub(crate) fn resolve(&self) -> String {
46        match self {
47            TextSource::Static(s) => s.clone(),
48            TextSource::Dyn(f) => f(),
49        }
50    }
51    /// Install the text binding for a realized node (no-op for static text).
52    pub(crate) fn bind_to(
53        self,
54        node: RNode,
55        make_patch: impl Fn(String) -> Box<dyn std::any::Any> + 'static,
56        affects_size: bool,
57    ) {
58        if let TextSource::Dyn(f) = self {
59            let seed = day_reactive::untrack(|| f());
60            bind_seeded(
61                seed,
62                move || f(),
63                move |t: &String| {
64                    let patch = make_patch(t.clone());
65                    with_tree(|tr| tr.patch(node, patch, affects_size));
66                },
67            );
68        }
69    }
70}
71
72/// Disjoint-marker conversion (the coherent form of §12.2's IntoText):
73/// literals, `String`, `Signal<String>`, and closures all convert, each under its own marker.
74pub trait IntoText<M> {
75    fn into_text(self) -> TextSource;
76}
77
78pub struct StaticMark;
79pub struct SignalMark;
80pub struct FnMark;
81pub struct LocalizedMark;
82
83/// A localized message is text that follows the locale: `label(res::str::title())`. The
84/// conversion lives here, on the side that owns `IntoText`, so the localization layer (which a
85/// backend also uses for its own menu titles) does not depend on the widget builders.
86impl IntoText<LocalizedMark> for day_localization_ui::LocalizedText {
87    fn into_text(self) -> TextSource {
88        TextSource::Dyn(Rc::new(move || self.format()))
89    }
90}
91/// Marker for an already-converted [`TextSource`].
92pub struct SourceMark;
93
94impl IntoText<SourceMark> for TextSource {
95    fn into_text(self) -> TextSource {
96        self
97    }
98}
99
100/// A focus-binding target for [`Decorate::focused`](crate::decorators::Decorate::focused) (docs/focus.md): either a `Signal<bool>`
101/// (one control) or a `(Signal<Option<K>>, K)` pair (one control of a group sharing a signal).
102/// The two-marker split is the same E0119 dodge as [`IntoText`].
103pub trait IntoFocusBinding<M> {
104    /// Split into (desired-focus tracked read, native-change write-back).
105    #[allow(clippy::type_complexity)]
106    fn into_focus_binding(self) -> (Box<dyn Fn() -> bool>, Box<dyn Fn(bool)>);
107}
108
109pub struct FocusBoolMark;
110pub struct FocusGroupMark;
111
112impl IntoFocusBinding<FocusBoolMark> for Signal<bool> {
113    fn into_focus_binding(self) -> (Box<dyn Fn() -> bool>, Box<dyn Fn(bool)>) {
114        (Box::new(move || self.get()), Box::new(move |f| self.set(f)))
115    }
116}
117
118impl<K: Copy + PartialEq + 'static> IntoFocusBinding<FocusGroupMark> for (Signal<Option<K>>, K) {
119    fn into_focus_binding(self) -> (Box<dyn Fn() -> bool>, Box<dyn Fn(bool)>) {
120        let (sig, key) = self;
121        (
122            Box::new(move || sig.get() == Some(key)),
123            Box::new(move |f| {
124                if f {
125                    sig.set(Some(key));
126                } else if sig.get_untracked() == Some(key) {
127                    // Only clear if the signal still names this control. When focus moved to a
128                    // sibling, the paired gain (dispatched first, docs/focus.md) already wrote
129                    // the new value and the group signal never passes through `None`.
130                    sig.set(None);
131                }
132            }),
133        )
134    }
135}
136
137impl IntoText<StaticMark> for &str {
138    fn into_text(self) -> TextSource {
139        TextSource::Static(self.to_owned())
140    }
141}
142impl IntoText<StaticMark> for String {
143    fn into_text(self) -> TextSource {
144        TextSource::Static(self)
145    }
146}
147impl IntoText<SignalMark> for Signal<String> {
148    fn into_text(self) -> TextSource {
149        TextSource::Dyn(Rc::new(move || self.get()))
150    }
151}
152impl<F, S> IntoText<FnMark> for F
153where
154    F: Fn() -> S + 'static,
155    S: Into<String>,
156{
157    fn into_text(self) -> TextSource {
158        TextSource::Dyn(Rc::new(move || self().into()))
159    }
160}
161
162// ---------------------------------------------------------------------------
163// Fraction sources: the read-only numeric analogue of TextSource, for `progress`.
164// ---------------------------------------------------------------------------
165
166pub enum FractionSource {
167    Static(f64),
168    Dyn(Rc<dyn Fn() -> f64>),
169}
170
171impl FractionSource {
172    /// Untracked seed value, clamped to `0.0..=1.0`.
173    #[must_use]
174    pub fn initial(&self) -> f64 {
175        let v = match self {
176            FractionSource::Static(v) => *v,
177            FractionSource::Dyn(f) => day_reactive::untrack(|| f()),
178        };
179        v.clamp(0.0, 1.0)
180    }
181    /// Install the fraction binding (no-op for static values). Writes are clamped so a
182    /// backend never sees an out-of-range fraction.
183    pub(crate) fn bind_to(self, node: RNode) {
184        if let FractionSource::Dyn(f) = self {
185            let seed = day_reactive::untrack(|| f()).clamp(0.0, 1.0);
186            bind_seeded(
187                seed,
188                move || f().clamp(0.0, 1.0),
189                move |v: &f64| {
190                    with_tree(|tr| tr.patch(node, Box::new(ProgressPatch::Value(Some(*v))), false));
191                },
192            );
193        }
194    }
195}
196
197/// Disjoint-marker conversion (like [`IntoText`]) so `progress(_)` accepts a constant `f64`,
198/// a `Signal<f64>`, or a closure. Reuses the same marker types.
199pub trait IntoFraction<M> {
200    fn into_fraction(self) -> FractionSource;
201}
202
203impl IntoFraction<StaticMark> for f64 {
204    fn into_fraction(self) -> FractionSource {
205        FractionSource::Static(self)
206    }
207}
208impl IntoFraction<SignalMark> for Signal<f64> {
209    fn into_fraction(self) -> FractionSource {
210        FractionSource::Dyn(Rc::new(move || self.get()))
211    }
212}
213impl<F> IntoFraction<FnMark> for F
214where
215    F: Fn() -> f64 + 'static,
216{
217    fn into_fraction(self) -> FractionSource {
218        FractionSource::Dyn(Rc::new(self))
219    }
220}
221
222// ---------------------------------------------------------------------------
223// Two-way binding surface (§5.3)
224// ---------------------------------------------------------------------------
225
226// The trait moved down to day-reactive and took its shipped name (`Binding`, read/write/peek)
227// in the same pass (2026-08-22), so day-model can implement it for `Field` with every dependency
228// pointing downward; re-exported here so piece code needs no extra import.
229pub use day_reactive::Binding;