Skip to main content

waft_widgets/widgets/
table.rs

1//! Flutter counterpart: `widgets/table.dart`.
2
3use std::any::{Any, TypeId};
4use std::collections::{HashMap, HashSet};
5use std::fmt;
6use std::panic::Location;
7use std::rc::Rc;
8
9use waft_embedder::{SemanticsRole, TextBaseline, TextDirection};
10use waft_foundation::{
11    App, DiagnosticPropertiesBuilder, EnumProperty, Handle, IntProperty, Key, LocalKey,
12};
13use waft_painting::DecorationRef;
14use waft_rendering::{
15    AnyRenderBox, AnyRenderObject, ErasedRenderObject, RenderBox, RenderHandle, RenderTable,
16};
17pub use waft_rendering::{
18    FixedColumnWidth, FlexColumnWidth, FractionColumnWidth, IntrinsicColumnWidth, MaxColumnWidth,
19    MinColumnWidth, TableBorder, TableCellParentData, TableCellVerticalAlignment, TableColumnWidth,
20    TableColumnWidthRef,
21};
22
23use crate::framework::{
24    AnyElement, BuildContext, CreationLocation, Element, ElementData, KeyRef, ParentDataWidget,
25    RenderObjectElement, RenderObjectElementData, RenderObjectElementWidget, RenderObjectWidget,
26    Slot, StatelessWidget, Widget, WidgetKind, WidgetRef, downcast_widget,
27};
28use crate::widgets::basic::{Directionality, Semantics};
29use crate::widgets::image::create_local_image_configuration;
30
31/// A horizontal group of cells in a [`Table`].
32///
33/// Every row in a table must have the same number of children.
34///
35/// The alignment of individual cells in a row can be controlled using a [`TableCell`].
36#[derive(Default)]
37pub struct TableRow {
38    /// An identifier for the row.
39    pub key: Option<Rc<dyn LocalKey>>,
40
41    /// A decoration to paint behind this row.
42    ///
43    /// Row decorations fill the horizontal and vertical extent of each row in the table, unlike
44    /// decorations for individual cells, which might not fill either.
45    pub decoration: Option<DecorationRef>,
46
47    /// The widgets that comprise the cells in this row.
48    ///
49    /// Children may be wrapped in [`TableCell`] widgets to provide per-cell configuration to
50    /// the [`Table`], but children are not required to be wrapped in [`TableCell`] widgets.
51    pub children: Vec<WidgetRef>,
52}
53
54impl TableRow {
55    /// Creates a row in a [`Table`]; Dart's named arguments are the setters.
56    pub fn new() -> TableRow {
57        TableRow::default()
58    }
59
60    /// Dart `TableRow(key:)`.
61    pub fn key(mut self, key: Rc<dyn LocalKey>) -> TableRow {
62        self.key = Some(key);
63        self
64    }
65
66    /// Dart `TableRow(decoration:)`.
67    pub fn decoration(mut self, decoration: impl Into<DecorationRef>) -> TableRow {
68        self.decoration = Some(decoration.into());
69        self
70    }
71
72    /// Dart `TableRow(children:)`.
73    pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> TableRow {
74        self.children = children.into_iter().collect();
75        self
76    }
77}
78
79impl fmt::Debug for TableRow {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        f.write_str("TableRow(")?;
82        if let Some(key) = &self.key {
83            write!(f, "{key:?}, ")?;
84        }
85        if let Some(decoration) = &self.decoration {
86            write!(f, "{decoration:?}, ")?;
87        }
88        if self.children.is_empty() {
89            f.write_str("no children")?;
90        } else {
91            write!(f, "{:?}", self.children)?;
92        }
93        f.write_str(")")
94    }
95}
96
97struct TableElementRow {
98    key: Option<Rc<dyn LocalKey>>,
99    children: Vec<AnyElement>,
100}
101
102/// A widget that uses the table layout algorithm for its children.
103///
104/// If you only have one row, the `Row` widget is more appropriate. If you only have one column,
105/// the `SliverList` or `Column` widgets will be more appropriate.
106///
107/// Rows size vertically based on their contents. To control the individual column widths, use
108/// the [`column_widths`](Self::column_widths) property to specify a [`TableColumnWidth`] for
109/// each column. If [`column_widths`](Self::column_widths) is `None`, or there is no entry for a
110/// given column in [`column_widths`](Self::column_widths), the table uses the
111/// [`default_column_width`](Self::default_column_width) instead.
112///
113/// By default, [`default_column_width`](Self::default_column_width) is a [`FlexColumnWidth`].
114/// This [`TableColumnWidth`] divides up the remaining space in the horizontal axis to determine
115/// the column width. If wrapping a [`Table`] in a horizontal `ScrollView`, choose a different
116/// [`TableColumnWidth`], such as [`FixedColumnWidth`].
117///
118/// For more details about the table layout algorithm, see [`RenderTable`]. To control the
119/// alignment of children, see [`TableCell`].
120pub struct Table {
121    pub key: Option<KeyRef>,
122
123    /// The rows of the table.
124    ///
125    /// Every row in a table must have the same number of children.
126    pub children: Vec<TableRow>,
127
128    /// How the horizontal extents of the columns of this table should be determined.
129    ///
130    /// If the map has no entry for a given column, the table uses the
131    /// [`default_column_width`](Self::default_column_width) instead. By default, that uses flex
132    /// sizing to distribute free space equally among the columns.
133    ///
134    /// The [`FixedColumnWidth`] class can be used to specify a specific width in pixels. That
135    /// is the cheapest way to size a table's columns.
136    ///
137    /// The layout performance of the table depends critically on which column sizing
138    /// algorithms are used here. In particular, [`IntrinsicColumnWidth`] is quite expensive
139    /// because it needs to measure each cell in the column to determine the intrinsic size of
140    /// the column.
141    ///
142    /// The keys of this map (column indexes) are zero-based.
143    ///
144    /// If this is set to `None`, then an empty map is assumed.
145    pub column_widths: Option<HashMap<usize, TableColumnWidthRef>>,
146
147    /// How to determine with widths of columns that don't have an explicit sizing algorithm.
148    ///
149    /// Specifically, the [`default_column_width`](Self::default_column_width) is used for
150    /// column `i` if `column_widths[i]` is absent. Defaults to [`FlexColumnWidth`], which will
151    /// divide the remaining horizontal space up evenly between columns of the same type
152    /// [`TableColumnWidth`].
153    ///
154    /// A [`Table`] in a horizontal `ScrollView` must use a [`FixedColumnWidth`], or an
155    /// [`IntrinsicColumnWidth`] as the horizontal space is infinite.
156    pub default_column_width: TableColumnWidthRef,
157
158    /// The direction in which the columns are ordered.
159    ///
160    /// Defaults to the ambient [`Directionality`].
161    pub text_direction: Option<TextDirection>,
162
163    /// The style to use when painting the boundary and interior divisions of the table.
164    pub border: Option<TableBorder>,
165
166    /// How cells that do not explicitly specify a vertical alignment are aligned vertically.
167    ///
168    /// Cells may specify a vertical alignment by wrapping their contents in a [`TableCell`]
169    /// widget.
170    pub default_vertical_alignment: TableCellVerticalAlignment,
171
172    /// The text baseline to use when aligning rows using
173    /// [`TableCellVerticalAlignment::Baseline`].
174    ///
175    /// This must be set if using baseline alignment. There is no default because there is no
176    /// way for the framework to know the correct baseline _a priori_.
177    pub text_baseline: Option<TextBaseline>,
178
179    /// Where this widget was made, in a debug build; see [`Widget::creation_location`].
180    created: Option<CreationLocation>,
181}
182
183impl Default for Table {
184    fn default() -> Table {
185        Table {
186            key: None,
187            children: Vec::new(),
188            column_widths: None,
189            default_column_width: FlexColumnWidth::default_width(),
190            text_direction: None,
191            border: None,
192            default_vertical_alignment: TableCellVerticalAlignment::Top,
193            text_baseline: None, // NO DEFAULT: we don't know what the text's baseline should be
194            created: None,
195        }
196    }
197}
198
199impl Table {
200    /// Creates a table; Dart's named arguments are the setters.
201    pub fn new() -> Table {
202        Table::default()
203    }
204
205    /// Dart `Table(key:)`.
206    pub fn key(mut self, key: KeyRef) -> Table {
207        self.key = Some(key);
208        self
209    }
210
211    /// Dart `Table(children:)`.
212    pub fn children(mut self, children: impl IntoIterator<Item = TableRow>) -> Table {
213        self.children = children.into_iter().collect();
214        self
215    }
216
217    /// Dart `Table(columnWidths:)`.
218    pub fn column_widths(mut self, column_widths: HashMap<usize, TableColumnWidthRef>) -> Table {
219        self.column_widths = Some(column_widths);
220        self
221    }
222
223    /// Dart `Table(defaultColumnWidth:)`.
224    pub fn default_column_width(mut self, default_column_width: TableColumnWidthRef) -> Table {
225        self.default_column_width = default_column_width;
226        self
227    }
228
229    /// Dart `Table(textDirection:)`.
230    pub fn text_direction(mut self, text_direction: TextDirection) -> Table {
231        self.text_direction = Some(text_direction);
232        self
233    }
234
235    /// Dart `Table(border:)`.
236    pub fn border(mut self, border: TableBorder) -> Table {
237        self.border = Some(border);
238        self
239    }
240
241    /// Dart `Table(defaultVerticalAlignment:)`.
242    pub fn default_vertical_alignment(
243        mut self,
244        default_vertical_alignment: TableCellVerticalAlignment,
245    ) -> Table {
246        self.default_vertical_alignment = default_vertical_alignment;
247        self
248    }
249
250    /// Dart `Table(textBaseline:)`.
251    pub fn text_baseline(mut self, text_baseline: TextBaseline) -> Table {
252        self.text_baseline = Some(text_baseline);
253        self
254    }
255
256    /// The tree node: a `Table` is its own tree node, which [`IntoWidget`] converts.
257    pub fn into_widget(self) -> WidgetRef {
258        Rc::new(self)
259    }
260
261    /// Dart's `_rowDecorations` field, as its constructor fills it: each row's decoration when
262    /// any row has one, else `None`.
263    pub fn effective_row_decorations(&self) -> Option<Vec<Option<DecorationRef>>> {
264        if !self.children.iter().any(|row| row.decoration.is_some()) {
265            return None;
266        }
267        Some(
268            self.children
269                .iter()
270                .map(|row| row.decoration.clone())
271                .collect(),
272        )
273    }
274
275    /// The number of columns: the length of the first row.
276    fn column_count(&self) -> usize {
277        self.children.first().map_or(0, |row| row.children.len())
278    }
279
280    /// Dart's constructor asserts: a baseline alignment has a text baseline, and the rows have
281    /// the same number of cells and none is empty. Dart's checks for duplicate keys wait with
282    /// the framework's.
283    fn debug_assert_is_valid(&self) -> bool {
284        debug_assert!(
285            self.default_vertical_alignment != TableCellVerticalAlignment::Baseline
286                || self.text_baseline.is_some(),
287            "textBaseline is required if you specify the defaultVerticalAlignment with \
288             TableCellVerticalAlignment.baseline"
289        );
290        if cfg!(debug_assertions) && !self.children.is_empty() {
291            let cell_count = self.column_count();
292            assert!(
293                self.children
294                    .iter()
295                    .all(|row| row.children.len() == cell_count),
296                "Table contains irregular row lengths.\n\
297                 Every TableRow in a Table must have the same number of children, so that \
298                 every cell is filled. Otherwise, the table will contain holes."
299            );
300            assert!(
301                self.children.iter().all(|row| !row.children.is_empty()),
302                "One or more TableRow have no children.\n\
303                 Every TableRow in a Table must have at least one child, so there is no empty \
304                 row. "
305            );
306        }
307        true
308    }
309}
310
311impl fmt::Debug for Table {
312    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313        f.debug_struct("Table")
314            .field("children", &self.children)
315            .finish_non_exhaustive()
316    }
317}
318
319impl Widget for Table {
320    fn key(&self) -> Option<&KeyRef> {
321        self.key.as_ref()
322    }
323
324    fn creation_location(&self) -> Option<&'static Location<'static>> {
325        self.created.and_then(CreationLocation::location)
326    }
327
328    fn record_creation_location(&mut self, location: CreationLocation) {
329        self.created = Some(location);
330    }
331
332    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
333        TableElement::new(app, this).as_element()
334    }
335
336    fn as_any(&self) -> &dyn Any {
337        self
338    }
339
340    fn widget_type(&self) -> TypeId {
341        TypeId::of::<Table>()
342    }
343
344    fn kind(&self) -> WidgetKind {
345        WidgetKind::Other
346    }
347}
348
349impl RenderObjectWidget for Table {
350    type RenderObject = RenderTable;
351
352    fn key(&self) -> Option<&KeyRef> {
353        self.key.as_ref()
354    }
355
356    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
357        debug_assert!(self.debug_assert_is_valid());
358        let text_direction = self
359            .text_direction
360            .unwrap_or_else(|| Directionality::of(app, context));
361        let render_object = RenderTable::new(app, text_direction);
362        render_object.set_columns(app, self.column_count());
363        render_object.set_rows(app, self.children.len());
364        render_object.set_column_widths(app, self.column_widths.clone());
365        render_object.set_default_column_width(app, Rc::clone(&self.default_column_width));
366        render_object.set_border(app, self.border);
367        render_object.set_row_decorations(app, self.effective_row_decorations());
368        let configuration = create_local_image_configuration(app, context, None);
369        render_object.set_configuration(app, configuration);
370        render_object.set_default_vertical_alignment(app, self.default_vertical_alignment);
371        render_object.set_text_baseline(app, self.text_baseline);
372        render_object.as_object()
373    }
374
375    fn update_render_object(
376        &self,
377        app: &mut App,
378        context: BuildContext,
379        render_object: RenderHandle<RenderTable>,
380    ) {
381        debug_assert!(self.debug_assert_is_valid());
382        debug_assert_eq!(render_object.columns(app), self.column_count());
383        debug_assert_eq!(render_object.rows(app), self.children.len());
384        render_object.set_column_widths(app, self.column_widths.clone());
385        render_object.set_default_column_width(app, Rc::clone(&self.default_column_width));
386        let text_direction = self
387            .text_direction
388            .unwrap_or_else(|| Directionality::of(app, context));
389        render_object.set_text_direction(app, text_direction);
390        render_object.set_border(app, self.border);
391        render_object.set_row_decorations(app, self.effective_row_decorations());
392        let configuration = create_local_image_configuration(app, context, None);
393        render_object.set_configuration(app, configuration);
394        render_object.set_default_vertical_alignment(app, self.default_vertical_alignment);
395        render_object.set_text_baseline(app, self.text_baseline);
396    }
397}
398
399/// Dart's `_TableSlot`: the cell a child of a [`Table`] fills.
400#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
401struct TableSlot {
402    column: usize,
403    row: usize,
404}
405
406impl TableSlot {
407    /// Dart's `_TableSlot.debugFillProperties`; nothing prints a slot, which the element keeps
408    /// only for identity.
409    #[allow(dead_code)]
410    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
411        properties.add(IntProperty::<usize>::new("x", Some(self.column)));
412        properties.add(IntProperty::<usize>::new("y", Some(self.row)));
413    }
414}
415
416/// Dart's `_TableElement`.
417struct TableElement {
418    element: ElementData,
419    render_object_element: RenderObjectElementData,
420    children: Vec<TableElementRow>,
421    doing_mount_or_update: bool,
422    forgotten_children: HashSet<AnyElement>,
423    /// One slot object per cell: a [`Slot::Custom`] compares by identity, and Dart's
424    /// `_TableSlot` compares by column and row, so each cell keeps the same object.
425    slots: HashMap<TableSlot, Rc<dyn Any>>,
426}
427
428impl TableElement {
429    fn new(app: &mut App, widget: WidgetRef) -> Handle<TableElement> {
430        debug_assert!(downcast_widget::<Table>(&*widget).is_some());
431        app.create(TableElement {
432            element: ElementData::new(widget),
433            render_object_element: RenderObjectElementData::default(),
434            children: Vec::new(),
435            doing_mount_or_update: false,
436            forgotten_children: HashSet::new(),
437            slots: HashMap::new(),
438        })
439        .into_tree_node(app)
440    }
441
442    /// Dart's `_TableSlot(column, row)` as an element slot.
443    fn slot(self: Handle<Self>, app: &mut App, column: usize, row: usize) -> Slot {
444        let slot = app
445            .get_mut(self)
446            .slots
447            .entry(TableSlot { column, row })
448            .or_insert_with(|| Rc::new(TableSlot { column, row }));
449        Slot::Custom(Rc::clone(slot))
450    }
451
452    /// Dart's `_TableSlot slot` parameter type.
453    fn table_slot(slot: Option<&Slot>) -> TableSlot {
454        match slot {
455            Some(Slot::Custom(slot)) => *slot
456                .downcast_ref::<TableSlot>()
457                .expect("a table gives its children table slots"),
458            _ => unreachable!("a table gives its children table slots"),
459        }
460    }
461
462    fn update_render_object_children(self: Handle<Self>, app: &mut App) {
463        let this = app.get(self);
464        let columns = this.children.first().map_or(0, |row| row.children.len());
465        let cells: Vec<AnyElement> = this
466            .children
467            .iter()
468            .flat_map(|row| row.children.iter().copied())
469            .collect();
470        let cells = cells
471            .into_iter()
472            .map(|child| {
473                Some(AnyRenderBox::from_object(
474                    child
475                        .render_object(app)
476                        .expect("a table cell has a render object"),
477                ))
478            })
479            .collect();
480        let render_object = self.typed_render_object(app);
481        render_object.set_flat_children(app, columns, cells);
482    }
483
484    fn is_forgotten(self: Handle<Self>, app: &App, child: AnyElement) -> bool {
485        app.get(self).forgotten_children.contains(&child)
486    }
487}
488
489impl RenderObjectElementWidget for TableElement {
490    type Widget = Table;
491
492    fn widget_of(widget: &WidgetRef) -> &Table {
493        downcast_widget::<Table>(&**widget).expect("a TableElement holds its Table")
494    }
495}
496
497impl RenderObjectElement for TableElement {
498    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
499        &app.get(self).render_object_element
500    }
501
502    fn render_object_element_data_mut(
503        self: Handle<Self>,
504        app: &mut App,
505    ) -> &mut RenderObjectElementData {
506        &mut app.get_mut(self).render_object_element
507    }
508}
509
510impl Element for TableElement {
511    crate::element_accessors!();
512
513    const IS_RENDER_OBJECT_ELEMENT: bool = true;
514
515    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
516        self.render_object_element_data(app).render_object()
517    }
518
519    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
520        None
521    }
522
523    fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
524        self.render_object_element_data(app).debug_doing_build()
525    }
526
527    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
528        RenderObjectElement::perform_rebuild(self, app);
529    }
530
531    fn deactivate(self: Handle<Self>, app: &mut App) {
532        RenderObjectElement::deactivate(self, app);
533    }
534
535    fn unmount(self: Handle<Self>, app: &mut App) {
536        RenderObjectElement::unmount(self, app);
537    }
538
539    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
540        RenderObjectElement::update_parent_data(self, app, parent_data_element);
541    }
542
543    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
544        RenderObjectElement::update_slot(self, app, new_slot);
545    }
546
547    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
548        RenderObjectElement::attach_render_object(self, app, new_slot);
549    }
550
551    fn detach_render_object(self: Handle<Self>, app: &mut App) {
552        RenderObjectElement::detach_render_object(self, app);
553    }
554
555    fn mount(
556        self: Handle<Self>,
557        app: &mut App,
558        parent: Option<AnyElement>,
559        new_slot: Option<Slot>,
560    ) {
561        debug_assert!(!app.get(self).doing_mount_or_update);
562        app.get_mut(self).doing_mount_or_update = true;
563        RenderObjectElement::mount(self, app, parent, new_slot);
564        let widget = self.as_element().widget(app).clone();
565        let table = Self::widget_of(&widget);
566        let mut children = Vec::with_capacity(table.children.len());
567        for (row_index, row) in table.children.iter().enumerate() {
568            let mut row_children = Vec::with_capacity(row.children.len());
569            for (column_index, child) in row.children.iter().enumerate() {
570                let slot = self.slot(app, column_index, row_index);
571                row_children.push(
572                    self.as_element()
573                        .inflate_widget(app, child.clone(), Some(slot)),
574                );
575            }
576            children.push(TableElementRow {
577                key: row.key.clone(),
578                children: row_children,
579            });
580        }
581        app.get_mut(self).children = children;
582        self.update_render_object_children(app);
583        debug_assert!(app.get(self).doing_mount_or_update);
584        app.get_mut(self).doing_mount_or_update = false;
585    }
586
587    fn insert_render_object_child(
588        self: Handle<Self>,
589        app: &mut App,
590        child: AnyRenderObject,
591        slot: Option<Slot>,
592    ) {
593        let render_object = self.typed_render_object(app);
594        render_object.as_object().setup_parent_data(app, child);
595        // Once [mount]/[update] are done, the children are getting set all at once
596        // in [update_render_object_children].
597        if !app.get(self).doing_mount_or_update {
598            let slot = Self::table_slot(slot.as_ref());
599            render_object.set_child(
600                app,
601                slot.column,
602                slot.row,
603                Some(AnyRenderBox::from_object(child)),
604            );
605        }
606    }
607
608    fn move_render_object_child(
609        self: Handle<Self>,
610        app: &mut App,
611        _child: AnyRenderObject,
612        _old_slot: Option<Slot>,
613        _new_slot: Option<Slot>,
614    ) {
615        debug_assert!(app.get(self).doing_mount_or_update);
616        // Child gets moved at the end of [update] in [update_render_object_children].
617    }
618
619    fn remove_render_object_child(
620        self: Handle<Self>,
621        app: &mut App,
622        _child: AnyRenderObject,
623        slot: Option<Slot>,
624    ) {
625        let slot = Self::table_slot(slot.as_ref());
626        self.typed_render_object(app)
627            .set_child(app, slot.column, slot.row, None);
628    }
629
630    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
631        debug_assert!(!app.get(self).doing_mount_or_update);
632        app.get_mut(self).doing_mount_or_update = true;
633        let mut old_keyed_rows: Vec<(Rc<dyn LocalKey>, Vec<AnyElement>)> = Vec::new();
634        let mut old_unkeyed: Vec<Vec<AnyElement>> = Vec::new();
635        for row in &app.get(self).children {
636            match &row.key {
637                Some(key) => old_keyed_rows.push((Rc::clone(key), row.children.clone())),
638                None => old_unkeyed.push(row.children.clone()),
639            }
640        }
641        let mut old_unkeyed_rows = old_unkeyed.iter();
642        let mut new_children = Vec::new();
643        let mut taken: HashSet<usize> = HashSet::new();
644        let is_forgotten = |app: &App, child: AnyElement| self.is_forgotten(app, child);
645        let table = Self::widget_of(&new_widget);
646        for (row_index, row) in table.children.iter().enumerate() {
647            let keyed = row.key.as_ref().and_then(|key| {
648                old_keyed_rows
649                    .iter()
650                    .position(|(old_key, _)| (**old_key).eq_key(&**key as &dyn Key))
651            });
652            let old_children = if let Some(index) = keyed {
653                taken.insert(index);
654                old_keyed_rows[index].1.clone()
655            } else if row.key.is_none()
656                && let Some(old_row) = old_unkeyed_rows.next()
657            {
658                old_row.clone()
659            } else {
660                Vec::new()
661            };
662            let slots: Vec<Option<Slot>> = (0..row.children.len())
663                .map(|column_index| Some(self.slot(app, column_index, row_index)))
664                .collect();
665            let children = self.as_element().update_children(
666                app,
667                &old_children,
668                &row.children,
669                Some(&is_forgotten),
670                Some(&slots),
671            );
672            new_children.push(TableElementRow {
673                key: row.key.clone(),
674                children,
675            });
676        }
677        for old_row in old_unkeyed_rows {
678            self.as_element()
679                .update_children(app, old_row, &[], Some(&is_forgotten), None);
680        }
681        for (index, (_, old_children)) in old_keyed_rows.iter().enumerate() {
682            if !taken.contains(&index) {
683                self.as_element().update_children(
684                    app,
685                    old_children,
686                    &[],
687                    Some(&is_forgotten),
688                    None,
689                );
690            }
691        }
692
693        app.get_mut(self).children = new_children;
694        self.update_render_object_children(app);
695        app.get_mut(self).forgotten_children.clear();
696        RenderObjectElement::update(self, app, new_widget);
697        debug_assert!(app.get(self).doing_mount_or_update);
698        app.get_mut(self).doing_mount_or_update = false;
699    }
700
701    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
702        let this = app.get(self);
703        for child in this.children.iter().flat_map(|row| &row.children) {
704            if !this.forgotten_children.contains(child) {
705                visitor(*child);
706            }
707        }
708    }
709
710    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
711        app.get_mut(self).forgotten_children.insert(child);
712    }
713}
714
715/// A widget that controls how a child of a [`Table`] is aligned.
716///
717/// A [`TableCell`] widget must be a descendant of a [`Table`], and the path from the
718/// [`TableCell`] widget to its enclosing [`Table`] must contain only [`TableRow`]s,
719/// [`StatelessWidget`]s, or `StatefulWidget`s (not other kinds of widgets, like
720/// [`RenderObjectWidget`]s).
721///
722/// To create an empty [`TableCell`], provide a `SizedBox::shrink` as the
723/// [`child`](Self::child).
724#[derive(Debug)]
725pub struct TableCell {
726    pub key: Option<KeyRef>,
727
728    /// How this cell is aligned vertically.
729    pub vertical_alignment: Option<TableCellVerticalAlignment>,
730
731    /// The child of this cell.
732    pub child: WidgetRef,
733}
734
735impl TableCell {
736    /// Creates a widget that controls how a child of a [`Table`] is aligned; Dart's optional
737    /// named arguments are the setters.
738    #[cfg_attr(debug_assertions, track_caller)]
739    pub fn new<K>(child: impl crate::framework::IntoWidget<K>) -> TableCell {
740        TableCell {
741            key: None,
742            vertical_alignment: None,
743            child: child.into_widget(),
744        }
745    }
746
747    /// Dart `TableCell(key:)`.
748    pub fn key(mut self, key: KeyRef) -> TableCell {
749        self.key = Some(key);
750        self
751    }
752
753    /// Dart `TableCell(verticalAlignment:)`.
754    pub fn vertical_alignment(
755        mut self,
756        vertical_alignment: TableCellVerticalAlignment,
757    ) -> TableCell {
758        self.vertical_alignment = Some(vertical_alignment);
759        self
760    }
761}
762
763impl StatelessWidget for TableCell {
764    fn key(&self) -> Option<&KeyRef> {
765        self.key.as_ref()
766    }
767
768    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
769        use crate::framework::IntoWidget;
770        TableCellParentDataWidget {
771            vertical_alignment: self.vertical_alignment,
772            child: Semantics::new()
773                .role(SemanticsRole::Cell)
774                .child(self.child.clone())
775                .into_widget(),
776        }
777        .into_widget()
778    }
779}
780
781/// Dart's `_TableCell`: writes a cell's vertical alignment into its parent data.
782#[derive(Debug)]
783struct TableCellParentDataWidget {
784    vertical_alignment: Option<TableCellVerticalAlignment>,
785    child: WidgetRef,
786}
787
788impl ParentDataWidget for TableCellParentDataWidget {
789    type ParentData = TableCellParentData;
790
791    fn child(&self) -> &WidgetRef {
792        &self.child
793    }
794
795    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
796        properties.add(EnumProperty::<TableCellVerticalAlignment>::new(
797            "verticalAlignment",
798            self.vertical_alignment,
799        ));
800    }
801
802    fn apply_parent_data(&self, app: &mut App, render_object: AnyRenderObject) {
803        let parent_data = render_object.parent_data_of_mut::<TableCellParentData>(app);
804        if parent_data.vertical_alignment != self.vertical_alignment {
805            parent_data.vertical_alignment = self.vertical_alignment;
806            if let Some(parent) = render_object.parent(app) {
807                parent.mark_needs_layout(app);
808            }
809        }
810    }
811}
812
813#[cfg(test)]
814mod tests {
815    use waft_embedder::{Offset, Size};
816    use waft_foundation::{AppCell, ValueKey};
817    use waft_painting::PaintingBinding;
818    use waft_rendering::RenderParagraph;
819
820    use super::*;
821    use crate::framework::IntoWidget;
822    use crate::test_harness::Harness;
823    use crate::widgets::basic::{Center, SizedBox};
824    use crate::widgets::text::Text;
825
826    /// What the shell does at start-up: the app-wide fonts, here the OS fonts.
827    fn install_fonts(app: &mut App) {
828        let binding = PaintingBinding::instance(app);
829        if !binding.has_fonts(app) {
830            binding.install_fonts(app, |fonts| {
831                fonts.add_source(valo_system_fonts::SystemFonts::load());
832            });
833        }
834    }
835
836    fn directional(text_direction: TextDirection, child: WidgetRef) -> WidgetRef {
837        Directionality::new(text_direction, child).into_widget()
838    }
839
840    fn mount(app: &mut App, child: WidgetRef) -> Harness {
841        install_fonts(app);
842        let harness = Harness::mount(app, child);
843        harness.pump(app);
844        harness
845    }
846
847    fn update(app: &mut App, harness: &Harness, child: WidgetRef) {
848        harness.set_child(app, child);
849        harness.pump(app);
850    }
851
852    /// The first `RenderTable` below `node`, depth first.
853    fn find_table(app: &App, node: AnyRenderObject) -> Option<RenderHandle<RenderTable>> {
854        if let Some(table) = node.downcast::<RenderTable>(app) {
855            return Some(table);
856        }
857        let mut children = Vec::new();
858        node.visit_children(app, &mut |child| children.push(child));
859        children
860            .into_iter()
861            .find_map(|child| find_table(app, child))
862    }
863
864    fn table_under(app: &App, harness: &Harness) -> RenderHandle<RenderTable> {
865        find_table(app, harness.render_root(app).as_object()).expect("a RenderTable")
866    }
867
868    fn text_row(texts: &[&str]) -> TableRow {
869        TableRow::new().children(texts.iter().map(|text| Text::new(*text).into_widget()))
870    }
871
872    /// The cell at column `x` of row `y`.
873    fn cell(app: &App, table: RenderHandle<RenderTable>, x: usize, y: usize) -> AnyRenderBox {
874        table.row(app, y)[x]
875    }
876
877    /// `table_test.dart`: "Table widget - empty".
878    #[test]
879    fn an_empty_table_mounts() {
880        let cell = AppCell::new();
881        let mut app = cell.borrow_mut();
882        let harness = mount(
883            &mut app,
884            directional(TextDirection::Ltr, Table::new().into_widget()),
885        );
886        assert_eq!(table_under(&app, &harness).rows(&app), 0);
887    }
888
889    /// `table_test.dart`: "Table widget - control test": flexible columns share the width
890    /// equally whatever the text, in either direction.
891    #[test]
892    fn flexible_columns_are_equal_in_both_directions() {
893        for text_direction in [TextDirection::Ltr, TextDirection::Rtl] {
894            let app_cell = AppCell::new();
895            let mut app = app_cell.borrow_mut();
896            let table = Table::new().children([
897                text_row(&["AAAAAA", "B", "C"]),
898                text_row(&["D", "EEE", "F"]),
899                text_row(&["G", "H", "III"]),
900            ]);
901            let harness = mount(&mut app, directional(text_direction, table.into_widget()));
902            let table = table_under(&app, &harness);
903            let a = cell(&app, table, 0, 0).size(&app);
904            for (x, y) in [(0, 1), (0, 2), (1, 0)] {
905                assert_eq!(cell(&app, table, x, y).size(&app), a, "{text_direction:?}");
906            }
907        }
908    }
909
910    fn fixed(width: f64) -> TableColumnWidthRef {
911        Rc::new(FixedColumnWidth::new(width))
912    }
913
914    /// `table_test.dart`: "Table widget - column offset (LTR)" and "(RTL)".
915    #[test]
916    fn fixed_columns_are_placed_from_the_start_edge() {
917        for text_direction in [TextDirection::Ltr, TextDirection::Rtl] {
918            let app_cell = AppCell::new();
919            let mut app = app_cell.borrow_mut();
920            let widths = HashMap::from([(0, fixed(50.0)), (1, fixed(60.0)), (2, fixed(75.0))]);
921            let table = Table::new()
922                .column_widths(widths)
923                .default_column_width(fixed(333.0))
924                .children([
925                    text_row(&["A1", "B1", "C1"]),
926                    text_row(&["A2", "B2", "C2"]),
927                    text_row(&["A3", "B3", "C3"]),
928                ]);
929            let harness = mount(
930                &mut app,
931                directional(
932                    text_direction,
933                    Center::new().child(table.into_widget()).into_widget(),
934                ),
935            );
936            let table = table_under(&app, &harness);
937            assert_eq!(table.size(&app).width(), 185.0);
938            let left = |app: &App, x: usize, y: usize| {
939                cell(app, table, x, y).box_parent_data(app).offset.dx()
940            };
941            for y in 0..3 {
942                for (x, width) in [(0, 50.0), (1, 60.0), (2, 75.0)] {
943                    assert_eq!(cell(&app, table, x, y).size(&app).width(), width);
944                }
945                let expected = match text_direction {
946                    TextDirection::Ltr => [0.0, 50.0, 110.0],
947                    TextDirection::Rtl => [135.0, 75.0, 0.0],
948                };
949                assert_eq!(
950                    [left(&app, 0, y), left(&app, 1, y), left(&app, 2, y)],
951                    expected,
952                    "{text_direction:?}"
953                );
954            }
955        }
956    }
957
958    /// `table_test.dart`: "Table widget - changing table dimensions": the first cell keeps its
959    /// render object, and a cell that moved to another place gets a new one.
960    #[test]
961    fn a_reshaped_table_keeps_the_cells_that_stay() {
962        let app_cell = AppCell::new();
963        let mut app = app_cell.borrow_mut();
964        let three_by_three = Table::new().children([
965            text_row(&["A", "B", "C"]),
966            text_row(&["D", "E", "F"]),
967            text_row(&["G", "H", "I"]),
968        ]);
969        let harness = mount(
970            &mut app,
971            directional(TextDirection::Ltr, three_by_three.into_widget()),
972        );
973        let table = table_under(&app, &harness);
974        let a1 = cell(&app, table, 0, 0);
975        let g1 = cell(&app, table, 0, 2);
976
977        let four_by_two = Table::new().children([
978            text_row(&["a", "b", "c", "d"]),
979            text_row(&["e", "f", "g", "h"]),
980        ]);
981        update(
982            &mut app,
983            &harness,
984            directional(TextDirection::Ltr, four_by_two.into_widget()),
985        );
986        assert_eq!((table.columns(&app), table.rows(&app)), (4, 2));
987        assert_eq!(cell(&app, table, 0, 0), a1);
988        assert_ne!(cell(&app, table, 2, 1), g1);
989        drop(app);
990        app_cell.checkpoint();
991        let app = app_cell.borrow();
992        assert!(
993            !app.contains(g1.as_object().id()),
994            "the old cell left the tree"
995        );
996    }
997
998    /// `table_test.dart`: "Table widget - intrinsic sizing test": intrinsic columns are as wide
999    /// as their widest text, and the rows as tall as their text.
1000    #[test]
1001    fn intrinsic_columns_fit_their_text() {
1002        let app_cell = AppCell::new();
1003        let mut app = app_cell.borrow_mut();
1004        let table = Table::new()
1005            .default_column_width(Rc::new(IntrinsicColumnWidth::new(None)))
1006            .children([
1007                text_row(&["AAA", "B", "C"]),
1008                text_row(&["D", "E", "FFFFFF"]),
1009                text_row(&["G", "H", "III"]),
1010            ]);
1011        let harness = mount(
1012            &mut app,
1013            directional(TextDirection::Ltr, table.into_widget()),
1014        );
1015        let table = table_under(&app, &harness);
1016        let a = cell(&app, table, 0, 0).size(&app);
1017        assert_eq!(cell(&app, table, 0, 1).size(&app), a);
1018        assert_eq!(cell(&app, table, 0, 2).size(&app), a);
1019        let b = cell(&app, table, 1, 0).size(&app);
1020        assert!(a.width() > b.width());
1021        assert_eq!(a.height(), b.height());
1022        let widest = cell(&app, table, 2, 1)
1023            .as_object()
1024            .downcast::<RenderParagraph>(&app)
1025            .expect("a paragraph")
1026            .text_size(&app)
1027            .width();
1028        assert_eq!(cell(&app, table, 2, 0).size(&app).width(), widest);
1029    }
1030
1031    /// `table_test.dart`: "Table widget - moving test" and "Table widget - keyed rows": a keyed
1032    /// row keeps its cells when it moves, and the cells of a removed keyed row leave.
1033    #[test]
1034    fn a_keyed_row_keeps_its_cells_when_it_moves() {
1035        let app_cell = AppCell::new();
1036        let mut app = app_cell.borrow_mut();
1037        let keyed = || {
1038            TableRow::new()
1039                .key(Rc::new(ValueKey::new(1)))
1040                .children([SizedBox::new().height(10.0).into_widget()])
1041        };
1042        let plain = || TableRow::new().children([SizedBox::new().height(20.0).into_widget()]);
1043        let harness = mount(
1044            &mut app,
1045            directional(
1046                TextDirection::Ltr,
1047                Table::new().children([keyed(), plain()]).into_widget(),
1048            ),
1049        );
1050        let table = table_under(&app, &harness);
1051        let keyed_cell = cell(&app, table, 0, 0);
1052
1053        update(
1054            &mut app,
1055            &harness,
1056            directional(
1057                TextDirection::Ltr,
1058                Table::new().children([plain(), keyed()]).into_widget(),
1059            ),
1060        );
1061        assert_eq!(cell(&app, table, 0, 1), keyed_cell);
1062        assert_eq!(cell(&app, table, 0, 1).size(&app).height(), 10.0);
1063
1064        update(
1065            &mut app,
1066            &harness,
1067            directional(
1068                TextDirection::Ltr,
1069                Table::new().children([plain()]).into_widget(),
1070            ),
1071        );
1072        assert_eq!(table.rows(&app), 1);
1073        drop(app);
1074        app_cell.checkpoint();
1075        let app = app_cell.borrow();
1076        assert!(
1077            !app.contains(keyed_cell.as_object().id()),
1078            "the keyed row's cell left the tree"
1079        );
1080    }
1081
1082    /// A `TableCell` places its child in the row by its own alignment, over the table's
1083    /// default.
1084    #[test]
1085    fn a_table_cell_aligns_its_child_in_the_row() {
1086        let app_cell = AppCell::new();
1087        let mut app = app_cell.borrow_mut();
1088        let sized = |height: f64| SizedBox::new().height(height).into_widget();
1089        let table = Table::new().children([TableRow::new().children([
1090            sized(100.0),
1091            TableCell::new(sized(20.0))
1092                .vertical_alignment(TableCellVerticalAlignment::Middle)
1093                .into_widget(),
1094            TableCell::new(sized(20.0))
1095                .vertical_alignment(TableCellVerticalAlignment::Bottom)
1096                .into_widget(),
1097            TableCell::new(sized(20.0)).into_widget(),
1098            TableCell::new(sized(20.0))
1099                .vertical_alignment(TableCellVerticalAlignment::Fill)
1100                .into_widget(),
1101        ])]);
1102        let harness = mount(
1103            &mut app,
1104            directional(TextDirection::Ltr, table.into_widget()),
1105        );
1106        let table = table_under(&app, &harness);
1107        let top = |x: usize| cell(&app, table, x, 0).box_parent_data(&app).offset.dy();
1108        assert_eq!([top(1), top(2), top(3), top(4)], [40.0, 80.0, 0.0, 0.0]);
1109        assert_eq!(cell(&app, table, 4, 0).size(&app).height(), 100.0);
1110        let parent_data = cell(&app, table, 1, 0)
1111            .as_object()
1112            .parent_data_of::<TableCellParentData>(&app);
1113        assert_eq!(
1114            parent_data.vertical_alignment,
1115            Some(TableCellVerticalAlignment::Middle)
1116        );
1117    }
1118
1119    /// `table_test.dart`: "Set defaultVerticalAlignment to intrinsic height and check their
1120    /// heights".
1121    #[test]
1122    fn intrinsic_height_rows_stretch_their_cells_to_the_tallest() {
1123        let app_cell = AppCell::new();
1124        let mut app = app_cell.borrow_mut();
1125        let sized = |height: f64, text: &str| {
1126            SizedBox::new()
1127                .height(height)
1128                .child(Text::new(text))
1129                .into_widget()
1130        };
1131        let table = Table::new()
1132            .default_vertical_alignment(TableCellVerticalAlignment::IntrinsicHeight)
1133            .children([
1134                TableRow::new().children([sized(100.0, "A"), sized(200.0, "B")]),
1135                TableRow::new().children([sized(200.0, "C"), sized(300.0, "D")]),
1136            ]);
1137        let harness = mount(
1138            &mut app,
1139            directional(
1140                TextDirection::Ltr,
1141                crate::widgets::basic::UnconstrainedBox::new()
1142                    .child(SizedBox::new().width(200.0).child(table.into_widget()))
1143                    .into_widget(),
1144            ),
1145        );
1146        let table = table_under(&app, &harness);
1147        let height = |x: usize, y: usize| cell(&app, table, x, y).size(&app).height();
1148        assert_eq!(height(0, 0), height(1, 0));
1149        assert_eq!(height(0, 1), height(1, 1));
1150        assert!(height(1, 1) > height(0, 0));
1151        assert_eq!(table.size(&app), Size::new(200.0, 500.0));
1152    }
1153
1154    /// A row decoration is given to the render table only when some row has one.
1155    #[test]
1156    fn row_decorations_reach_the_render_table() {
1157        let app_cell = AppCell::new();
1158        let mut app = app_cell.borrow_mut();
1159        let plain = Table::new().children([text_row(&["a"]), text_row(&["b"])]);
1160        assert!(plain.effective_row_decorations().is_none());
1161        let decorated = Table::new().children([
1162            text_row(&["a"]),
1163            text_row(&["b"]).decoration(waft_painting::BoxDecoration::new()),
1164        ]);
1165        let harness = mount(
1166            &mut app,
1167            directional(TextDirection::Ltr, decorated.into_widget()),
1168        );
1169        let table = table_under(&app, &harness);
1170        let decorations = table.row_decorations(&app);
1171        assert_eq!(decorations.len(), 2);
1172        assert!(decorations[0].is_none() && decorations[1].is_some());
1173        assert_eq!(table.get_row_box(&app, 0).top, 0.0);
1174        assert_eq!(
1175            cell(&app, table, 0, 1).box_parent_data(&app).offset,
1176            Offset::new(0.0, table.get_row_box(&app, 1).top)
1177        );
1178    }
1179
1180    /// `table_test.dart`: "Table widget requires all TableRows to have same number of children".
1181    #[test]
1182    #[should_panic(expected = "Table contains irregular row lengths.")]
1183    fn rows_of_different_lengths_are_refused() {
1184        let app_cell = AppCell::new();
1185        let mut app = app_cell.borrow_mut();
1186        let table = Table::new().children([text_row(&["a", "b"]), text_row(&["c"])]);
1187        mount(
1188            &mut app,
1189            directional(TextDirection::Ltr, table.into_widget()),
1190        );
1191    }
1192}