Skip to main content

waft_widgets/widgets/
layout_builder.rs

1//! Flutter counterpart: `widgets/layout_builder.dart`.
2//!
3//! Dart's `AbstractLayoutBuilder<LayoutInfoType>` / `ConstrainedLayoutBuilder<ConstraintType>`
4//! generics collapse into [`LayoutBuilder`] over `BoxConstraints`; `SliverLayoutBuilder`
5//! waits with slivers and brings the abstraction back with it.
6
7use std::any::{Any, TypeId};
8use std::fmt;
9use std::panic::Location;
10use std::rc::Rc;
11
12use waft_embedder::{Offset, Size, TextBaseline};
13use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
14use waft_rendering::{
15    AnyBoxConstraints, AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult,
16    DryLayoutFailure, PaintingContext, RenderBox, RenderBoxData, RenderHandle, RenderObject,
17    RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin,
18    RenderObjectWithLayoutCallbackData, RenderObjectWithLayoutCallbackMixin,
19    debug_checking_intrinsics,
20};
21use waft_scheduler::{FrameCallback, SchedulerBinding, SchedulerPhase};
22
23use crate::framework::{
24    AnyElement, BuildContext, BuildScope, BuildScopeCallback, CreationLocation, Element,
25    ElementData, KeyRef, RenderObjectElement, RenderObjectElementData, RenderObjectElementWidget,
26    RenderObjectWidget, Slot, Widget, WidgetKind, WidgetRef, downcast_widget,
27};
28use crate::view::View;
29
30/// The signature of the [`LayoutBuilder`] builder function.
31///
32/// The constraints are the box's as its parent gave them, a `BoxConstraints` subclass
33/// instance included ([`AnyBoxConstraints::extension`] is Dart's `constraints as T`).
34pub type LayoutWidgetBuilder = Rc<dyn Fn(&mut App, BuildContext, AnyBoxConstraints) -> WidgetRef>;
35
36/// Builds a widget tree that can depend on the parent widget's size.
37///
38/// Similar to the `Builder` widget except that the framework calls the
39/// [`builder`](Self::builder) function at layout time and provides the parent widget's
40/// constraints. This is useful when the parent constrains the child's size and doesn't
41/// depend on the child's intrinsic size. The [`LayoutBuilder`]'s final size will match its
42/// child's size.
43///
44/// The [`builder`](Self::builder) function is called in the following situations:
45///
46/// * The first time the widget is laid out.
47/// * When the parent widget passes different layout constraints.
48/// * When the parent widget updates this widget.
49/// * When the dependencies that the [`builder`](Self::builder) function subscribes to change.
50///
51/// The [`builder`](Self::builder) function is _not_ called during layout if the parent
52/// passes the same constraints repeatedly.
53///
54/// If the child should be smaller than the parent, consider wrapping the child in an `Align`
55/// widget. If the child might want to be bigger, consider wrapping it in a
56/// `SingleChildScrollView` or `OverflowBox`.
57///
58/// See also:
59///
60///  * `SliverLayoutBuilder`, the sliver counterpart of this widget.
61///  * `Builder`, which calls a `build` function at build time.
62///  * `StatefulBuilder`, which passes its `build` function a `setState` callback.
63///  * `CustomSingleChildLayout`, which positions its child during layout.
64pub struct LayoutBuilder {
65    pub key: Option<KeyRef>,
66    /// Called at layout time to construct the widget tree.
67    ///
68    /// The builder must not return null.
69    pub builder: LayoutWidgetBuilder,
70    /// Where this widget was made, in a debug build; see [`Widget::creation_location`].
71    created: Option<CreationLocation>,
72}
73
74impl LayoutBuilder {
75    /// Creates a widget that defers its building until layout.
76    pub fn new(
77        builder: impl Fn(&mut App, BuildContext, AnyBoxConstraints) -> WidgetRef + 'static,
78    ) -> LayoutBuilder {
79        LayoutBuilder {
80            key: None,
81            builder: Rc::new(builder),
82            created: None,
83        }
84    }
85
86    /// Dart `LayoutBuilder(key:)`.
87    pub fn key(mut self, key: KeyRef) -> LayoutBuilder {
88        self.key = Some(key);
89        self
90    }
91
92    /// The tree node: a `LayoutBuilder` is its own tree node, which [`IntoWidget`] converts.
93    #[cfg_attr(debug_assertions, track_caller)]
94    pub fn into_widget(mut self) -> WidgetRef {
95        self.created = Some(CreationLocation::of_caller());
96        Rc::new(self)
97    }
98
99    /// Whether [`builder`](Self::builder) needs to be called again even if the layout
100    /// constraints are the same.
101    ///
102    /// When this widget's configuration is updated, the [`builder`](Self::builder) callback
103    /// most likely needs to be called to build this widget's child. However, subclasses may
104    /// provide ways in which the widget can be updated without needing to rebuild the child.
105    /// Such subclasses can use this method to tell the framework when the child widget
106    /// should be rebuilt.
107    ///
108    /// When this method is called by the framework, the newly configured widget is asked if
109    /// it requires a rebuild, and it is passed the old widget as a parameter.
110    pub fn update_should_rebuild(&self, old_widget: &LayoutBuilder) -> bool {
111        let _ = old_widget;
112        true
113    }
114}
115
116impl fmt::Debug for LayoutBuilder {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.debug_struct("LayoutBuilder").finish_non_exhaustive()
119    }
120}
121
122impl Widget for LayoutBuilder {
123    fn key(&self) -> Option<&KeyRef> {
124        self.key.as_ref()
125    }
126
127    fn creation_location(&self) -> Option<&'static Location<'static>> {
128        self.created.and_then(CreationLocation::location)
129    }
130
131    fn record_creation_location(&mut self, location: CreationLocation) {
132        self.created = Some(location);
133    }
134
135    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
136        LayoutBuilderElement::new(app, this).as_element()
137    }
138
139    fn as_any(&self) -> &dyn Any {
140        self
141    }
142
143    fn widget_type(&self) -> TypeId {
144        TypeId::of::<LayoutBuilder>()
145    }
146
147    fn kind(&self) -> WidgetKind {
148        WidgetKind::Other
149    }
150}
151
152impl RenderObjectWidget for LayoutBuilder {
153    type RenderObject = RenderLayoutBuilder;
154
155    fn key(&self) -> Option<&KeyRef> {
156        self.key.as_ref()
157    }
158
159    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
160        RenderLayoutBuilder::new(app).as_object()
161    }
162
163    // updateRenderObject is redundant with the logic in the LayoutBuilderElement below.
164    fn update_render_object(
165        &self,
166        _app: &mut App,
167        _context: BuildContext,
168        _render_object: RenderHandle<RenderLayoutBuilder>,
169    ) {
170    }
171}
172
173/// Dart's `_LayoutBuilderElement`: builds its child from within the render object's layout.
174pub struct LayoutBuilderElement {
175    element: ElementData,
176    render_object_element: RenderObjectElementData,
177    child: Option<AnyElement>,
178    /// Dart's `late final _buildScope`, created right after the element so its
179    /// `scheduleRebuild` can name it.
180    build_scope: Option<Ref<BuildScope>>,
181    // To schedule a rebuild, markNeedsLayout needs to be called on this Element's
182    // render object (as the rebuilding is done in its performLayout call). However,
183    // the render tree should typically be kept clean during the postFrameCallbacks
184    // and the idle phase, so the layout data can be safely read.
185    deferred_callback_scheduled: bool,
186    // The constraints that were used to invoke the layout callback with last time,
187    // during layout. The `previous_layout_info` value is compared to the new one
188    // to determine whether the builder needs to be called.
189    previous_layout_info: Option<AnyBoxConstraints>,
190    needs_build: bool,
191}
192
193impl LayoutBuilderElement {
194    fn new(app: &mut App, widget: WidgetRef) -> Handle<LayoutBuilderElement> {
195        debug_assert!(downcast_widget::<LayoutBuilder>(&*widget).is_some());
196        let this = app
197            .create(LayoutBuilderElement {
198                element: ElementData::new(widget),
199                render_object_element: RenderObjectElementData::default(),
200                child: None,
201                build_scope: None,
202                deferred_callback_scheduled: false,
203                previous_layout_info: None,
204                needs_build: true,
205            })
206            .into_tree_node(app);
207        let build_scope = BuildScope::new(
208            app,
209            Some(Listener::handle_method(this, Self::schedule_rebuild)),
210        );
211        app.get_mut(this).build_scope = Some(build_scope);
212        this
213    }
214
215    fn render_layout_builder(self: Handle<Self>, app: &App) -> RenderHandle<RenderLayoutBuilder> {
216        self.typed_render_object(app)
217    }
218
219    fn schedule_rebuild(self: Handle<Self>, app: &mut App) {
220        if app.get(self).deferred_callback_scheduled {
221            return;
222        }
223        let defer_mark_needs_layout = match SchedulerBinding::scheduler_phase(app) {
224            SchedulerPhase::Idle | SchedulerPhase::PostFrameCallbacks => true,
225            SchedulerPhase::TransientCallbacks
226            | SchedulerPhase::MidFrameMicrotasks
227            | SchedulerPhase::PersistentCallbacks => false,
228        };
229        if !defer_mark_needs_layout {
230            self.render_layout_builder(app)
231                .schedule_layout_callback(app);
232            return;
233        }
234        app.get_mut(self).deferred_callback_scheduled = true;
235        SchedulerBinding::schedule_frame_callback(
236            app,
237            FrameCallback::new(move |app, _time_stamp| self.frame_callback(app)),
238            View::maybe_id_of(app, self.as_element()),
239            false,
240            true,
241        );
242    }
243
244    fn frame_callback(self: Handle<Self>, app: &mut App) {
245        app.get_mut(self).deferred_callback_scheduled = false;
246        // This method is only called when the render tree is stable, if the Element
247        // is deactivated it will never be reincorporated back to the tree.
248        if self.as_element().mounted(app) {
249            self.render_layout_builder(app)
250                .schedule_layout_callback(app);
251        }
252    }
253
254    fn rebuild_with_constraints(self: Handle<Self>, app: &mut App) {
255        let render_object = self.render_layout_builder(app);
256        let layout_info = render_object.layout_info(app);
257        let this = self.as_element();
258        let needs_callback = app.get(self).needs_build
259            || Some(&layout_info) != app.get(self).previous_layout_info.as_ref();
260        let callback: Option<BuildScopeCallback> = needs_callback.then(|| {
261            Box::new(move |app: &mut App| {
262                debug_assert!(layout_info == render_object.layout_info(app));
263                let builder = Self::widget_of(this.widget(app)).builder.clone();
264                let built = builder(app, this, layout_info.clone());
265                // A panic in the builder unwinds; there is no `ErrorWidget`.
266                let child = app.get(self).child;
267                let child = this.update_child(app, child, Some(built), None);
268                debug_assert!(child.is_some());
269                let state = app.get_mut(self);
270                state.child = child;
271                state.needs_build = false;
272                state.previous_layout_info = Some(layout_info);
273            }) as BuildScopeCallback
274        });
275        let owner = this.owner(app).expect("a laying-out element has an owner");
276        owner.build_scope(app, this, callback);
277    }
278}
279
280impl RenderObjectElementWidget for LayoutBuilderElement {
281    type Widget = LayoutBuilder;
282
283    fn widget_of(widget: &WidgetRef) -> &LayoutBuilder {
284        downcast_widget::<LayoutBuilder>(&**widget)
285            .expect("a LayoutBuilderElement holds its widget")
286    }
287}
288
289impl RenderObjectElement for LayoutBuilderElement {
290    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
291        &app.get(self).render_object_element
292    }
293
294    fn render_object_element_data_mut(
295        self: Handle<Self>,
296        app: &mut App,
297    ) -> &mut RenderObjectElementData {
298        &mut app.get_mut(self).render_object_element
299    }
300}
301
302impl Element for LayoutBuilderElement {
303    crate::element_accessors!();
304
305    const IS_RENDER_OBJECT_ELEMENT: bool = true;
306
307    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
308        self.render_object_element_data(app).render_object()
309    }
310
311    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
312        None
313    }
314
315    fn debug_doing_build(self: Handle<Self>, _app: &App) -> bool {
316        false
317    }
318
319    fn build_scope(self: Handle<Self>, app: &App) -> Handle<BuildScope> {
320        app.get(self)
321            .build_scope
322            .handle()
323            .expect("created with the element")
324    }
325
326    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
327        if let Some(child) = app.get(self).child {
328            visitor(child);
329        }
330    }
331
332    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
333        debug_assert!(app.get(self).child == Some(child));
334        app.get_mut(self).child = None;
335    }
336
337    fn mount(
338        self: Handle<Self>,
339        app: &mut App,
340        parent: Option<AnyElement>,
341        new_slot: Option<Slot>,
342    ) {
343        RenderObjectElement::mount(self, app, parent, new_slot); // Creates the renderObject.
344        let render_object = self.render_layout_builder(app);
345        render_object.update_callback(
346            app,
347            Listener::handle_method(self, Self::rebuild_with_constraints),
348        );
349    }
350
351    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
352        let old_widget = self.as_element().widget(app).clone();
353        debug_assert!(!Rc::ptr_eq(&old_widget, &new_widget));
354        RenderObjectElement::update(self, app, new_widget.clone());
355        let render_object = self.render_layout_builder(app);
356        render_object.update_callback(
357            app,
358            Listener::handle_method(self, Self::rebuild_with_constraints),
359        );
360        if Self::widget_of(&new_widget).update_should_rebuild(Self::widget_of(&old_widget)) {
361            app.get_mut(self).needs_build = true;
362            render_object.schedule_layout_callback(app);
363        }
364    }
365
366    fn mark_needs_build(self: Handle<Self>, app: &mut App) {
367        // Calling super.markNeedsBuild is not needed. This Element does not need
368        // to performRebuild since this call already does what performRebuild does,
369        // So the element is clean as soon as this method returns and does not have
370        // to be added to the dirty list or marked as dirty.
371        self.render_layout_builder(app)
372            .schedule_layout_callback(app);
373        app.get_mut(self).needs_build = true;
374    }
375
376    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
377        // This gets called if markNeedsBuild() is called on us.
378        // That might happen if, e.g., our builder uses Inherited widgets.
379        // Force the callback to be called, even if the layout constraints are the
380        // same. This is because that callback may depend on the updated widget
381        // configuration, or an inherited widget.
382        self.render_layout_builder(app)
383            .schedule_layout_callback(app);
384        app.get_mut(self).needs_build = true;
385        RenderObjectElement::perform_rebuild(self, app); // Calls widget.updateRenderObject (a no-op in this case).
386    }
387
388    fn deactivate(self: Handle<Self>, app: &mut App) {
389        RenderObjectElement::deactivate(self, app);
390    }
391
392    fn unmount(self: Handle<Self>, app: &mut App) {
393        let render_object = self.render_layout_builder(app);
394        render_object.set_callback(app, None);
395        RenderObjectElement::unmount(self, app);
396    }
397
398    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
399        RenderObjectElement::update_parent_data(self, app, parent_data_element);
400    }
401
402    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
403        RenderObjectElement::update_slot(self, app, new_slot);
404    }
405
406    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
407        RenderObjectElement::attach_render_object(self, app, new_slot);
408    }
409
410    fn detach_render_object(self: Handle<Self>, app: &mut App) {
411        RenderObjectElement::detach_render_object(self, app);
412    }
413
414    fn insert_render_object_child(
415        self: Handle<Self>,
416        app: &mut App,
417        child: AnyRenderObject,
418        slot: Option<Slot>,
419    ) {
420        debug_assert!(slot.is_none());
421        let render_object = self.render_layout_builder(app);
422        render_object.set_child(app, Some(child.as_box().expect("a box child")));
423    }
424
425    fn move_render_object_child(
426        self: Handle<Self>,
427        _app: &mut App,
428        _child: AnyRenderObject,
429        _old_slot: Option<Slot>,
430        _new_slot: Option<Slot>,
431    ) {
432        debug_assert!(false, "a layout builder has one child");
433    }
434
435    fn remove_render_object_child(
436        self: Handle<Self>,
437        app: &mut App,
438        child: AnyRenderObject,
439        _slot: Option<Slot>,
440    ) {
441        let render_object = self.render_layout_builder(app);
442        debug_assert!(render_object.child(app).map(|current| current.as_object()) == Some(child));
443        render_object.set_child(app, None);
444    }
445}
446
447/// Generic mixin for `RenderObject`s created by `AbstractLayoutBuilder`s, which run a
448/// builder callback during layout (Dart's `RenderAbstractLayoutBuilderMixin` /
449/// `RenderConstrainedLayoutBuilder`).
450///
451/// The callback is `LayoutBuilderElement::rebuild_with_constraints`; it reads the constraints
452/// from the render object rather than receiving them.
453pub trait RenderAbstractLayoutBuilderMixin: RenderObjectWithLayoutCallbackMixin {
454    /// The layout callback, if set.
455    fn callback(self: RenderHandle<Self>, app: &App) -> Option<Listener>;
456
457    /// Sets (or clears) the layout callback without scheduling it.
458    fn set_callback(self: RenderHandle<Self>, app: &mut App, callback: Option<Listener>);
459
460    /// Change the layout callback and schedule it.
461    fn update_callback(self: RenderHandle<Self>, app: &mut App, value: Listener) {
462        if self.callback(app).as_ref() == Some(&value) {
463            return;
464        }
465        self.set_callback(app, Some(value));
466        self.schedule_layout_callback(app);
467    }
468
469    /// The information the builder is given: this box's constraints, with their subclass.
470    fn layout_info(self: RenderHandle<Self>, app: &App) -> AnyBoxConstraints {
471        self.any_constraints(app)
472    }
473}
474
475/// Dart's `_RenderLayoutBuilder`: a box that runs its layout callback, then sizes to its
476/// child (or fills its constraints without one).
477pub struct RenderLayoutBuilder {
478    render_object: RenderObjectData,
479    render_box: RenderBoxData,
480    child: RenderObjectWithChildData<AnyRenderBox>,
481    layout_callback: RenderObjectWithLayoutCallbackData,
482    callback: Option<Listener>,
483}
484
485impl RenderLayoutBuilder {
486    /// Creates the render object with no callback and no child.
487    pub fn new(app: &mut App) -> RenderHandle<RenderLayoutBuilder> {
488        RenderHandle::new_box(
489            app,
490            RenderLayoutBuilder {
491                render_object: RenderObjectData::default(),
492                render_box: RenderBoxData::default(),
493                child: RenderObjectWithChildData::default(),
494                layout_callback: RenderObjectWithLayoutCallbackData::default(),
495                callback: None,
496            },
497        )
498    }
499}
500
501impl RenderObjectWithChildMixin for RenderLayoutBuilder {
502    type ChildType = AnyRenderBox;
503
504    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
505        &self.get(app).child
506    }
507
508    fn child_data_mut(
509        self: RenderHandle<Self>,
510        app: &mut App,
511    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
512        &mut self.get_mut(app).child
513    }
514}
515
516impl RenderObjectWithLayoutCallbackMixin for RenderLayoutBuilder {
517    fn layout_callback_data(
518        self: RenderHandle<Self>,
519        app: &App,
520    ) -> &RenderObjectWithLayoutCallbackData {
521        &self.get(app).layout_callback
522    }
523
524    fn layout_callback_data_mut(
525        self: RenderHandle<Self>,
526        app: &mut App,
527    ) -> &mut RenderObjectWithLayoutCallbackData {
528        &mut self.get_mut(app).layout_callback
529    }
530
531    fn layout_callback(self: RenderHandle<Self>, app: &mut App) {
532        let callback = self
533            .get(app)
534            .callback
535            .clone()
536            .expect("a callback is set before layout");
537        callback.call(app);
538    }
539}
540
541impl RenderAbstractLayoutBuilderMixin for RenderLayoutBuilder {
542    fn callback(self: RenderHandle<Self>, app: &App) -> Option<Listener> {
543        self.get(app).callback.clone()
544    }
545
546    fn set_callback(self: RenderHandle<Self>, app: &mut App, callback: Option<Listener>) {
547        self.get_mut(app).callback = callback;
548    }
549}
550
551impl RenderObject for RenderLayoutBuilder {
552    waft_rendering::render_object_accessors!();
553
554    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
555        let constraints = self.constraints(app);
556        self.run_layout_callback(app);
557        if let Some(child) = self.child(app) {
558            child.layout(app, constraints, true);
559            let size = constraints.constrain(child.size(app));
560            self.set_size(app, size);
561        } else {
562            self.set_size(app, constraints.biggest());
563        }
564    }
565
566    fn paint(
567        self: RenderHandle<Self>,
568        app: &mut App,
569        context: &mut PaintingContext,
570        offset: Offset,
571    ) {
572        if let Some(child) = self.child(app) {
573            context.paint_child(app, child.as_object(), offset);
574        }
575    }
576
577    fn visit_children(
578        self: RenderHandle<Self>,
579        app: &App,
580        visitor: &mut dyn FnMut(AnyRenderObject),
581    ) {
582        if let Some(child) = self.child(app) {
583            visitor(child.as_object());
584        }
585    }
586}
587
588impl RenderLayoutBuilder {
589    fn debug_throw_if_not_checking_intrinsics(self: RenderHandle<Self>) -> bool {
590        let _ = self;
591        debug_assert!(
592            debug_checking_intrinsics(),
593            "LayoutBuilder does not support returning intrinsic dimensions.\n\
594             Calculating the intrinsic dimensions would require running the layout callback \
595             speculatively, which might mutate the live render object tree."
596        );
597        true
598    }
599}
600
601impl RenderBox for RenderLayoutBuilder {
602    waft_rendering::render_box_accessors!();
603
604    fn compute_min_intrinsic_width(self: RenderHandle<Self>, _app: &mut App, _height: f64) -> f64 {
605        debug_assert!(self.debug_throw_if_not_checking_intrinsics());
606        0.0
607    }
608
609    fn compute_max_intrinsic_width(self: RenderHandle<Self>, _app: &mut App, _height: f64) -> f64 {
610        debug_assert!(self.debug_throw_if_not_checking_intrinsics());
611        0.0
612    }
613
614    fn compute_min_intrinsic_height(self: RenderHandle<Self>, _app: &mut App, _width: f64) -> f64 {
615        debug_assert!(self.debug_throw_if_not_checking_intrinsics());
616        0.0
617    }
618
619    fn compute_max_intrinsic_height(self: RenderHandle<Self>, _app: &mut App, _width: f64) -> f64 {
620        debug_assert!(self.debug_throw_if_not_checking_intrinsics());
621        0.0
622    }
623
624    fn compute_dry_layout(
625        self: RenderHandle<Self>,
626        _app: &mut App,
627        _constraints: BoxConstraints,
628    ) -> Size {
629        self.debug_cannot_compute_dry_layout(DryLayoutFailure::Reason(
630            "Calculating the dry layout would require running the layout callback \
631             speculatively, which might mutate the live render object tree.",
632        ));
633        Size::ZERO
634    }
635
636    fn compute_dry_baseline(
637        self: RenderHandle<Self>,
638        _app: &mut App,
639        _constraints: BoxConstraints,
640        _baseline: TextBaseline,
641    ) -> Option<f64> {
642        self.debug_cannot_compute_dry_layout(DryLayoutFailure::Reason(
643            "Calculating the dry baseline would require running the layout callback \
644             speculatively, which might mutate the live render object tree.",
645        ));
646        None
647    }
648
649    fn hit_test_children(
650        self: RenderHandle<Self>,
651        app: &mut App,
652        result: &mut BoxHitTestResult<'_>,
653        position: Offset,
654    ) -> bool {
655        self.child(app)
656            .is_some_and(|child| child.hit_test(app, result, position))
657    }
658}
659
660#[cfg(test)]
661mod tests {
662    use std::cell::RefCell;
663    use waft_foundation::AppCell;
664
665    use waft_embedder::{Size, TextDirection};
666
667    use super::*;
668    use crate::framework::IntoWidget;
669    use crate::test_harness::Harness;
670    use crate::widgets::basic::{Directionality, SizedBox};
671
672    type Seen = Rc<RefCell<Vec<BoxConstraints>>>;
673
674    fn builder(seen: &Seen) -> WidgetRef {
675        let seen = Rc::clone(seen);
676        LayoutBuilder::new(move |_app, _context, constraints| {
677            seen.borrow_mut().push(constraints.constraints());
678            SizedBox::square(Some(10.0)).into_widget()
679        })
680        .into_widget()
681    }
682
683    fn sized(width: f64, child: WidgetRef) -> WidgetRef {
684        SizedBox::new()
685            .width(width)
686            .height(50.0)
687            .child(child)
688            .into_widget()
689    }
690
691    /// A `LayoutBuilder` is a widget wherever one is taken, as Dart's `Widget` is: `Focus::new`
692    /// takes it without the inherent `into_widget` being called.
693    #[test]
694    fn a_layout_builder_goes_wherever_a_widget_is_taken() {
695        let cell = AppCell::new();
696        let mut app = cell.borrow_mut();
697        let seen: Seen = Rc::default();
698        let seen_in_builder = Rc::clone(&seen);
699        let focused = crate::widgets::focus_scope::Focus::new(LayoutBuilder::new(
700            move |_app, _context, constraints| {
701                seen_in_builder.borrow_mut().push(constraints.constraints());
702                SizedBox::square(Some(10.0)).into_widget()
703            },
704        ));
705        let harness = Harness::mount(&mut app, focused.into_widget());
706        harness.pump(&mut app);
707        assert_eq!(seen.borrow().len(), 1, "the builder ran under the focus");
708    }
709
710    #[test]
711    fn the_builder_runs_at_layout_with_the_constraints_and_only_when_they_change() {
712        let cell = AppCell::new();
713        let mut app = cell.borrow_mut();
714        let seen: Seen = Rc::default();
715        let harness = Harness::mount(&mut app, sized(100.0, builder(&seen)));
716        harness.pump(&mut app);
717        assert_eq!(
718            *seen.borrow(),
719            vec![BoxConstraints::tight(Size::new(100.0, 50.0))]
720        );
721
722        harness.pump(&mut app);
723        assert_eq!(seen.borrow().len(), 1);
724
725        harness.set_child(&mut app, sized(80.0, builder(&seen)));
726        harness.pump(&mut app);
727        assert_eq!(seen.borrow().len(), 2);
728        assert_eq!(
729            seen.borrow()[1],
730            BoxConstraints::tight(Size::new(80.0, 50.0))
731        );
732    }
733
734    /// A `BoxConstraints` subclass with one field, as material's `_BottomSheetBoxConstraints`.
735    #[derive(Debug)]
736    struct Inset(f64);
737
738    impl waft_rendering::BoxConstraintsExtension for Inset {
739        fn as_any(&self) -> &dyn Any {
740            self
741        }
742
743        fn eq_extension(&self, other: &dyn waft_rendering::BoxConstraintsExtension) -> bool {
744            other
745                .as_any()
746                .downcast_ref::<Inset>()
747                .is_some_and(|other| other.0 == self.0)
748        }
749    }
750
751    /// Lays out its one child with the same plain constraints and an `Inset` of `self.0`.
752    #[derive(Debug)]
753    struct InsetDelegate(f64);
754
755    impl waft_rendering::MultiChildLayoutDelegate for InsetDelegate {
756        fn perform_layout(
757            &self,
758            app: &mut App,
759            children: &mut waft_rendering::MultiChildLayoutChildren,
760            size: Size,
761        ) {
762            children.layout_child(
763                app,
764                &child_id(),
765                AnyBoxConstraints::with_shared(BoxConstraints::loose(size), Rc::new(Inset(self.0))),
766            );
767        }
768
769        fn should_relayout(
770            &self,
771            old_delegate: &dyn waft_rendering::MultiChildLayoutDelegate,
772        ) -> bool {
773            old_delegate
774                .as_any()
775                .downcast_ref::<InsetDelegate>()
776                .is_none_or(|old_delegate| old_delegate.0 != self.0)
777        }
778
779        fn as_any(&self) -> &dyn Any {
780            self
781        }
782    }
783
784    fn child_id() -> waft_rendering::ChildLayoutId {
785        Rc::new(waft_foundation::ValueKey::new("child"))
786    }
787
788    #[test]
789    fn the_builder_gets_the_constraints_subclass_and_reruns_when_only_its_fields_change() {
790        let cell = AppCell::new();
791        let mut app = cell.borrow_mut();
792        let seen = Rc::new(RefCell::new(Vec::new()));
793        let layout_builder = {
794            let seen = Rc::clone(&seen);
795            LayoutBuilder::new(move |_app, _context, constraints| {
796                seen.borrow_mut().push((
797                    constraints.constraints(),
798                    constraints.extension::<Inset>().map(|inset| inset.0),
799                ));
800                SizedBox::square(Some(10.0)).into_widget()
801            })
802            .into_widget()
803        };
804        let layout = |inset: f64| {
805            sized(
806                100.0,
807                crate::widgets::basic::CustomMultiChildLayout::new(Rc::new(InsetDelegate(inset)))
808                    .children([crate::widgets::basic::LayoutId::new(
809                        child_id(),
810                        layout_builder.clone(),
811                    )
812                    .into_widget()])
813                    .into_widget(),
814            )
815        };
816        let loose = BoxConstraints::loose(Size::new(100.0, 50.0));
817        let harness = Harness::mount(&mut app, layout(1.0));
818        harness.pump(&mut app);
819        assert_eq!(*seen.borrow(), vec![(loose, Some(1.0))]);
820
821        harness.set_child(&mut app, layout(1.0));
822        harness.pump(&mut app);
823        assert_eq!(
824            seen.borrow().len(),
825            1,
826            "equal constraints, the same builder widget"
827        );
828
829        harness.set_child(&mut app, layout(2.0));
830        harness.pump(&mut app);
831        assert_eq!(
832            *seen.borrow(),
833            vec![(loose, Some(1.0)), (loose, Some(2.0))],
834            "only the subclass field changed"
835        );
836    }
837
838    #[test]
839    fn an_inherited_dependency_change_rebuilds_the_builder_during_layout() {
840        let cell = AppCell::new();
841        let mut app = cell.borrow_mut();
842        let seen = Rc::new(RefCell::new(Vec::new()));
843        let dependent = {
844            let seen = Rc::clone(&seen);
845            LayoutBuilder::new(move |app, context, _constraints| {
846                seen.borrow_mut().push(Directionality::of(app, context));
847                SizedBox::square(Some(10.0)).into_widget()
848            })
849            .into_widget()
850        };
851        let under = |direction: TextDirection, child: WidgetRef| {
852            Directionality::new(direction, child).into_widget()
853        };
854        let harness = Harness::mount(&mut app, under(TextDirection::Ltr, dependent.clone()));
855        harness.pump(&mut app);
856        harness.set_child(&mut app, under(TextDirection::Rtl, dependent));
857        harness.pump(&mut app);
858        assert_eq!(*seen.borrow(), vec![TextDirection::Ltr, TextDirection::Rtl]);
859    }
860}