1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
//! [`LayoutBuilder`]: builds its content **from the box actually available** — the
//! most powerful responsive primitive, since a component adapts wherever it is placed,
//! in a narrow sidebar or full screen, and not merely to the window.
//!
//! As with a virtualised list item, the content is **built on the fly** every frame, so
//! it has **no retained state**: hover and clicks work, but persistent keyboard focus
//! and deferred overlays do not.
//!
//! The sizing contract: **as big as what it built**, on any axis its style leaves open.
//! That is the reference's rule — `size = constraints.constrain(child.size)` — and it is
//! what lets a `LayoutBuilder` be dropped into a column without having to guess a height
//! for it first.
//!
//! It works because the widget is a **measured** leaf rather than a plain one: the
//! layout engine calls back during the computation, with the space actually available,
//! at the same point the reference runs its layout callback. The closure builds the
//! subtree, lays it out in a tree of its own, and returns its size.
//!
//! Three consequences worth knowing:
//!
//! - **A pinned axis stays pinned.** `width`, `height` and `flex` still win, because a
//! dimension the style already gives is one the engine never asks about.
//! - **The closure runs more than once a frame** — once for the measurement, once for
//! the paint, and again for each intrinsic question the engine asks. It must therefore
//! be cheap and free of side effects, which it must be anyway: it is called with no
//! retained state.
//! - **A subtree holding one is not layout-cached.** The relayout cache reuses geometry
//! when a fingerprint of the styles and the structure has not moved, and a closure has
//! no fingerprint: two frames that look identical to it can still want different
//! boxes. So the root is recomputed every frame rather than risk a stale one.
use frus_core::{Rect, Scene, Size};
use frus_layout::{Dimension, Style};
use crate::interaction::Status;
use crate::theme::Theme;
use crate::widget::Widget;
/// Builds its child from the available size (`size → widget`).
pub struct LayoutBuilder<Msg = crate::callback::Callback> {
width: Dimension,
height: Dimension,
flex_grow: f32,
/// Whether it takes all the room on offer, as an [`Aligned`](crate::Aligned) does, rather
/// than the size of what it built (milestone 586).
fills: bool,
build: Box<dyn Fn(Size) -> Box<dyn Widget<Msg>>>,
}
impl<Msg> LayoutBuilder<Msg> {
/// Builds from a `size → widget` factory. The size received is the **real box**
/// allocated to this `LayoutBuilder`, in logical px.
pub fn new<W: Widget<Msg> + 'static>(build: impl Fn(Size) -> W + 'static) -> Self {
Self {
width: Dimension::Auto,
height: Dimension::Auto,
flex_grow: 0.0,
fills: false,
build: Box::new(move |size| Box::new(build(size)) as Box<dyn Widget<Msg>>),
}
}
/// Sets the width, in logical pixels.
pub fn width(mut self, width: f32) -> Self {
self.width = Dimension::Length(width);
self
}
/// Sets the height, in logical pixels.
pub fn height(mut self, height: f32) -> Self {
self.height = Dimension::Length(height);
self
}
/// Takes all the room on offer, so that the size handed to the closure is the room and
/// not what the closure built (milestone 586).
pub(crate) fn filling(mut self) -> Self {
self.fills = true;
self
}
/// Flex growth factor along the parent's main axis.
pub fn flex(mut self, grow: f32) -> Self {
self.flex_grow = grow;
self
}
}
impl<Msg> Widget<Msg> for LayoutBuilder<Msg> {
fn style(&self) -> Style {
Style {
width: self.width,
height: self.height,
flex_grow: self.flex_grow,
..Default::default()
}
}
fn children(&self) -> &[Box<dyn Widget<Msg>>] {
&[]
}
fn paint(&self, _bounds: Rect, _status: Status, _theme: &Theme, _scene: &mut Scene) {}
fn on_click(&self) -> Option<Msg> {
None
}
fn layout_builder(&self) -> Option<&dyn Fn(Size) -> Box<dyn Widget<Msg>>> {
Some(&*self.build)
}
fn fill_axes(&self, _theme: &Theme) -> crate::widget::FillAxes {
if self.fills {
crate::widget::FillAxes::BOTH
} else {
crate::widget::FillAxes::NONE
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{build_ui, Container, Runtime, SizeClass};
use frus_core::{Color, Primitive};
#[test]
fn receives_its_real_box() {
use std::cell::Cell;
use std::rc::Rc;
let seen = Rc::new(Cell::new(Size::new(0.0, 0.0)));
let probe = seen.clone();
let lb = LayoutBuilder::<()>::new(move |size| {
probe.set(size);
Container::<()>::new().color(Color::rgb(1.0, 0.0, 0.0))
})
.width(320.0)
.height(48.0);
let _ui = build_ui(
&lb,
Size::new(800.0, 600.0),
&Runtime::default(),
&Theme::default(),
);
// The factory receives the LayoutBuilder's box, not the window's.
assert_eq!(seen.get(), Size::new(320.0, 48.0));
}
/// The reference's rule: with no height of its own, the box is as tall as what the
/// closure built. Before milestone 355 this laid out 0 px tall and the widget's own
/// documentation told you to go and find a number for it.
#[test]
fn it_is_as_big_as_what_it_built() {
let lb = LayoutBuilder::<()>::new(|_| {
Container::<()>::new()
.height(60.0)
.color(Color::rgb(1.0, 0.0, 0.0))
});
let root = crate::Flex::<()>::column()
.width(200.0)
.height(400.0)
.child(lb);
let ui = build_ui(
&root,
Size::new(200.0, 400.0),
&Runtime::default(),
&Theme::default(),
);
let painted = ui
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { rect, color, .. } if color.r > 0.9 && color.g < 0.1 => {
Some(*rect)
}
_ => None,
})
.expect("the built content is painted");
assert_eq!(
painted.height, 60.0,
"the box is its content's: {painted:?}"
);
}
/// A sibling after it is pushed down by what it built — which is the point: the box
/// is real, not a zero-height hole the rest of the column lays out through.
#[test]
fn what_it_built_pushes_its_siblings_down() {
let column = crate::Flex::<()>::column()
.width(200.0)
.height(400.0)
.child(LayoutBuilder::<()>::new(|_| {
Container::<()>::new().height(60.0)
}))
.child(
Container::<()>::new()
.height(20.0)
.color(Color::rgb(0.0, 1.0, 0.0)),
);
let ui = build_ui(
&column,
Size::new(200.0, 400.0),
&Runtime::default(),
&Theme::default(),
);
let sibling = ui
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { rect, color, .. } if color.g > 0.9 && color.r < 0.1 => {
Some(*rect)
}
_ => None,
})
.expect("the sibling is painted");
assert_eq!(sibling.y, 60.0, "it starts below the built content");
}
/// An axis the style pins is still the style's: the engine never asks about a
/// dimension it already knows, so every existing `height(...)` behaves as it did.
#[test]
fn a_pinned_axis_is_still_the_style_s() {
let lb = LayoutBuilder::<()>::new(|_| {
Container::<()>::new()
.height(60.0)
.color(Color::rgb(1.0, 0.0, 0.0))
})
.height(120.0);
let root = crate::Flex::<()>::column()
.width(200.0)
.height(400.0)
.child(lb)
.child(
Container::<()>::new()
.height(20.0)
.color(Color::rgb(0.0, 1.0, 0.0)),
);
let ui = build_ui(
&root,
Size::new(200.0, 400.0),
&Runtime::default(),
&Theme::default(),
);
let sibling = ui
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { rect, color, .. } if color.g > 0.9 && color.r < 0.1 => {
Some(*rect)
}
_ => None,
})
.expect("the sibling is painted");
assert_eq!(sibling.y, 120.0, "the style's 120, not the content's 60");
}
#[test]
fn adapts_content_to_available_width() {
// Picks a number of tiles from the box's size class.
let count_tiles = |window_w: f32| {
let lb = LayoutBuilder::<()>::new(|size| {
let tiles = match SizeClass::from_width(size.width) {
SizeClass::Compact => 1,
SizeClass::Medium => 2,
SizeClass::Expanded => 3,
};
let mut row = crate::Flex::<()>::row();
for _ in 0..tiles {
row = row.child(
Container::<()>::new()
.width(10.0)
.height(10.0)
.color(Color::WHITE),
);
}
row
})
.height(20.0);
// The root column is sized, so the stretch gives the LayoutBuilder the
// window's width and its box reflects the available width.
let root = crate::Flex::<()>::column()
.width(window_w)
.height(200.0)
.child(lb);
let ui = build_ui(
&root,
Size::new(window_w, 200.0),
&Runtime::default(),
&Theme::default(),
);
ui.scene()
.primitives()
.iter()
.filter(|p| matches!(p, Primitive::Rect { color, .. } if *color == Color::WHITE))
.count()
};
assert_eq!(count_tiles(400.0), 1);
assert_eq!(count_tiles(700.0), 2);
assert_eq!(count_tiles(1000.0), 3);
}
}