cranpose_ui/widgets/
layout.rs1#![allow(non_snake_case)]
4
5use std::{cell::RefCell, rc::Rc};
6
7use cranpose_core::{NodeId, SlotId};
8use cranpose_ui_graphics::Size;
9use cranpose_ui_layout::{MeasurePolicy, Placement};
10
11use super::{nodes::LayoutNode, scopes::BoxWithConstraintsScopeImpl};
12use crate::{
13 composable,
14 modifier::Modifier,
15 subcompose_layout::{
16 Constraints, MeasurePolicy as SubcomposeMeasurePolicy, MeasureResult, SubcomposeLayoutNode,
17 SubcomposeLayoutScope, SubcomposeMeasureScope, SubcomposeMeasureScopeImpl,
18 },
19};
20
21struct RetainedMeasurePolicy<P> {
22 value: P,
23 policy: Rc<dyn MeasurePolicy>,
24}
25
26#[composable]
27pub fn Layout<F, P>(modifier: Modifier, measure_policy: P, mut content: F) -> NodeId
28where
29 F: FnMut() + 'static,
30 P: MeasurePolicy + Clone + PartialEq + 'static,
31{
32 let policy_holder = cranpose_core::remember({
33 let measure_policy = measure_policy.clone();
34 move || {
35 Rc::new(RefCell::new(RetainedMeasurePolicy {
36 value: measure_policy.clone(),
37 policy: Rc::new(measure_policy),
38 }))
39 }
40 })
41 .with(|holder| holder.clone());
42 let policy = {
43 let mut holder = policy_holder.borrow_mut();
44 if holder.value != measure_policy {
45 holder.value = measure_policy.clone();
46 holder.policy = Rc::new(measure_policy);
47 }
48 Rc::clone(&holder.policy)
49 };
50 let modifier_for_reset = modifier.clone();
51 let policy_for_reset = Rc::clone(&policy);
52 let id = cranpose_core::with_current_composer(|composer| {
53 composer.emit_recyclable_node(
54 || LayoutNode::new(modifier.clone(), Rc::clone(&policy)),
55 move |node| {
56 *node = LayoutNode::new(modifier_for_reset.clone(), Rc::clone(&policy_for_reset));
57 },
58 )
59 });
60 let composed_density = crate::density::density();
61 if let Err(err) = cranpose_core::with_node_mut(id, |node: &mut LayoutNode| {
62 node.set_modifier(modifier.clone());
63 node.set_measure_policy(Rc::clone(&policy));
64 node.set_density(composed_density);
65 }) {
66 debug_assert!(false, "failed to update Layout node: {err}");
67 }
68 cranpose_core::push_parent(id);
69 content();
70 cranpose_core::pop_parent();
71 id
72}
73
74#[composable]
75pub fn SubcomposeLayout(
76 modifier: Modifier,
77 measure_policy: impl for<'scope> Fn(
78 &mut SubcomposeMeasureScopeImpl<'scope>,
79 Constraints,
80 ) -> MeasureResult
81 + 'static,
82) -> NodeId {
83 cranpose_core::debug_label_current_scope("SubcomposeLayout");
84 let policy_cell =
85 cranpose_core::remember(|| Rc::new(RefCell::new(None::<Rc<SubcomposeMeasurePolicy>>)))
86 .with(|cell| cell.clone());
87 let current_policy: Rc<SubcomposeMeasurePolicy> = Rc::new(measure_policy);
88 let policy_captures_changed = {
89 let mut policy_cell_ref = policy_cell.borrow_mut();
90 let changed = policy_cell_ref
91 .as_ref()
92 .is_none_or(|previous| !Rc::ptr_eq(previous, ¤t_policy));
93 *policy_cell_ref = Some(current_policy);
94 changed
95 };
96 let policy: Rc<SubcomposeMeasurePolicy> = cranpose_core::remember(move || {
97 let policy_cell = policy_cell.clone();
98 let policy: Rc<SubcomposeMeasurePolicy> =
99 Rc::new(
100 move |scope, constraints| match policy_cell.borrow().as_ref().cloned() {
101 Some(current) => current(scope, constraints),
102 None => empty_subcompose_measure_result(constraints),
103 },
104 );
105 policy
106 })
107 .with(|policy| policy.clone());
108 let id = cranpose_core::with_current_composer(|composer| {
109 composer.emit_node(|| SubcomposeLayoutNode::new(modifier.clone(), Rc::clone(&policy)))
110 });
111 let captured_context =
112 cranpose_core::with_current_composer(|composer| composer.capture_composition_context());
113 let composed_density = crate::density::density();
114 if let Err(err) = cranpose_core::with_node_mut(id, |node: &mut SubcomposeLayoutNode| {
115 node.set_modifier(modifier.clone());
116 node.set_measure_policy(Rc::clone(&policy));
117 node.set_captured_context(captured_context.clone());
118 node.set_density(composed_density);
119 if policy_captures_changed {
120 node.invalidate_subcomposition();
121 }
122 }) {
123 debug_assert!(false, "failed to update SubcomposeLayout node: {err}");
124 }
125 id
126}
127
128fn empty_subcompose_measure_result(constraints: Constraints) -> MeasureResult {
129 let (width, height) = constraints.constrain(0.0, 0.0);
130 MeasureResult::new(Size { width, height }, Vec::new())
131}
132
133#[composable(no_skip)]
134pub fn BoxWithConstraints<F>(modifier: Modifier, content: F) -> NodeId
135where
136 F: FnMut(BoxWithConstraintsScopeImpl) + 'static,
137{
138 let content_ref: Rc<RefCell<F>> = Rc::new(RefCell::new(content));
139 SubcomposeLayout(modifier, move |scope, constraints| {
140 let scope_impl = BoxWithConstraintsScopeImpl::new(constraints);
141 let scope_for_content = scope_impl;
142 let measurables = {
143 let content_ref = Rc::clone(&content_ref);
144 scope.subcompose(SlotId::new(0), constraints, move || {
145 cranpose_core::debug_label_current_scope("BoxWithConstraints.slot(0)");
146 let mut content = content_ref.borrow_mut();
147 content(scope_for_content);
148 })
149 };
150 let child_constraints = Constraints {
151 min_width: 0.0,
152 max_width: constraints.max_width,
153 min_height: 0.0,
154 max_height: constraints.max_height,
155 };
156
157 let mut width = 0.0_f32;
158 let mut height = 0.0_f32;
159 let mut placements = Vec::with_capacity(measurables.len());
160
161 for measurable in measurables {
162 let placeable = scope.measure(measurable, child_constraints);
163 width = width.max(placeable.width());
164 height = height.max(placeable.height());
165 placeable.place(0.0, 0.0);
166 placements.push(Placement::new(placeable.node_id(), 0.0, 0.0, 0));
167 }
168
169 width = width.clamp(constraints.min_width, constraints.max_width);
170 height = height.clamp(constraints.min_height, constraints.max_height);
171 scope.layout(width, height, placements)
172 })
173}
174
175#[cfg(test)]
176mod tests {
177 use std::cell::Cell;
178
179 use cranpose_core::{Composition, MemoryApplier, MutableState, location_key};
180
181 use super::*;
182
183 #[test]
184 fn layout_recomposes_when_content_reads_state() {
185 let _app_context = crate::render_state::app_context_test_scope();
186 thread_local! {
187 static INVOCATIONS: Cell<usize> = const { Cell::new(0) };
188 }
189
190 let mut composition = Composition::new(MemoryApplier::new());
191 let runtime = composition.runtime_handle();
192 let state = MutableState::with_runtime(0_i32, runtime);
193
194 composition
195 .render(location_key(file!(), line!(), column!()), {
196 let observed_state = state;
197 move || {
198 Layout(
199 Modifier::empty(),
200 crate::layout::policies::EmptyMeasurePolicy,
201 {
202 let observed_state = observed_state;
203 move || {
204 let _ = observed_state.value();
205 INVOCATIONS.with(|calls| calls.set(calls.get() + 1));
206 }
207 },
208 );
209 }
210 })
211 .expect("initial layout render");
212
213 INVOCATIONS.with(|calls| assert_eq!(calls.get(), 1));
214
215 state.set_value(1);
216 composition
217 .process_invalid_scopes()
218 .expect("layout content recomposition");
219
220 INVOCATIONS.with(|calls| assert_eq!(calls.get(), 2));
221 }
222
223 #[test]
224 fn subcompose_missing_policy_cell_measures_empty_layout() {
225 let result = empty_subcompose_measure_result(Constraints {
226 min_width: 12.0,
227 max_width: 120.0,
228 min_height: 8.0,
229 max_height: 90.0,
230 });
231
232 assert_eq!(result.size.width, 12.0);
233 assert_eq!(result.size.height, 8.0);
234 assert!(result.placements.is_empty());
235 }
236}