waft-widgets 0.9.1

Widget framework and widgets for Waft
Documentation
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
//! Flutter counterpart: `widgets/layout_builder.dart`.
//!
//! Dart's `AbstractLayoutBuilder<LayoutInfoType>` / `ConstrainedLayoutBuilder<ConstraintType>`
//! generics collapse into [`LayoutBuilder`] over `BoxConstraints`; `SliverLayoutBuilder`
//! waits with slivers and brings the abstraction back with it.

use std::any::{Any, TypeId};
use std::fmt;
use std::rc::Rc;

use waft_embedder::{Offset, Size, TextBaseline};
use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
use waft_rendering::{
    AnyBoxConstraints, AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult,
    DryLayoutFailure, PaintingContext, RenderBox, RenderBoxData, RenderHandle, RenderObject,
    RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin,
    RenderObjectWithLayoutCallbackData, RenderObjectWithLayoutCallbackMixin,
    debug_checking_intrinsics,
};
use waft_scheduler::{FrameCallback, SchedulerBinding, SchedulerPhase};

use crate::framework::{
    AnyElement, BuildContext, BuildScope, BuildScopeCallback, Element, ElementData, KeyRef,
    RenderObjectElement, RenderObjectElementData, RenderObjectElementWidget, RenderObjectWidget,
    Slot, Widget, WidgetKind, WidgetRef, downcast_widget,
};
use crate::view::View;

/// The signature of the [`LayoutBuilder`] builder function.
///
/// The constraints are the box's as its parent gave them, a `BoxConstraints` subclass
/// instance included ([`AnyBoxConstraints::extension`] is Dart's `constraints as T`).
pub type LayoutWidgetBuilder = Rc<dyn Fn(&mut App, BuildContext, AnyBoxConstraints) -> WidgetRef>;

/// Builds a widget tree that can depend on the parent widget's size.
///
/// Similar to the `Builder` widget except that the framework calls the
/// [`builder`](Self::builder) function at layout time and provides the parent widget's
/// constraints. This is useful when the parent constrains the child's size and doesn't
/// depend on the child's intrinsic size. The [`LayoutBuilder`]'s final size will match its
/// child's size.
///
/// The [`builder`](Self::builder) function is called in the following situations:
///
/// * The first time the widget is laid out.
/// * When the parent widget passes different layout constraints.
/// * When the parent widget updates this widget.
/// * When the dependencies that the [`builder`](Self::builder) function subscribes to change.
///
/// The [`builder`](Self::builder) function is _not_ called during layout if the parent
/// passes the same constraints repeatedly.
///
/// If the child should be smaller than the parent, consider wrapping the child in an `Align`
/// widget. If the child might want to be bigger, consider wrapping it in a
/// `SingleChildScrollView` or `OverflowBox`.
///
/// See also:
///
///  * `SliverLayoutBuilder`, the sliver counterpart of this widget.
///  * `Builder`, which calls a `build` function at build time.
///  * `StatefulBuilder`, which passes its `build` function a `setState` callback.
///  * `CustomSingleChildLayout`, which positions its child during layout.
pub struct LayoutBuilder {
    pub key: Option<KeyRef>,
    /// Called at layout time to construct the widget tree.
    ///
    /// The builder must not return null.
    pub builder: LayoutWidgetBuilder,
}

impl LayoutBuilder {
    /// Creates a widget that defers its building until layout.
    pub fn new(
        builder: impl Fn(&mut App, BuildContext, AnyBoxConstraints) -> WidgetRef + 'static,
    ) -> LayoutBuilder {
        LayoutBuilder {
            key: None,
            builder: Rc::new(builder),
        }
    }

    /// Dart `LayoutBuilder(key:)`.
    pub fn key(mut self, key: KeyRef) -> LayoutBuilder {
        self.key = Some(key);
        self
    }

    /// The tree node: a `LayoutBuilder` is its own tree node, which [`IntoWidget`] converts.
    pub fn into_widget(self) -> WidgetRef {
        Rc::new(self)
    }

    /// Whether [`builder`](Self::builder) needs to be called again even if the layout
    /// constraints are the same.
    ///
    /// When this widget's configuration is updated, the [`builder`](Self::builder) callback
    /// most likely needs to be called to build this widget's child. However, subclasses may
    /// provide ways in which the widget can be updated without needing to rebuild the child.
    /// Such subclasses can use this method to tell the framework when the child widget
    /// should be rebuilt.
    ///
    /// When this method is called by the framework, the newly configured widget is asked if
    /// it requires a rebuild, and it is passed the old widget as a parameter.
    pub fn update_should_rebuild(&self, old_widget: &LayoutBuilder) -> bool {
        let _ = old_widget;
        true
    }
}

impl fmt::Debug for LayoutBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("LayoutBuilder").finish_non_exhaustive()
    }
}

impl Widget for LayoutBuilder {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        LayoutBuilderElement::new(app, this).as_element()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn widget_type(&self) -> TypeId {
        TypeId::of::<LayoutBuilder>()
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::Other
    }
}

impl RenderObjectWidget for LayoutBuilder {
    type RenderObject = RenderLayoutBuilder;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
        RenderLayoutBuilder::new(app).as_object()
    }

    // updateRenderObject is redundant with the logic in the LayoutBuilderElement below.
    fn update_render_object(
        &self,
        _app: &mut App,
        _context: BuildContext,
        _render_object: RenderHandle<RenderLayoutBuilder>,
    ) {
    }
}

/// Dart's `_LayoutBuilderElement`: builds its child from within the render object's layout.
pub struct LayoutBuilderElement {
    element: ElementData,
    render_object_element: RenderObjectElementData,
    child: Option<AnyElement>,
    /// Dart's `late final _buildScope`, created right after the element so its
    /// `scheduleRebuild` can name it.
    build_scope: Option<Ref<BuildScope>>,
    // To schedule a rebuild, markNeedsLayout needs to be called on this Element's
    // render object (as the rebuilding is done in its performLayout call). However,
    // the render tree should typically be kept clean during the postFrameCallbacks
    // and the idle phase, so the layout data can be safely read.
    deferred_callback_scheduled: bool,
    // The constraints that were used to invoke the layout callback with last time,
    // during layout. The `previous_layout_info` value is compared to the new one
    // to determine whether the builder needs to be called.
    previous_layout_info: Option<AnyBoxConstraints>,
    needs_build: bool,
}

impl LayoutBuilderElement {
    fn new(app: &mut App, widget: WidgetRef) -> Handle<LayoutBuilderElement> {
        debug_assert!(downcast_widget::<LayoutBuilder>(&*widget).is_some());
        let this = app
            .create(LayoutBuilderElement {
                element: ElementData::new(widget),
                render_object_element: RenderObjectElementData::default(),
                child: None,
                build_scope: None,
                deferred_callback_scheduled: false,
                previous_layout_info: None,
                needs_build: true,
            })
            .into_tree_node(app);
        let build_scope = BuildScope::new(
            app,
            Some(Listener::handle_method(this, Self::schedule_rebuild)),
        );
        app.get_mut(this).build_scope = Some(build_scope);
        this
    }

    fn render_layout_builder(self: Handle<Self>, app: &App) -> RenderHandle<RenderLayoutBuilder> {
        self.typed_render_object(app)
    }

    fn schedule_rebuild(self: Handle<Self>, app: &mut App) {
        if app.get(self).deferred_callback_scheduled {
            return;
        }
        let defer_mark_needs_layout = match SchedulerBinding::scheduler_phase(app) {
            SchedulerPhase::Idle | SchedulerPhase::PostFrameCallbacks => true,
            SchedulerPhase::TransientCallbacks
            | SchedulerPhase::MidFrameMicrotasks
            | SchedulerPhase::PersistentCallbacks => false,
        };
        if !defer_mark_needs_layout {
            self.render_layout_builder(app)
                .schedule_layout_callback(app);
            return;
        }
        app.get_mut(self).deferred_callback_scheduled = true;
        SchedulerBinding::schedule_frame_callback(
            app,
            FrameCallback::new(move |app, _time_stamp| self.frame_callback(app)),
            View::maybe_id_of(app, self.as_element()),
            false,
            true,
        );
    }

    fn frame_callback(self: Handle<Self>, app: &mut App) {
        app.get_mut(self).deferred_callback_scheduled = false;
        // This method is only called when the render tree is stable, if the Element
        // is deactivated it will never be reincorporated back to the tree.
        if self.as_element().mounted(app) {
            self.render_layout_builder(app)
                .schedule_layout_callback(app);
        }
    }

    fn rebuild_with_constraints(self: Handle<Self>, app: &mut App) {
        let render_object = self.render_layout_builder(app);
        let layout_info = render_object.layout_info(app);
        let this = self.as_element();
        let needs_callback = app.get(self).needs_build
            || Some(&layout_info) != app.get(self).previous_layout_info.as_ref();
        let callback: Option<BuildScopeCallback> = needs_callback.then(|| {
            Box::new(move |app: &mut App| {
                debug_assert!(layout_info == render_object.layout_info(app));
                let builder = Self::widget_of(this.widget(app)).builder.clone();
                let built = builder(app, this, layout_info.clone());
                // A panic in the builder unwinds; there is no `ErrorWidget`.
                let child = app.get(self).child;
                let child = this.update_child(app, child, Some(built), None);
                debug_assert!(child.is_some());
                let state = app.get_mut(self);
                state.child = child;
                state.needs_build = false;
                state.previous_layout_info = Some(layout_info);
            }) as BuildScopeCallback
        });
        let owner = this.owner(app).expect("a laying-out element has an owner");
        owner.build_scope(app, this, callback);
    }
}

impl RenderObjectElementWidget for LayoutBuilderElement {
    type Widget = LayoutBuilder;

    fn widget_of(widget: &WidgetRef) -> &LayoutBuilder {
        downcast_widget::<LayoutBuilder>(&**widget)
            .expect("a LayoutBuilderElement holds its widget")
    }
}

impl RenderObjectElement for LayoutBuilderElement {
    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
        &app.get(self).render_object_element
    }

    fn render_object_element_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut RenderObjectElementData {
        &mut app.get_mut(self).render_object_element
    }
}

impl Element for LayoutBuilderElement {
    crate::element_accessors!();

    const IS_RENDER_OBJECT_ELEMENT: bool = true;

    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
        self.render_object_element_data(app).render_object()
    }

    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
        None
    }

    fn debug_doing_build(self: Handle<Self>, _app: &App) -> bool {
        false
    }

    fn build_scope(self: Handle<Self>, app: &App) -> Handle<BuildScope> {
        app.get(self)
            .build_scope
            .handle()
            .expect("created with the element")
    }

    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
        if let Some(child) = app.get(self).child {
            visitor(child);
        }
    }

    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
        debug_assert!(app.get(self).child == Some(child));
        app.get_mut(self).child = None;
    }

    fn mount(
        self: Handle<Self>,
        app: &mut App,
        parent: Option<AnyElement>,
        new_slot: Option<Slot>,
    ) {
        RenderObjectElement::mount(self, app, parent, new_slot); // Creates the renderObject.
        let render_object = self.render_layout_builder(app);
        render_object.update_callback(
            app,
            Listener::handle_method(self, Self::rebuild_with_constraints),
        );
    }

    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
        let old_widget = self.as_element().widget(app).clone();
        debug_assert!(!Rc::ptr_eq(&old_widget, &new_widget));
        RenderObjectElement::update(self, app, new_widget.clone());
        let render_object = self.render_layout_builder(app);
        render_object.update_callback(
            app,
            Listener::handle_method(self, Self::rebuild_with_constraints),
        );
        if Self::widget_of(&new_widget).update_should_rebuild(Self::widget_of(&old_widget)) {
            app.get_mut(self).needs_build = true;
            render_object.schedule_layout_callback(app);
        }
    }

    fn mark_needs_build(self: Handle<Self>, app: &mut App) {
        // Calling super.markNeedsBuild is not needed. This Element does not need
        // to performRebuild since this call already does what performRebuild does,
        // So the element is clean as soon as this method returns and does not have
        // to be added to the dirty list or marked as dirty.
        self.render_layout_builder(app)
            .schedule_layout_callback(app);
        app.get_mut(self).needs_build = true;
    }

    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
        // This gets called if markNeedsBuild() is called on us.
        // That might happen if, e.g., our builder uses Inherited widgets.
        // Force the callback to be called, even if the layout constraints are the
        // same. This is because that callback may depend on the updated widget
        // configuration, or an inherited widget.
        self.render_layout_builder(app)
            .schedule_layout_callback(app);
        app.get_mut(self).needs_build = true;
        RenderObjectElement::perform_rebuild(self, app); // Calls widget.updateRenderObject (a no-op in this case).
    }

    fn deactivate(self: Handle<Self>, app: &mut App) {
        RenderObjectElement::deactivate(self, app);
    }

    fn unmount(self: Handle<Self>, app: &mut App) {
        let render_object = self.render_layout_builder(app);
        render_object.set_callback(app, None);
        RenderObjectElement::unmount(self, app);
    }

    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
        RenderObjectElement::update_parent_data(self, app, parent_data_element);
    }

    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        RenderObjectElement::update_slot(self, app, new_slot);
    }

    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        RenderObjectElement::attach_render_object(self, app, new_slot);
    }

    fn detach_render_object(self: Handle<Self>, app: &mut App) {
        RenderObjectElement::detach_render_object(self, app);
    }

    fn insert_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        slot: Option<Slot>,
    ) {
        debug_assert!(slot.is_none());
        let render_object = self.render_layout_builder(app);
        render_object.set_child(app, Some(child.as_box().expect("a box child")));
    }

    fn move_render_object_child(
        self: Handle<Self>,
        _app: &mut App,
        _child: AnyRenderObject,
        _old_slot: Option<Slot>,
        _new_slot: Option<Slot>,
    ) {
        debug_assert!(false, "a layout builder has one child");
    }

    fn remove_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        _slot: Option<Slot>,
    ) {
        let render_object = self.render_layout_builder(app);
        debug_assert!(render_object.child(app).map(|current| current.as_object()) == Some(child));
        render_object.set_child(app, None);
    }
}

/// Generic mixin for `RenderObject`s created by `AbstractLayoutBuilder`s, which run a
/// builder callback during layout (Dart's `RenderAbstractLayoutBuilderMixin` /
/// `RenderConstrainedLayoutBuilder`).
///
/// The callback is `LayoutBuilderElement::rebuild_with_constraints`; it reads the constraints
/// from the render object rather than receiving them.
pub trait RenderAbstractLayoutBuilderMixin: RenderObjectWithLayoutCallbackMixin {
    /// The layout callback, if set.
    fn callback(self: RenderHandle<Self>, app: &App) -> Option<Listener>;

    /// Sets (or clears) the layout callback without scheduling it.
    fn set_callback(self: RenderHandle<Self>, app: &mut App, callback: Option<Listener>);

    /// Change the layout callback and schedule it.
    fn update_callback(self: RenderHandle<Self>, app: &mut App, value: Listener) {
        if self.callback(app).as_ref() == Some(&value) {
            return;
        }
        self.set_callback(app, Some(value));
        self.schedule_layout_callback(app);
    }

    /// The information the builder is given: this box's constraints, with their subclass.
    fn layout_info(self: RenderHandle<Self>, app: &App) -> AnyBoxConstraints {
        self.any_constraints(app)
    }
}

/// Dart's `_RenderLayoutBuilder`: a box that runs its layout callback, then sizes to its
/// child (or fills its constraints without one).
pub struct RenderLayoutBuilder {
    render_object: RenderObjectData,
    render_box: RenderBoxData,
    child: RenderObjectWithChildData<AnyRenderBox>,
    layout_callback: RenderObjectWithLayoutCallbackData,
    callback: Option<Listener>,
}

impl RenderLayoutBuilder {
    /// Creates the render object with no callback and no child.
    pub fn new(app: &mut App) -> RenderHandle<RenderLayoutBuilder> {
        RenderHandle::new_box(
            app,
            RenderLayoutBuilder {
                render_object: RenderObjectData::default(),
                render_box: RenderBoxData::default(),
                child: RenderObjectWithChildData::default(),
                layout_callback: RenderObjectWithLayoutCallbackData::default(),
                callback: None,
            },
        )
    }
}

impl RenderObjectWithChildMixin for RenderLayoutBuilder {
    type ChildType = AnyRenderBox;

    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
        &self.get(app).child
    }

    fn child_data_mut(
        self: RenderHandle<Self>,
        app: &mut App,
    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
        &mut self.get_mut(app).child
    }
}

impl RenderObjectWithLayoutCallbackMixin for RenderLayoutBuilder {
    fn layout_callback_data(
        self: RenderHandle<Self>,
        app: &App,
    ) -> &RenderObjectWithLayoutCallbackData {
        &self.get(app).layout_callback
    }

    fn layout_callback_data_mut(
        self: RenderHandle<Self>,
        app: &mut App,
    ) -> &mut RenderObjectWithLayoutCallbackData {
        &mut self.get_mut(app).layout_callback
    }

    fn layout_callback(self: RenderHandle<Self>, app: &mut App) {
        let callback = self
            .get(app)
            .callback
            .clone()
            .expect("a callback is set before layout");
        callback.call(app);
    }
}

impl RenderAbstractLayoutBuilderMixin for RenderLayoutBuilder {
    fn callback(self: RenderHandle<Self>, app: &App) -> Option<Listener> {
        self.get(app).callback.clone()
    }

    fn set_callback(self: RenderHandle<Self>, app: &mut App, callback: Option<Listener>) {
        self.get_mut(app).callback = callback;
    }
}

impl RenderObject for RenderLayoutBuilder {
    waft_rendering::render_object_accessors!();

    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
        let constraints = self.constraints(app);
        self.run_layout_callback(app);
        if let Some(child) = self.child(app) {
            child.layout(app, constraints, true);
            let size = constraints.constrain(child.size(app));
            self.set_size(app, size);
        } else {
            self.set_size(app, constraints.biggest());
        }
    }

    fn paint(
        self: RenderHandle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
    ) {
        if let Some(child) = self.child(app) {
            context.paint_child(app, child.as_object(), offset);
        }
    }

    fn visit_children(
        self: RenderHandle<Self>,
        app: &App,
        visitor: &mut dyn FnMut(AnyRenderObject),
    ) {
        if let Some(child) = self.child(app) {
            visitor(child.as_object());
        }
    }
}

impl RenderLayoutBuilder {
    fn debug_throw_if_not_checking_intrinsics(self: RenderHandle<Self>) -> bool {
        let _ = self;
        debug_assert!(
            debug_checking_intrinsics(),
            "LayoutBuilder does not support returning intrinsic dimensions.\n\
             Calculating the intrinsic dimensions would require running the layout callback \
             speculatively, which might mutate the live render object tree."
        );
        true
    }
}

impl RenderBox for RenderLayoutBuilder {
    waft_rendering::render_box_accessors!();

    fn compute_min_intrinsic_width(self: RenderHandle<Self>, _app: &mut App, _height: f64) -> f64 {
        debug_assert!(self.debug_throw_if_not_checking_intrinsics());
        0.0
    }

    fn compute_max_intrinsic_width(self: RenderHandle<Self>, _app: &mut App, _height: f64) -> f64 {
        debug_assert!(self.debug_throw_if_not_checking_intrinsics());
        0.0
    }

    fn compute_min_intrinsic_height(self: RenderHandle<Self>, _app: &mut App, _width: f64) -> f64 {
        debug_assert!(self.debug_throw_if_not_checking_intrinsics());
        0.0
    }

    fn compute_max_intrinsic_height(self: RenderHandle<Self>, _app: &mut App, _width: f64) -> f64 {
        debug_assert!(self.debug_throw_if_not_checking_intrinsics());
        0.0
    }

    fn compute_dry_layout(
        self: RenderHandle<Self>,
        _app: &mut App,
        _constraints: BoxConstraints,
    ) -> Size {
        self.debug_cannot_compute_dry_layout(DryLayoutFailure::Reason(
            "Calculating the dry layout would require running the layout callback \
             speculatively, which might mutate the live render object tree.",
        ));
        Size::ZERO
    }

    fn compute_dry_baseline(
        self: RenderHandle<Self>,
        _app: &mut App,
        _constraints: BoxConstraints,
        _baseline: TextBaseline,
    ) -> Option<f64> {
        self.debug_cannot_compute_dry_layout(DryLayoutFailure::Reason(
            "Calculating the dry baseline would require running the layout callback \
             speculatively, which might mutate the live render object tree.",
        ));
        None
    }

    fn hit_test_children(
        self: RenderHandle<Self>,
        app: &mut App,
        result: &mut BoxHitTestResult<'_>,
        position: Offset,
    ) -> bool {
        self.child(app)
            .is_some_and(|child| child.hit_test(app, result, position))
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;
    use waft_foundation::AppCell;

    use waft_embedder::{Size, TextDirection};

    use super::*;
    use crate::framework::IntoWidget;
    use crate::test_harness::Harness;
    use crate::widgets::basic::{Directionality, SizedBox};

    type Seen = Rc<RefCell<Vec<BoxConstraints>>>;

    fn builder(seen: &Seen) -> WidgetRef {
        let seen = Rc::clone(seen);
        LayoutBuilder::new(move |_app, _context, constraints| {
            seen.borrow_mut().push(constraints.constraints());
            SizedBox::square(Some(10.0)).into_widget()
        })
        .into_widget()
    }

    fn sized(width: f64, child: WidgetRef) -> WidgetRef {
        SizedBox::new()
            .width(width)
            .height(50.0)
            .child(child)
            .into_widget()
    }

    /// A `LayoutBuilder` is a widget wherever one is taken, as Dart's `Widget` is: `Focus::new`
    /// takes it without the inherent `into_widget` being called.
    #[test]
    fn a_layout_builder_goes_wherever_a_widget_is_taken() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let seen: Seen = Rc::default();
        let seen_in_builder = Rc::clone(&seen);
        let focused = crate::widgets::focus_scope::Focus::new(LayoutBuilder::new(
            move |_app, _context, constraints| {
                seen_in_builder.borrow_mut().push(constraints.constraints());
                SizedBox::square(Some(10.0)).into_widget()
            },
        ));
        let harness = Harness::mount(&mut app, focused.into_widget());
        harness.pump(&mut app);
        assert_eq!(seen.borrow().len(), 1, "the builder ran under the focus");
    }

    #[test]
    fn the_builder_runs_at_layout_with_the_constraints_and_only_when_they_change() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let seen: Seen = Rc::default();
        let harness = Harness::mount(&mut app, sized(100.0, builder(&seen)));
        harness.pump(&mut app);
        assert_eq!(
            *seen.borrow(),
            vec![BoxConstraints::tight(Size::new(100.0, 50.0))]
        );

        harness.pump(&mut app);
        assert_eq!(seen.borrow().len(), 1);

        harness.set_child(&mut app, sized(80.0, builder(&seen)));
        harness.pump(&mut app);
        assert_eq!(seen.borrow().len(), 2);
        assert_eq!(
            seen.borrow()[1],
            BoxConstraints::tight(Size::new(80.0, 50.0))
        );
    }

    /// A `BoxConstraints` subclass with one field, as material's `_BottomSheetBoxConstraints`.
    #[derive(Debug)]
    struct Inset(f64);

    impl waft_rendering::BoxConstraintsExtension for Inset {
        fn as_any(&self) -> &dyn Any {
            self
        }

        fn eq_extension(&self, other: &dyn waft_rendering::BoxConstraintsExtension) -> bool {
            other
                .as_any()
                .downcast_ref::<Inset>()
                .is_some_and(|other| other.0 == self.0)
        }
    }

    /// Lays out its one child with the same plain constraints and an `Inset` of `self.0`.
    #[derive(Debug)]
    struct InsetDelegate(f64);

    impl waft_rendering::MultiChildLayoutDelegate for InsetDelegate {
        fn perform_layout(
            &self,
            app: &mut App,
            children: &mut waft_rendering::MultiChildLayoutChildren,
            size: Size,
        ) {
            children.layout_child(
                app,
                &child_id(),
                AnyBoxConstraints::with_shared(BoxConstraints::loose(size), Rc::new(Inset(self.0))),
            );
        }

        fn should_relayout(
            &self,
            old_delegate: &dyn waft_rendering::MultiChildLayoutDelegate,
        ) -> bool {
            old_delegate
                .as_any()
                .downcast_ref::<InsetDelegate>()
                .is_none_or(|old_delegate| old_delegate.0 != self.0)
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    fn child_id() -> waft_rendering::ChildLayoutId {
        Rc::new(waft_foundation::ValueKey::new("child"))
    }

    #[test]
    fn the_builder_gets_the_constraints_subclass_and_reruns_when_only_its_fields_change() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let seen = Rc::new(RefCell::new(Vec::new()));
        let layout_builder = {
            let seen = Rc::clone(&seen);
            LayoutBuilder::new(move |_app, _context, constraints| {
                seen.borrow_mut().push((
                    constraints.constraints(),
                    constraints.extension::<Inset>().map(|inset| inset.0),
                ));
                SizedBox::square(Some(10.0)).into_widget()
            })
            .into_widget()
        };
        let layout = |inset: f64| {
            sized(
                100.0,
                crate::widgets::basic::CustomMultiChildLayout::new(Rc::new(InsetDelegate(inset)))
                    .children([crate::widgets::basic::LayoutId::new(
                        child_id(),
                        layout_builder.clone(),
                    )
                    .into_widget()])
                    .into_widget(),
            )
        };
        let loose = BoxConstraints::loose(Size::new(100.0, 50.0));
        let harness = Harness::mount(&mut app, layout(1.0));
        harness.pump(&mut app);
        assert_eq!(*seen.borrow(), vec![(loose, Some(1.0))]);

        harness.set_child(&mut app, layout(1.0));
        harness.pump(&mut app);
        assert_eq!(
            seen.borrow().len(),
            1,
            "equal constraints, the same builder widget"
        );

        harness.set_child(&mut app, layout(2.0));
        harness.pump(&mut app);
        assert_eq!(
            *seen.borrow(),
            vec![(loose, Some(1.0)), (loose, Some(2.0))],
            "only the subclass field changed"
        );
    }

    #[test]
    fn an_inherited_dependency_change_rebuilds_the_builder_during_layout() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let seen = Rc::new(RefCell::new(Vec::new()));
        let dependent = {
            let seen = Rc::clone(&seen);
            LayoutBuilder::new(move |app, context, _constraints| {
                seen.borrow_mut().push(Directionality::of(app, context));
                SizedBox::square(Some(10.0)).into_widget()
            })
            .into_widget()
        };
        let under = |direction: TextDirection, child: WidgetRef| {
            Directionality::new(direction, child).into_widget()
        };
        let harness = Harness::mount(&mut app, under(TextDirection::Ltr, dependent.clone()));
        harness.pump(&mut app);
        harness.set_child(&mut app, under(TextDirection::Rtl, dependent));
        harness.pump(&mut app);
        assert_eq!(*seen.borrow(), vec![TextDirection::Ltr, TextDirection::Rtl]);
    }
}