Skip to main content

repose_ui/
subcompose.rs

1//! SubcomposeLayout and BoxWithConstraints.
2//!
3//! These layouts compose their children during the *reconcile* pass using the
4//! current available size, so the inner content can adapt to the parent's
5//! constraints.
6
7use std::hash::{DefaultHasher, Hash, Hasher};
8use std::sync::Arc;
9
10use repose_core::{BoxWithConstraintsScope, Modifier, SubcomposeScope, View, ViewKind};
11
12/// Hash any `Hash` value into a `u64` suitable for use as a
13/// [`Modifier::key`](repose_core::Modifier::key).
14///
15/// This is what the `*_with_key` helpers use internally. It is exposed for
16/// callers who want to set the key on a `Modifier` directly.
17pub fn subcompose_hash_key<K: Hash>(key: &K) -> u64 {
18    let mut h = DefaultHasher::new();
19    key.hash(&mut h);
20    h.finish()
21}
22
23/// A layout whose `content` closure is invoked with the current available
24/// size (in dp) and returns one or more `(slot_id, view)` pairs.
25///
26/// The single-slot form takes a closure that returns a single `View`; that
27/// view is implicitly assigned slot id `0`. The multi-slot form takes a
28/// closure returning a `Vec<(u64, View)>` and is exposed by
29/// [`subcompose_layout_with_slots`] for callers that need multiple slots.
30///
31/// `content` runs during reconcile. The first frame the closure is called
32/// and its result is cached; subsequent frames reuse the cached result as
33/// long as the available scope (and the `SubcomposeLayout`'s modifier) are
34/// unchanged.
35///
36/// If `content` captures state (such as a `Signal`) whose changes should
37/// re-trigger the closure, use [`subcompose_with_key`] (or
38/// [`box_with_constraints_with_key`]) so the cache is invalidated when that
39/// state changes.
40pub fn SubcomposeLayout<F>(modifier: Modifier, content: F) -> View
41where
42    F: Fn(SubcomposeScope) -> View + 'static,
43{
44    let wrapped: Arc<dyn Fn(&SubcomposeScope) -> Vec<(u64, View)>> =
45        Arc::new(move |scope| vec![(0, content(*scope))]);
46    View {
47        id: 0,
48        kind: ViewKind::SubcomposeLayout { content: wrapped },
49        modifier,
50        children: Vec::new(),
51        scope_key: None,
52        semantics: None,
53    }
54}
55
56/// Multi-slot variant of [`SubcomposeLayout`]. The `content` closure receives
57/// the current scope and returns a list of `(slot_id, view)` pairs. Slot ids
58/// are stable across frames: removing or reordering slots preserves the
59/// underlying tree nodes.
60pub fn subcompose_layout_with_slots<F>(modifier: Modifier, content: F) -> View
61where
62    F: Fn(SubcomposeScope) -> Vec<(u64, View)> + 'static,
63{
64    let wrapped: Arc<dyn Fn(&SubcomposeScope) -> Vec<(u64, View)>> =
65        Arc::new(move |scope| content(*scope));
66    View {
67        id: 0,
68        kind: ViewKind::SubcomposeLayout { content: wrapped },
69        modifier,
70        children: Vec::new(),
71        scope_key: None,
72        semantics: None,
73    }
74}
75
76/// A [`SubcomposeLayout`] specialized for the "show different content based on
77/// the available width/height" use case.
78///
79/// The supplied `content` receives a [`BoxWithConstraintsScope`] containing the
80/// current constraints (in dp) and returns the `View` to render. The resulting
81/// view fills the available space.
82pub fn BoxWithConstraints<F>(modifier: Modifier, content: F) -> View
83where
84    F: Fn(BoxWithConstraintsScope) -> View + 'static,
85{
86    SubcomposeLayout(modifier, move |scope| {
87        content(BoxWithConstraintsScope {
88            min_width: scope.min_width,
89            max_width: scope.max_width,
90            min_height: scope.min_height,
91            max_height: scope.max_height,
92        })
93    })
94}
95
96/// Build a [`SubcomposeLayout`] that re-invokes its `content` closure whenever
97/// the hashed value of `key` changes.
98///
99/// Use this when the closure captures state that should re-trigger
100/// subcomposition. Typical pattern: read the signal *outside* the closure and
101/// pass the value here so the cache key changes when the signal changes.
102///
103/// ```ignore
104/// let count = signal.get();
105/// subcompose_with_key(count, modifier, move |scope| {
106///     let count = signal.get();  // inner read observes the same value
107///     Text(format!("count = {count}"))
108/// });
109/// ```
110pub fn subcompose_with_key<K, F>(key: K, modifier: Modifier, content: F) -> View
111where
112    K: Hash,
113    F: Fn(SubcomposeScope) -> View + 'static,
114{
115    let hashed = subcompose_hash_key(&key);
116    SubcomposeLayout(modifier.key(hashed), content)
117}
118
119/// Keyed variant of [`BoxWithConstraints`]. Re-invokes `content` whenever the
120/// hashed value of `key` changes.
121pub fn box_with_constraints_with_key<K, F>(key: K, modifier: Modifier, content: F) -> View
122where
123    K: Hash,
124    F: Fn(BoxWithConstraintsScope) -> View + 'static,
125{
126    subcompose_with_key(key, modifier, move |scope| {
127        content(BoxWithConstraintsScope {
128            min_width: scope.min_width,
129            max_width: scope.max_width,
130            min_height: scope.min_height,
131            max_height: scope.max_height,
132        })
133    })
134}
135
136/// Multi-slot keyed variant of [`subcompose_layout_with_slots`]. The `key`'s
137/// hashed value is attached to the resulting `SubcomposeLayout` so the cache
138/// is invalidated whenever the key changes.
139pub fn subcompose_with_key_slots<K, F>(key: K, modifier: Modifier, content: F) -> View
140where
141    K: Hash,
142    F: Fn(SubcomposeScope) -> Vec<(u64, View)> + 'static,
143{
144    let hashed = subcompose_hash_key(&key);
145    subcompose_layout_with_slots(modifier.key(hashed), content)
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151    use crate::layout::LayoutEngine;
152    use crate::{Column, Interactions, ViewExt};
153    use std::collections::HashMap;
154    use std::sync::Arc;
155    use std::sync::atomic::{AtomicUsize, Ordering};
156
157    fn text_view(text: &str) -> View {
158        use repose_core::{
159            Color, FontStyle, FontWeight, TextAlign, TextDecoration, TextOverflow, ViewKind,
160        };
161        View {
162            id: 0,
163            kind: ViewKind::Text {
164                text: text.to_string(),
165                color: Color::WHITE,
166                font_size: 14.0,
167                soft_wrap: true,
168                max_lines: None,
169                overflow: TextOverflow::Visible,
170                font_family: None,
171                annotations: None,
172                text_align: TextAlign::Unspecified,
173                font_weight: FontWeight::NORMAL,
174                font_style: FontStyle::Normal,
175                text_decoration: TextDecoration::default(),
176                letter_spacing: 0.0,
177                line_height: 0.0,
178            },
179            modifier: Modifier::default(),
180            children: vec![],
181            scope_key: None,
182            semantics: None,
183        }
184    }
185
186    fn make_root(view: View) -> View {
187        Column(Modifier::new()).child(view)
188    }
189
190    #[test]
191    fn subcompose_hash_key_is_deterministic_and_distinguishes_values() {
192        assert_eq!(subcompose_hash_key(&"hello"), subcompose_hash_key(&"hello"));
193        assert_ne!(subcompose_hash_key(&"hello"), subcompose_hash_key(&"world"));
194        assert_eq!(
195            subcompose_hash_key(&(1u32, 2u32)),
196            subcompose_hash_key(&(1u32, 2u32))
197        );
198        assert_ne!(
199            subcompose_hash_key(&(1u32, 2u32)),
200            subcompose_hash_key(&(1u32, 3u32))
201        );
202    }
203
204    #[test]
205    fn subcompose_with_key_runs_closure_once_until_key_changes() {
206        let calls = Arc::new(AtomicUsize::new(0));
207        let calls_c = calls.clone();
208
209        // Both roots share the same Arc<AtomicUsize> so the second closure's
210        // increments are visible to the assertion below.
211        let sub = subcompose_with_key(1u64, Modifier::new(), move |_scope| {
212            calls_c.fetch_add(1, Ordering::SeqCst);
213            text_view("k=1")
214        });
215        let root_v1 = make_root(sub);
216
217        let calls2 = calls.clone();
218        let sub = subcompose_with_key(2u64, Modifier::new(), move |_scope| {
219            calls2.fetch_add(1, Ordering::SeqCst);
220            text_view("k=2")
221        });
222        let root_v2 = make_root(sub);
223
224        let mut engine = LayoutEngine::new();
225
226        // Frame with key=1: closure runs once.
227        let _ = engine.layout_frame(
228            &root_v1,
229            (400, 400),
230            &HashMap::new(),
231            &Interactions::default(),
232            None,
233        );
234        assert_eq!(calls.load(Ordering::SeqCst), 1);
235
236        // Repeat the same key=1 frame: closure stays cached.
237        let _ = engine.layout_frame(
238            &root_v1,
239            (400, 400),
240            &HashMap::new(),
241            &Interactions::default(),
242            None,
243        );
244        assert_eq!(calls.load(Ordering::SeqCst), 1);
245
246        // Now switch to key=2 (a different subcompose node) and verify the
247        // new closure runs.
248        let _ = engine.layout_frame(
249            &root_v2,
250            (400, 400),
251            &HashMap::new(),
252            &Interactions::default(),
253            None,
254        );
255        assert_eq!(calls.load(Ordering::SeqCst), 2);
256    }
257
258    #[test]
259    fn box_with_constraints_with_key_forwards_scope() {
260        use crate::Box as RBox;
261        let sub = box_with_constraints_with_key(42u64, Modifier::new(), |scope| {
262            assert!(scope.max_width > 0.0);
263            RBox(Modifier::new())
264        });
265        // Smoke check: builds a valid View with the SubcomposeLayout kind.
266        match sub.kind {
267            ViewKind::SubcomposeLayout { .. } => {}
268            _ => panic!("expected SubcomposeLayout"),
269        }
270    }
271
272    #[test]
273    fn subcompose_with_key_slots_runs_closure_once_until_key_changes() {
274        let calls = Arc::new(AtomicUsize::new(0));
275        let calls_c = calls.clone();
276
277        let sub = subcompose_with_key_slots(1u64, Modifier::new(), move |_scope| {
278            calls_c.fetch_add(1, Ordering::SeqCst);
279            vec![(0, text_view("k=1")), (1, text_view("k=1b"))]
280        });
281        let root_v1 = make_root(sub);
282
283        let calls2 = calls.clone();
284        let sub2 = subcompose_with_key_slots(2u64, Modifier::new(), move |_scope| {
285            calls2.fetch_add(1, Ordering::SeqCst);
286            vec![(0, text_view("k=2"))]
287        });
288        let root_v2 = make_root(sub2);
289
290        let mut engine = LayoutEngine::new();
291
292        let _ = engine.layout_frame(
293            &root_v1,
294            (400, 400),
295            &HashMap::new(),
296            &Interactions::default(),
297            None,
298        );
299        assert_eq!(calls.load(Ordering::SeqCst), 1);
300
301        // Same key: cache hit.
302        let _ = engine.layout_frame(
303            &root_v1,
304            (400, 400),
305            &HashMap::new(),
306            &Interactions::default(),
307            None,
308        );
309        assert_eq!(calls.load(Ordering::SeqCst), 1);
310
311        // New key: closure runs.
312        let _ = engine.layout_frame(
313            &root_v2,
314            (400, 400),
315            &HashMap::new(),
316            &Interactions::default(),
317            None,
318        );
319        assert_eq!(calls.load(Ordering::SeqCst), 2);
320    }
321}