1use waft_embedder::{Offset, Size, TextBaseline};
4use waft_foundation::App;
5use waft_rendering::{
6 AnyRenderBox, AnyRenderObject, BoxConstraints, ChildLayoutHelper, Constraints, PaintingContext,
7 RenderBox, RenderBoxData, RenderHandle, RenderObject, RenderObjectData,
8 RenderObjectWithChildData, RenderObjectWithChildMixin, RenderProxyBoxMixin,
9};
10use waft_widgets::{
11 BuildContext, IntoWidget, KeyRef, Positioned, RenderObjectWidget,
12 SingleChildRenderObjectWidget, Stack, StackFit, StatelessWidget, WidgetRef,
13};
14
15#[derive(Debug)]
27pub struct GridTile {
28 pub key: Option<KeyRef>,
29 pub header: Option<WidgetRef>,
33 pub footer: Option<WidgetRef>,
37 pub child: WidgetRef,
39}
40
41impl GridTile {
42 #[cfg_attr(debug_assertions, track_caller)]
44 pub fn new<K>(child: impl IntoWidget<K>) -> GridTile {
45 GridTile {
46 key: None,
47 header: None,
48 footer: None,
49 child: child.into_widget(),
50 }
51 }
52
53 pub fn key(mut self, key: KeyRef) -> GridTile {
55 self.key = Some(key);
56 self
57 }
58
59 #[cfg_attr(debug_assertions, track_caller)]
61 pub fn header<K>(mut self, header: impl IntoWidget<K>) -> GridTile {
62 self.header = Some(header.into_widget());
63 self
64 }
65
66 #[cfg_attr(debug_assertions, track_caller)]
68 pub fn footer<K>(mut self, footer: impl IntoWidget<K>) -> GridTile {
69 self.footer = Some(footer.into_widget());
70 self
71 }
72}
73
74impl StatelessWidget for GridTile {
75 fn key(&self) -> Option<&KeyRef> {
76 self.key.as_ref()
77 }
78
79 fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
80 if self.header.is_none() && self.footer.is_none() {
81 return self.child.clone();
82 }
83
84 let mut children = vec![FillBoundedAxes::new(self.child.clone()).into_widget()];
89 if let Some(header) = &self.header {
90 children.push(
91 Positioned::new(header.clone())
92 .top(0.0)
93 .left(0.0)
94 .right(0.0)
95 .into_widget(),
96 );
97 }
98 if let Some(footer) = &self.footer {
99 children.push(
100 Positioned::new(footer.clone())
101 .left(0.0)
102 .bottom(0.0)
103 .right(0.0)
104 .into_widget(),
105 );
106 }
107 Stack::new()
108 .fit(StackFit::Passthrough)
109 .children(children)
110 .into_widget()
111 }
112}
113
114#[derive(Debug)]
117struct FillBoundedAxes {
118 child: WidgetRef,
119}
120
121impl FillBoundedAxes {
122 fn new(child: WidgetRef) -> FillBoundedAxes {
123 FillBoundedAxes { child }
124 }
125}
126
127impl RenderObjectWidget for FillBoundedAxes {
128 type RenderObject = RenderFillBoundedAxes;
129
130 fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
131 RenderFillBoundedAxes::new(app).as_object()
132 }
133}
134
135impl SingleChildRenderObjectWidget for FillBoundedAxes {
136 fn child(&self) -> Option<&WidgetRef> {
137 Some(&self.child)
138 }
139}
140
141struct RenderFillBoundedAxes {
143 render_object: RenderObjectData,
144 render_box: RenderBoxData,
145 child: RenderObjectWithChildData<AnyRenderBox>,
146}
147
148impl RenderFillBoundedAxes {
149 fn new(app: &mut App) -> RenderHandle<RenderFillBoundedAxes> {
150 RenderHandle::new_box(
151 app,
152 RenderFillBoundedAxes {
153 render_object: RenderObjectData::new(),
154 render_box: RenderBoxData::new(),
155 child: RenderObjectWithChildData::new(),
156 },
157 )
158 }
159
160 fn fill_bounded_axes(constraints: BoxConstraints) -> BoxConstraints {
161 constraints
162 .copy_with()
163 .min_width(if constraints.has_bounded_width() {
164 constraints.max_width
165 } else {
166 constraints.min_width
167 })
168 .min_height(if constraints.has_bounded_height() {
169 constraints.max_height
170 } else {
171 constraints.min_height
172 })
173 }
174}
175
176impl RenderObjectWithChildMixin for RenderFillBoundedAxes {
177 type ChildType = AnyRenderBox;
178
179 fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
180 &self.get(app).child
181 }
182
183 fn child_data_mut(
184 self: RenderHandle<Self>,
185 app: &mut App,
186 ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
187 &mut self.get_mut(app).child
188 }
189}
190
191impl RenderProxyBoxMixin for RenderFillBoundedAxes {}
192
193impl RenderObject for RenderFillBoundedAxes {
194 waft_rendering::render_object_accessors!();
195
196 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
197 let constraints = self.constraints(app);
198 let child_constraints = RenderFillBoundedAxes::fill_bounded_axes(constraints);
199 let Some(child) = self.child(app) else {
200 let size = constraints.constrain(child_constraints.smallest());
201 self.set_size(app, size);
202 return;
203 };
204 let child_size = ChildLayoutHelper::layout_child(app, child, child_constraints);
205 self.set_size(app, constraints.constrain(child_size));
206 }
207
208 fn paint(
209 self: RenderHandle<Self>,
210 app: &mut App,
211 context: &mut PaintingContext,
212 offset: Offset,
213 ) {
214 RenderProxyBoxMixin::paint(self, app, context, offset);
215 }
216
217 fn visit_children(
218 self: RenderHandle<Self>,
219 app: &App,
220 visitor: &mut dyn FnMut(AnyRenderObject),
221 ) {
222 if let Some(child) = self.child(app) {
223 visitor(child.as_object());
224 }
225 }
226}
227
228impl RenderBox for RenderFillBoundedAxes {
229 waft_rendering::render_box_accessors!();
230
231 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
232 RenderProxyBoxMixin::setup_parent_data(self, app, child);
233 }
234
235 fn apply_paint_transform(
236 self: RenderHandle<Self>,
237 app: &App,
238 child: AnyRenderObject,
239 transform: &mut waft_embedder::Matrix4,
240 ) {
241 RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
242 }
243
244 fn hit_test_children(
245 self: RenderHandle<Self>,
246 app: &mut App,
247 result: &mut waft_rendering::BoxHitTestResult<'_>,
248 position: Offset,
249 ) -> bool {
250 RenderProxyBoxMixin::hit_test_children(self, app, result, position)
251 }
252
253 fn compute_min_intrinsic_width(self: RenderHandle<Self>, _app: &mut App, _height: f64) -> f64 {
256 0.0
257 }
258
259 fn compute_max_intrinsic_width(self: RenderHandle<Self>, _app: &mut App, _height: f64) -> f64 {
260 0.0
261 }
262
263 fn compute_min_intrinsic_height(self: RenderHandle<Self>, _app: &mut App, _width: f64) -> f64 {
264 0.0
265 }
266
267 fn compute_max_intrinsic_height(self: RenderHandle<Self>, _app: &mut App, _width: f64) -> f64 {
268 0.0
269 }
270
271 fn compute_distance_to_actual_baseline(
272 self: RenderHandle<Self>,
273 app: &mut App,
274 baseline: TextBaseline,
275 ) -> Option<f64> {
276 RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
277 }
278
279 fn compute_dry_layout(
280 self: RenderHandle<Self>,
281 app: &mut App,
282 constraints: BoxConstraints,
283 ) -> Size {
284 let child_constraints = RenderFillBoundedAxes::fill_bounded_axes(constraints);
285 if child_constraints.is_tight() {
286 return child_constraints.smallest();
287 }
288 let child_size = match self.child(app) {
289 Some(child) => child.get_dry_layout(app, child_constraints),
290 None => child_constraints.smallest(),
291 };
292 constraints.constrain(child_size)
293 }
294
295 fn compute_dry_baseline(
296 self: RenderHandle<Self>,
297 app: &mut App,
298 constraints: BoxConstraints,
299 baseline: TextBaseline,
300 ) -> Option<f64> {
301 let child_constraints = RenderFillBoundedAxes::fill_bounded_axes(constraints);
302 self.child(app)?
303 .get_dry_baseline(app, child_constraints, baseline)
304 }
305}
306
307#[cfg(test)]
308mod tests {
309 use waft_embedder::{Size, TextBaseline};
310 use waft_foundation::ValueKey;
311 use waft_painting::{Alignment, Axis, BoxDecoration};
312 use waft_widgets::testing::{WidgetTester, find, test_widgets};
313 use waft_widgets::{
314 Align, Center, ColoredBox, ConstrainedBox, Container, DecoratedBox, Directionality, Icon,
315 LayoutBuilder, ListView, SizedBox, Text, TextDirection,
316 };
317
318 use super::*;
319 use crate::colors::Colors;
320 use crate::grid_tile_bar::GridTileBar;
321 use crate::icons::Icons;
322 use crate::test_support::material_app;
323 use crate::theme_data::ThemeData;
324
325 fn pump_home<K>(tester: &mut WidgetTester, home: impl IntoWidget<K>) {
327 let theme = ThemeData::builder().build(&tester.cell.borrow());
328 tester.pump_widget(material_app(theme, home.into_widget()));
329 }
330
331 fn key(name: &'static str) -> KeyRef {
332 KeyRef::from(ValueKey::new(name))
333 }
334
335 fn tile_box(tester: &WidgetTester) -> AnyRenderBox {
336 tester
337 .render_object(find::by_type::<GridTile>())
338 .as_box()
339 .expect("a grid tile is a box")
340 }
341
342 #[test]
343 fn grid_tile_control_test() {
344 test_widgets(|tester| {
345 let header_key = key("header");
346 let footer_key = key("footer");
347
348 pump_home(
349 tester,
350 GridTile::new(DecoratedBox::new(
351 BoxDecoration::new().color(Colors::GREEN.shade500()),
352 ))
353 .header(
354 GridTileBar::new()
355 .key(header_key.clone())
356 .leading(Icon::new(Some(Icons::thumb_up())))
357 .title(Text::new("Header"))
358 .subtitle(Text::new("Subtitle"))
359 .trailing(Icon::new(Some(Icons::thumb_up()))),
360 )
361 .footer(
362 GridTileBar::new()
363 .key(footer_key.clone())
364 .title(Text::new("Footer"))
365 .background_color(Colors::BLACK38),
366 ),
367 );
368
369 assert_eq!(find::text("Header").evaluate(tester).len(), 1);
370 assert_eq!(find::text("Footer").evaluate(tester).len(), 1);
371
372 assert!(
373 tester.get_bottom_left(find::by_key(header_key)).dy()
374 < tester.get_top_left(find::by_key(footer_key)).dy()
375 );
376
377 tester.pump_widget(Directionality::new(
378 TextDirection::Ltr,
379 GridTile::new(Text::new("Simple")),
380 ));
381
382 assert_eq!(find::text("Simple").evaluate(tester).len(), 1);
383 });
384 }
385
386 #[test]
387 fn grid_tile_does_not_crash_at_zero_area() {
388 test_widgets(|tester| {
389 pump_home(
390 tester,
391 Center::new().child(SizedBox::shrink().child(GridTile::new(Text::new("X")))),
392 );
393 assert_eq!(tester.get_size(find::by_type::<GridTile>()), Size::ZERO);
394 });
395 }
396
397 #[test]
398 fn grid_tile_with_header_and_footer_sizes_itself_to_its_child_when_the_width_is_unbounded() {
399 test_widgets(|tester| {
400 pump_home(
401 tester,
402 Center::new().child(
403 SizedBox::new().height(100.0).child(
404 ListView::builder(|_app, _context, _index| {
405 Some(
406 GridTile::new(
407 Container::new()
408 .height(100.0)
409 .width(80.0)
410 .color(Colors::RED.primary()),
411 )
412 .header(Text::new("Header"))
413 .footer(Text::new("Footer"))
414 .into_widget(),
415 )
416 })
417 .item_count(1)
418 .build()
419 .scroll_direction(Axis::Horizontal),
420 ),
421 ),
422 );
423
424 assert_eq!(
425 tester.get_size(find::by_type::<GridTile>()),
426 Size::new(80.0, 100.0)
427 );
428 assert_eq!(find::text("Header").evaluate(tester).len(), 1);
429 assert_eq!(find::text("Footer").evaluate(tester).len(), 1);
430 });
431 }
432
433 #[test]
434 fn grid_tile_child_fills_the_tile_when_the_constraints_are_tight() {
435 test_widgets(|tester| {
436 let child_key = key("child");
437
438 pump_home(
439 tester,
440 Center::new().child(
441 SizedBox::new().width(200.0).height(150.0).child(
442 GridTile::new(
443 ColoredBox::new(Colors::RED.primary()).key(child_key.clone()),
444 )
445 .header(Text::new("Header"))
446 .footer(Text::new("Footer")),
447 ),
448 ),
449 );
450
451 assert_eq!(
452 tester.get_size(find::by_type::<GridTile>()),
453 Size::new(200.0, 150.0)
454 );
455 assert_eq!(
456 tester.get_size(find::by_key(child_key)),
457 Size::new(200.0, 150.0)
458 );
459 });
460 }
461
462 #[test]
463 fn grid_tile_child_fills_the_tile_when_the_constraints_are_bounded_but_loose() {
464 test_widgets(|tester| {
465 let child_key = key("child");
466
467 pump_home(
468 tester,
469 Center::new().child(
470 ConstrainedBox::new(BoxConstraints::new().max_width(200.0).max_height(150.0))
471 .child(
472 GridTile::new(
473 Container::new()
474 .key(child_key.clone())
475 .width(80.0)
476 .height(100.0)
477 .color(Colors::RED.primary()),
478 )
479 .header(Text::new("Header"))
480 .footer(Text::new("Footer")),
481 ),
482 ),
483 );
484
485 assert_eq!(
486 tester.get_size(find::by_type::<GridTile>()),
487 Size::new(200.0, 150.0)
488 );
489 assert_eq!(
490 tester.get_size(find::by_key(child_key)),
491 Size::new(200.0, 150.0)
492 );
493 });
494 }
495
496 #[test]
497 fn grid_tile_dry_baseline_matches_its_baseline_when_the_constraints_are_bounded_but_loose() {
498 test_widgets(|tester| {
499 let constraints = BoxConstraints::new().max_width(200.0).max_height(150.0);
500
501 pump_home(
502 tester,
503 Center::new().child(
504 ConstrainedBox::new(constraints).child(
505 GridTile::new(
506 Align::new()
509 .alignment(Alignment::CENTER_LEFT.into())
510 .height_factor(1.0)
511 .child(Text::new("X")),
512 )
513 .footer(Text::new("Footer")),
514 ),
515 ),
516 );
517
518 let text = tester
521 .render_object(find::text("X"))
522 .as_box()
523 .expect("a text is a box");
524 let text_baseline = text
525 .get_dry_baseline(
526 &mut tester.cell.borrow_mut(),
527 BoxConstraints::new(),
528 TextBaseline::Alphabetic,
529 )
530 .expect("a text has a baseline");
531 let expected_baseline = tester.get_top_left(find::text("X")).dy()
532 - tester.get_top_left(find::by_type::<GridTile>()).dy()
533 + text_baseline;
534 assert_eq!(
535 tester.get_size(find::by_type::<GridTile>()),
536 Size::new(200.0, 150.0)
537 );
538
539 let tile = tester
540 .render_object(find::descendant(
541 find::by_type::<GridTile>(),
542 find::by_type::<Stack>(),
543 ))
544 .as_box()
545 .expect("a stack is a box");
546 assert_eq!(
547 tile.get_dry_baseline(
548 &mut tester.cell.borrow_mut(),
549 constraints,
550 TextBaseline::Alphabetic
551 ),
552 Some(expected_baseline)
553 );
554 });
555 }
556
557 #[test]
558 fn grid_tile_with_header_and_footer_reports_zero_intrinsic_sizes() {
559 test_widgets(|tester| {
560 pump_home(
561 tester,
562 GridTile::new(SizedBox::new().width(80.0).height(100.0))
563 .header(Text::new("Header"))
564 .footer(Text::new("Footer")),
565 );
566
567 let tile = tile_box(tester);
568 let mut app = tester.cell.borrow_mut();
569 assert_eq!(tile.get_min_intrinsic_width(&mut app, 150.0), 0.0);
570 assert_eq!(tile.get_max_intrinsic_width(&mut app, 150.0), 0.0);
571 assert_eq!(tile.get_min_intrinsic_height(&mut app, 200.0), 0.0);
572 assert_eq!(tile.get_max_intrinsic_height(&mut app, 200.0), 0.0);
573 });
574 }
575
576 #[test]
577 fn grid_tile_dry_layout_does_not_query_its_child_when_both_axes_are_bounded() {
578 test_widgets(|tester| {
579 pump_home(
580 tester,
581 GridTile::new(
582 LayoutBuilder::new(|_app, _context, _constraints| {
583 SizedBox::new().into_widget()
584 })
585 .into_widget(),
586 )
587 .header(Text::new("Header"))
588 .footer(Text::new("Footer")),
589 );
590
591 let tile = tile_box(tester);
592 let mut app = tester.cell.borrow_mut();
593 assert_eq!(
594 tile.get_dry_layout(
595 &mut app,
596 BoxConstraints::new().max_width(200.0).max_height(150.0)
597 ),
598 Size::new(200.0, 150.0)
599 );
600 assert_eq!(
601 tile.get_dry_layout(
602 &mut app,
603 BoxConstraints::tight_for(Some(200.0), Some(150.0))
604 ),
605 Size::new(200.0, 150.0)
606 );
607 });
608 }
609}