Skip to main content

egui_pop_core/ui/
layout.rs

1//! Rows, grids and flows: [`UiPop::row`] and
2//! [`UiPop::grid`] place cells on tracks, align them on
3//! their text's baseline, and leave gaps of [`Space`] only;
4//! [`UiPop::flow`] places whole cells left to right and wraps them.
5//!
6//! A track is sized by its content ([`Track::CONTENT`]), by a share of what
7//! is left ([`Track::fr`]), by a share of the container ([`Track::percent`])
8//! or in lines of body text ([`Track::em`]), each between an optional
9//! [`Length`] minimum and maximum.
10//!
11//! ```
12//! use egui_pop_core::theme::{self, ThemeSpec};
13//! use egui_pop_core::ui::{Align, Flow, Grid, Length, Row, Space, Track, UiPop};
14//!
15//! let ctx = egui::Context::default();
16//! theme::install(&ctx, &ThemeSpec::new("pop-dark"));
17//! let mut name = String::from("IMG_0001");
18//! let mut out = ctx.run_ui(Default::default(), |ui| {
19//!     // A line: a title, a field taking what is left (between 8 and 24
20//!     // em), a button sized to its content, all on one baseline.
21//!     let field = Track::fr(1.0).min(Length::Em(8.0)).max(Length::Em(24.0));
22//!     ui.row(Row::new([Track::CONTENT, field, Track::CONTENT]), |r| {
23//!         r.cell(|ui| ui.section_title("Name"));
24//!         r.cell(|ui| ui.text_edit_singleline(&mut name));
25//!         r.cell(|ui| ui.button("Rename"));
26//!     });
27//!     // Headers as wide as the widest, values take the rest; one column
28//!     // when narrower than 30 em.
29//!     let grid = Grid::new("details", [Track::CONTENT, Track::fr(1.0)])
30//!         .fold_below(Length::Em(30.0));
31//!     ui.grid(grid, |g| {
32//!         g.header("Kind");
33//!         g.cell(|ui| ui.label("Raw image"));
34//!         g.header("Size");
35//!         g.cell(|ui| ui.label("24 MB"));
36//!     });
37//!     // A button bar: buttons as wide as the widest, at the end.
38//!     let bar = Row::new([Track::CONTENT; 2]).justify(Align::End).equal_widths();
39//!     ui.row(bar, |r| {
40//!         r.cell(|ui| ui.button("Cancel"));
41//!         r.cell(|ui| ui.button("OK"));
42//!     });
43//!     // Actions that wrap whole when narrow, never inside a button.
44//!     ui.flow(Flow::new(), |f| {
45//!         f.cell(|ui| ui.button("Save as template"));
46//!         f.cell(|ui| ui.add_enabled_ui(false, |ui| ui.button("Delete")).inner);
47//!     });
48//!     ui.space_role(Space::Group);
49//! });
50//! out.textures_delta.clear();
51//! ```
52//!
53//! How it measures: egui places each widget once, so cells are placed from
54//! the sizes and baselines they had on the previous pass (kept in the
55//! context's temporary memory under the layout's id). When they change, the
56//! layout asks egui to discard the pass and run another, as egui's own
57//! `Grid` does; at rest nothing is measured twice. A cell's baseline is the
58//! first baseline of the text it paints; a cell painting no text is taken
59//! as a single-line widget with body text centred in it, as egui draws its
60//! own.
61
62use std::hash::{Hash, Hasher};
63
64use egui::{
65    Align as EguiAlign, AsIdSalt, IdSalt, InnerResponse, Layout, Pos2, Rect, Response, Sense,
66    Shape, TextStyle, TextWrapMode, Ui, UiBuilder, Vec2, pos2, vec2,
67};
68
69use super::{Space, TextRole, UiPop};
70use crate::theme::Tokens;
71
72/// A length for a track's size, minimum or maximum, never in points.
73#[derive(Clone, Copy, Debug, PartialEq)]
74pub enum Length {
75    /// Lines of body text: `n` times the body text role's size
76    /// (`text-role.body.size`), so it follows the text scale.
77    Em(f32),
78    /// A share of the container's width, `0.0..=100.0`.
79    Percent(f32),
80}
81
82impl Length {
83    /// In points, for a body text size `em` and a container `width` wide.
84    pub fn points(self, em: f32, width: f32) -> f32 {
85        match self {
86            Length::Em(n) => n * em,
87            Length::Percent(p) => p / 100.0 * width,
88        }
89    }
90}
91
92#[derive(Clone, Copy, Debug, PartialEq)]
93enum Size {
94    Content,
95    Fr(f32),
96    Fixed(Length),
97}
98
99/// The width of a column of a [`Row`] or a [`Grid`].
100#[derive(Clone, Copy, Debug, PartialEq)]
101pub struct Track {
102    size: Size,
103    min: Option<Length>,
104    max: Option<Length>,
105}
106
107impl Track {
108    /// As wide as its content (the widest cell of the column in a grid), as
109    /// measured on the previous pass.
110    pub const CONTENT: Track = Track {
111        size: Size::Content,
112        min: None,
113        max: None,
114    };
115
116    /// A weight of what the other tracks and the gaps leave: two `fr(1.0)`
117    /// share it equally.
118    pub fn fr(weight: f32) -> Self {
119        Self::of(Size::Fr(weight.max(0.0)))
120    }
121
122    /// `n` lines of body text ([`Length::Em`]).
123    pub fn em(n: f32) -> Self {
124        Self::of(Size::Fixed(Length::Em(n)))
125    }
126
127    /// A share of the container's width ([`Length::Percent`]).
128    pub fn percent(p: f32) -> Self {
129        Self::of(Size::Fixed(Length::Percent(p)))
130    }
131
132    /// Never narrower than `min`.
133    pub fn min(mut self, min: Length) -> Self {
134        self.min = Some(min);
135        self
136    }
137
138    /// Never wider than `max` (a minimum wins over it).
139    pub fn max(mut self, max: Length) -> Self {
140        self.max = Some(max);
141        self
142    }
143
144    fn of(size: Size) -> Self {
145        Self {
146            size,
147            min: None,
148            max: None,
149        }
150    }
151
152    fn clamp(&self, w: f32, em: f32, width: f32) -> f32 {
153        let w = self.max.map_or(w, |m| w.min(m.points(em, width)));
154        self.min.map_or(w, |m| w.max(m.points(em, width))).max(0.0)
155    }
156}
157
158/// How cells sit in their line ([`Row::align`], [`Grid::align`]), or a
159/// line in its container ([`Row::justify`]).
160#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
161pub enum Align {
162    /// At the top (or the start of the line).
163    Start,
164    /// Centred.
165    Center,
166    /// At the bottom (or the end of the line).
167    End,
168    /// Every cell's first text baseline on one line; across a line, the
169    /// same as [`Align::Start`].
170    #[default]
171    Baseline,
172}
173
174impl Align {
175    fn share(self) -> f32 {
176        match self {
177            Align::Start | Align::Baseline => 0.0,
178            Align::Center => 0.5,
179            Align::End => 1.0,
180        }
181    }
182}
183
184#[derive(Clone, Debug)]
185pub(super) struct Spec {
186    id_salt: Option<IdSalt>,
187    tracks: Vec<Track>,
188    gap: Space,
189    row_gap: Space,
190    align: Align,
191    justify: Align,
192    equal: bool,
193    fold_below: Option<Length>,
194}
195
196impl Spec {
197    fn new(tracks: impl IntoIterator<Item = Track>) -> Self {
198        let mut tracks: Vec<Track> = tracks.into_iter().collect();
199        if tracks.is_empty() {
200            tracks.push(Track::CONTENT);
201        }
202        Self {
203            id_salt: None,
204            tracks,
205            gap: Space::Inline,
206            row_gap: Space::Inline,
207            align: Align::Baseline,
208            justify: Align::Start,
209            equal: false,
210            fold_below: None,
211        }
212    }
213}
214
215/// One line of cells, one per track, shown by [`UiPop::row`]. Cells are
216/// [`Space::Inline`] apart and on one baseline unless told otherwise.
217#[derive(Clone, Debug)]
218pub struct Row(pub(super) Spec);
219
220impl Row {
221    /// A row of `tracks`, one cell each.
222    pub fn new(tracks: impl IntoIterator<Item = Track>) -> Self {
223        Self(Spec::new(tracks))
224    }
225
226    /// Its id, for the sizes it keeps between passes; by default the
227    /// `Ui`'s next automatic id.
228    pub fn id_salt(mut self, salt: impl AsIdSalt) -> Self {
229        self.0.id_salt = Some(IdSalt::new(salt));
230        self
231    }
232
233    /// The space between cells (`Space::Inline` by default).
234    pub fn gap(mut self, gap: Space) -> Self {
235        self.0.gap = gap;
236        self
237    }
238
239    /// How cells sit vertically ([`Align::Baseline`] by default).
240    pub fn align(mut self, align: Align) -> Self {
241        self.0.align = align;
242        self
243    }
244
245    /// Where the cells go when they leave room (no [`Track::fr`]):
246    /// [`Align::End`] for a button bar.
247    pub fn justify(mut self, justify: Align) -> Self {
248        self.0.justify = justify;
249        self
250    }
251
252    /// Every content-sized cell as wide as the widest, its content
253    /// stretched across it (buttons of a bar).
254    pub fn equal_widths(mut self) -> Self {
255        self.0.equal = true;
256        self
257    }
258}
259
260/// Lines of cells on shared tracks, shown by [`UiPop::grid`]: cells fill
261/// the tracks left to right, a line per track count. Columns are
262/// [`Space::Group`] apart, lines [`Space::Inline`].
263#[derive(Clone, Debug)]
264pub struct Grid(pub(super) Spec);
265
266impl Grid {
267    /// A grid of `tracks`, under an id unique in its `Ui`.
268    pub fn new(id_salt: impl AsIdSalt, tracks: impl IntoIterator<Item = Track>) -> Self {
269        let mut spec = Spec::new(tracks);
270        spec.id_salt = Some(IdSalt::new(id_salt));
271        spec.gap = Space::Group;
272        Self(spec)
273    }
274
275    /// The space between columns (`Space::Group` by default).
276    pub fn gap(mut self, gap: Space) -> Self {
277        self.0.gap = gap;
278        self
279    }
280
281    /// The space between lines (`Space::Inline` by default).
282    pub fn row_gap(mut self, gap: Space) -> Self {
283        self.0.row_gap = gap;
284        self
285    }
286
287    /// How cells sit vertically in their line ([`Align::Baseline`] by
288    /// default).
289    pub fn align(mut self, align: Align) -> Self {
290        self.0.align = align;
291        self
292    }
293
294    /// Every content-sized column as wide as the widest.
295    pub fn equal_widths(mut self) -> Self {
296        self.0.equal = true;
297        self
298    }
299
300    /// Below `width`, one column: each line's cells stacked full width (a
301    /// header over its value), [`Space::Inline`] apart, lines
302    /// [`Space::Group`] apart.
303    pub fn fold_below(mut self, width: Length) -> Self {
304        self.0.fold_below = Some(width);
305        self
306    }
307}
308
309/// A cell's size, measured from its top.
310#[derive(Clone, Copy, Debug, Default, PartialEq)]
311struct Cell {
312    height: f32,
313    baseline: f32,
314}
315
316/// What a layout keeps between passes.
317#[derive(Clone, Debug, Default)]
318struct Measured {
319    /// The widest content of each column.
320    content: Vec<f32>,
321    /// Each line's cells.
322    lines: Vec<Vec<Cell>>,
323    /// The text painted in each equal-width column, to measure it again
324    /// when it changes.
325    texts: Vec<u64>,
326    /// Measure the equal-width columns at their natural width next pass.
327    remeasure: bool,
328}
329
330impl Measured {
331    fn near(&self, other: &Self) -> bool {
332        let close = |a: f32, b: f32| (a - b).abs() < 0.5;
333        self.content.len() == other.content.len()
334            && self
335                .content
336                .iter()
337                .zip(&other.content)
338                .all(|(a, b)| close(*a, *b))
339            && self.lines.len() == other.lines.len()
340            && self.lines.iter().zip(&other.lines).all(|(a, b)| {
341                a.len() == b.len()
342                    && a.iter()
343                        .zip(b)
344                        .all(|(a, b)| close(a.height, b.height) && close(a.baseline, b.baseline))
345            })
346            && self.texts == other.texts
347            && self.remeasure == other.remeasure
348    }
349}
350
351/// The cells of a [`Row`] or a [`Grid`], filled in order.
352pub struct Cells<'a> {
353    ui: &'a mut Ui,
354    spec: Spec,
355    id: egui::Id,
356    prev: Measured,
357    next: Measured,
358    folded: bool,
359    measuring: bool,
360    xs: Vec<f32>,
361    widths: Vec<f32>,
362    origin: Pos2,
363    full_width: f32,
364    bottom_limit: f32,
365    body_row: f32,
366    body_baseline: f32,
367    index: usize,
368    line_top: f32,
369    line_bottom: f32,
370    right: f32,
371    ppp: f32,
372}
373
374impl std::fmt::Debug for Cells<'_> {
375    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
376        f.debug_struct("Cells")
377            .field("id", &self.id)
378            .field("index", &self.index)
379            .field("folded", &self.folded)
380            .field("widths", &self.widths)
381            .finish_non_exhaustive()
382    }
383}
384
385impl Cells<'_> {
386    /// The next cell, `add` drawing its content top-down from its top-left
387    /// corner.
388    pub fn cell<R>(&mut self, add: impl FnOnce(&mut Ui) -> R) -> R {
389        let n = self.spec.tracks.len();
390        let (line, col) = (self.index / n, self.index % n);
391        let index = self.index;
392        self.index += 1;
393        let space = |s: Space| s.points(&Tokens::of(self.ui.ctx()));
394        if index > 0 && (self.folded || col == 0) {
395            let gap = match (self.folded, col) {
396                (true, 0) => space(Space::Group).max(space(self.spec.row_gap)),
397                (true, _) => space(Space::Inline),
398                _ => space(self.spec.row_gap),
399            };
400            self.line_top = self.round(self.line_bottom + gap);
401            self.line_bottom = self.line_top;
402        }
403        let track = self.spec.tracks[col];
404        let content = track.size == Size::Content;
405        let equal = self.spec.equal && content;
406        let (x, width) = if self.folded {
407            (self.origin.x, self.full_width)
408        } else if equal && self.measuring {
409            (self.xs[col], 0.0)
410        } else {
411            (self.xs[col], self.widths[col])
412        };
413        let offset = if self.folded {
414            0.0
415        } else {
416            self.round(self.offset(line, col))
417        };
418        let top = self.line_top + offset;
419        let rect = Rect::from_min_max(pos2(x, top), pos2(x + width, self.bottom_limit.max(top)));
420        let layout = if equal {
421            Layout::top_down_justified(EguiAlign::Center)
422        } else {
423            Layout::top_down(EguiAlign::Min)
424        };
425        let mut child = self.ui.new_child(
426            UiBuilder::new()
427                .id_salt(("egui_pop.cell", index))
428                .max_rect(rect)
429                .layout(layout),
430        );
431        if content && !self.folded {
432            child.style_mut().wrap_mode = Some(TextWrapMode::Extend);
433        }
434        let layer = child.layer_id();
435        let start = self
436            .ui
437            .ctx()
438            .graphics(|g| g.get(layer).map_or(0, |l| l.next_idx().0));
439        let out = add(&mut child);
440        let used = child.min_rect();
441        let (first, texts) = scan(self.ui.ctx(), layer, start);
442        let height = (used.bottom() - top).max(0.0);
443        let baseline = first.map_or((height - self.body_row) / 2.0 + self.body_baseline, |y| {
444            y - top
445        });
446        self.line_bottom = self.line_bottom.max(used.bottom());
447        self.right = self.right.max(used.right()).max(rect.right());
448        if !self.folded {
449            if content {
450                // Its width, not its right edge: content wider than a
451                // cell measured at no width spills on both sides.
452                let w = used.width().max(0.0);
453                self.next.content[col] = self.next.content[col].max(w);
454            }
455            if equal {
456                let mut h = std::hash::DefaultHasher::new();
457                (self.next.texts[col], texts).hash(&mut h);
458                self.next.texts[col] = h.finish();
459            }
460            if self.next.lines.len() <= line {
461                self.next.lines.resize(line + 1, vec![Cell::default(); n]);
462            }
463            self.next.lines[line][col] = Cell { height, baseline };
464        }
465        out
466    }
467
468    /// A header cell: `text` in the muted text role, a header/value grid's
469    /// first column.
470    pub fn header(&mut self, text: impl Into<String>) -> Response {
471        let text = text.into();
472        self.cell(|ui| ui.text_role(TextRole::Muted, text))
473    }
474
475    /// The offset of a cell from its line's top, from the previous pass.
476    fn offset(&self, line: usize, col: usize) -> f32 {
477        let Some(cells) = self.prev.lines.get(line) else {
478            return 0.0;
479        };
480        let Some(cell) = cells.get(col) else {
481            return 0.0;
482        };
483        match self.spec.align {
484            Align::Start => 0.0,
485            Align::Baseline => {
486                let base = cells.iter().map(|c| c.baseline).fold(0.0, f32::max);
487                base - cell.baseline
488            }
489            align => {
490                let tallest = cells.iter().map(|c| c.height).fold(0.0, f32::max);
491                (tallest - cell.height) * align.share()
492            }
493        }
494    }
495
496    fn round(&self, v: f32) -> f32 {
497        (v * self.ppp).round() / self.ppp
498    }
499}
500
501/// The topmost text baseline painted on `layer` from shape `start`, and a
502/// hash of the texts painted.
503fn scan(ctx: &egui::Context, layer: egui::LayerId, start: usize) -> (Option<f32>, u64) {
504    fn visit(shape: &Shape, first: &mut Option<f32>, hash: &mut std::hash::DefaultHasher) {
505        match shape {
506            Shape::Vec(shapes) => shapes.iter().for_each(|s| visit(s, first, hash)),
507            Shape::Text(t) => {
508                t.galley.text().hash(hash);
509                if t.angle != 0.0 {
510                    return;
511                }
512                let Some(row) = t.galley.rows.iter().find(|r| !r.row.glyphs.is_empty()) else {
513                    return;
514                };
515                let y = t.pos.y + row.pos.y + row.row.glyphs[0].pos.y;
516                *first = Some(first.map_or(y, |f| f.min(y)));
517            }
518            _ => {}
519        }
520    }
521    let mut first = None;
522    let mut hash = std::hash::DefaultHasher::new();
523    ctx.graphics(|g| {
524        if let Some(list) = g.get(layer) {
525            list.all_entries()
526                .skip(start)
527                .for_each(|c| visit(&c.shape, &mut first, &mut hash));
528        }
529    });
530    (first, hash.finish())
531}
532
533/// Widths of `tracks` in a container `width` wide with `gap` between them.
534fn widths(
535    tracks: &[Track],
536    content: &[f32],
537    width: f32,
538    gap: f32,
539    em: f32,
540    equal: bool,
541) -> Vec<f32> {
542    let mut out: Vec<f32> = tracks
543        .iter()
544        .enumerate()
545        .map(|(i, t)| match t.size {
546            Size::Content => t.clamp(content.get(i).copied().unwrap_or(0.0), em, width),
547            Size::Fixed(l) => t.clamp(l.points(em, width), em, width),
548            Size::Fr(_) => 0.0,
549        })
550        .collect();
551    if equal {
552        let widest = tracks
553            .iter()
554            .zip(&out)
555            .filter(|(t, _)| t.size == Size::Content)
556            .map(|(_, w)| *w)
557            .fold(0.0, f32::max);
558        for (t, w) in tracks.iter().zip(out.iter_mut()) {
559            if t.size == Size::Content {
560                *w = widest;
561            }
562        }
563    }
564    // What is left goes to the fractions by weight; a fraction held at its
565    // minimum or maximum leaves the rest to the others.
566    let gaps = gap * tracks.len().saturating_sub(1) as f32;
567    let mut left = width - gaps - out.iter().sum::<f32>();
568    let mut open: Vec<usize> = (0..tracks.len())
569        .filter(|i| matches!(tracks[*i].size, Size::Fr(_)))
570        .collect();
571    while !open.is_empty() {
572        let weight: f32 = open
573            .iter()
574            .map(|i| match tracks[*i].size {
575                Size::Fr(w) => w,
576                _ => 0.0,
577            })
578            .sum();
579        let share = |i: usize| match tracks[i].size {
580            Size::Fr(w) if weight > 0.0 => left.max(0.0) * w / weight,
581            _ => 0.0,
582        };
583        let held = open.iter().position(|&i| {
584            let s = share(i);
585            (tracks[i].clamp(s, em, width) - s).abs() > 0.01
586        });
587        match held {
588            Some(k) => {
589                let i = open.remove(k);
590                out[i] = tracks[i].clamp(share(i), em, width);
591                left -= out[i];
592            }
593            None => {
594                for &i in &open {
595                    out[i] = share(i);
596                }
597                break;
598            }
599        }
600    }
601    out
602}
603
604pub(super) fn show<R>(
605    ui: &mut Ui,
606    spec: Spec,
607    add: impl FnOnce(&mut Cells<'_>) -> R,
608) -> InnerResponse<R> {
609    let id = match spec.id_salt {
610        Some(salt) => ui.make_persistent_id(salt),
611        None => {
612            let id = ui.next_auto_id();
613            ui.skip_ahead_auto_ids(1);
614            id
615        }
616    };
617    let tokens = Tokens::of(ui.ctx());
618    let em = tokens.text_role.body.size.max(1.0);
619    let avail = ui.available_rect_before_wrap();
620    let full_width = avail.width().max(0.0);
621    let prev = ui
622        .data(|d| d.get_temp::<Measured>(id))
623        .unwrap_or_else(|| Measured {
624            remeasure: true,
625            ..Measured::default()
626        });
627    let folded = spec
628        .fold_below
629        .is_some_and(|l| full_width < l.points(em, full_width));
630    let n = spec.tracks.len();
631    let gap = spec.gap.points(&tokens);
632    let mut content = prev.content.clone();
633    content.resize(n, 0.0);
634    let ws = widths(&spec.tracks, &content, full_width, gap, em, spec.equal);
635    let ppp = ui.ctx().pixels_per_point();
636    let round = |v: f32| (v * ppp).round() / ppp;
637    let total = ws.iter().sum::<f32>() + gap * n.saturating_sub(1) as f32;
638    let mut x = avail.left() + (full_width - total).max(0.0) * spec.justify.share();
639    let mut xs = Vec::with_capacity(n);
640    for w in &ws {
641        xs.push(round(x));
642        x += w + gap;
643    }
644    let body = TextStyle::Body.resolve(ui.style());
645    let probe = ui
646        .painter()
647        .layout_no_wrap("Hg".to_owned(), body, egui::Color32::WHITE);
648    let body_row = probe.size().y;
649    let body_baseline = probe
650        .rows
651        .first()
652        .and_then(|r| r.row.glyphs.first().map(|g| r.pos.y + g.pos.y))
653        .unwrap_or(body_row);
654    let top = round(avail.top());
655    let measuring = prev.remeasure;
656    let mut next = Measured {
657        content: vec![0.0; n],
658        texts: vec![0; n],
659        ..Measured::default()
660    };
661    if folded {
662        // Folded cells measure nothing: the columns keep what they had.
663        next = Measured {
664            remeasure: false,
665            ..prev.clone()
666        };
667    }
668    let mut cells = Cells {
669        ui,
670        id,
671        prev,
672        next,
673        folded,
674        measuring,
675        xs,
676        widths: ws,
677        origin: avail.min,
678        full_width,
679        bottom_limit: avail.bottom(),
680        body_row,
681        body_baseline,
682        index: 0,
683        line_top: top,
684        line_bottom: top,
685        right: avail.left(),
686        ppp,
687        spec,
688    };
689    let inner = add(&mut cells);
690    let Cells {
691        ui,
692        id,
693        prev,
694        mut next,
695        folded,
696        spec,
697        line_bottom,
698        right,
699        ..
700    } = cells;
701    if !folded {
702        next.remeasure = spec.equal && next.texts != prev.texts;
703        if measuring {
704            // Natural widths measured: the next pass shows them.
705            next.remeasure = false;
706        }
707    }
708    let changed = !next.near(&prev) || (measuring && !folded);
709    if changed {
710        ui.data_mut(|d| d.insert_temp(id, next));
711        ui.ctx()
712            .request_discard("egui-pop row or grid sizes changed");
713    }
714    let has_fr = spec.tracks.iter().any(|t| matches!(t.size, Size::Fr(_)));
715    let right = if has_fr || folded {
716        right.max(avail.right())
717    } else {
718        right
719    };
720    let rect = Rect::from_min_max(avail.min, pos2(right, line_bottom.max(avail.top())));
721    let response = ui.allocate_rect(rect, Sense::hover());
722    InnerResponse::new(inner, response)
723}
724
725/// Whole cells left to right, wrapping to the next line those that do not
726/// fit, shown by [`UiPop::flow`]: a bar of action buttons that keeps each
727/// button on one line in a narrow container. Cells are [`Space::Inline`]
728/// apart, lines [`Space::Inline`] apart, each cell centred on its line.
729///
730/// Unlike egui's `horizontal_wrapped`, which wraps only widgets placed
731/// directly in it, a flow wraps any cell, a child `Ui` included (a toned
732/// button, an `add_enabled_ui` scope): each cell is placed at the size it
733/// had on the previous pass.
734#[derive(Clone, Debug)]
735pub struct Flow {
736    id_salt: Option<IdSalt>,
737    gap: Space,
738    row_gap: Space,
739}
740
741impl Default for Flow {
742    fn default() -> Self {
743        Self::new()
744    }
745}
746
747impl Flow {
748    /// A flow with the default gaps.
749    pub fn new() -> Self {
750        Self {
751            id_salt: None,
752            gap: Space::Inline,
753            row_gap: Space::Inline,
754        }
755    }
756
757    /// Its id, for the sizes it keeps between passes; by default the
758    /// `Ui`'s next automatic id.
759    pub fn id_salt(mut self, salt: impl AsIdSalt) -> Self {
760        self.id_salt = Some(IdSalt::new(salt));
761        self
762    }
763
764    /// The space between cells on a line (`Space::Inline` by default).
765    pub fn gap(mut self, gap: Space) -> Self {
766        self.gap = gap;
767        self
768    }
769
770    /// The space between lines (`Space::Inline` by default).
771    pub fn row_gap(mut self, gap: Space) -> Self {
772        self.row_gap = gap;
773        self
774    }
775}
776
777/// The sizes of a flow's cells on the previous pass.
778#[derive(Clone, Debug, Default, PartialEq)]
779struct FlowSizes(Vec<Vec2>);
780
781/// The cells of a [`Flow`], placed in order.
782pub struct FlowCells<'a> {
783    ui: &'a mut Ui,
784    prev: Vec<Vec2>,
785    next: Vec<Vec2>,
786    spacing: Vec2,
787}
788
789impl std::fmt::Debug for FlowCells<'_> {
790    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
791        f.debug_struct("FlowCells")
792            .field("index", &self.next.len())
793            .finish_non_exhaustive()
794    }
795}
796
797impl FlowCells<'_> {
798    /// The next cell, `add` drawing its content left to right (on one line,
799    /// text unwrapped); the cell moves to the next line whole when it does
800    /// not fit on this one.
801    pub fn cell<R>(&mut self, add: impl FnOnce(&mut Ui) -> R) -> R {
802        let index = self.next.len();
803        // Unknown on the first pass: placed at no size, measured, and the
804        // pass discarded.
805        let size = self.prev.get(index).copied().unwrap_or(Vec2::ZERO);
806        let spacing = self.spacing;
807        let layout = Layout::left_to_right(EguiAlign::Center);
808        let out = self.ui.allocate_ui_with_layout(size, layout, |ui| {
809            ui.spacing_mut().item_spacing = spacing;
810            ui.style_mut().wrap_mode = Some(TextWrapMode::Extend);
811            add(ui)
812        });
813        self.next.push(out.response.rect.size());
814        out.inner
815    }
816}
817
818pub(super) fn show_flow<R>(
819    ui: &mut Ui,
820    flow: Flow,
821    add: impl FnOnce(&mut FlowCells<'_>) -> R,
822) -> InnerResponse<R> {
823    let id = match flow.id_salt {
824        Some(salt) => ui.make_persistent_id(salt),
825        None => {
826            let id = ui.next_auto_id();
827            ui.skip_ahead_auto_ids(1);
828            id
829        }
830    };
831    let tokens = Tokens::of(ui.ctx());
832    let prev = ui.data(|d| d.get_temp::<FlowSizes>(id));
833    let measuring = prev.is_none();
834    let prev = prev.unwrap_or_default().0;
835    let spacing = ui.spacing().item_spacing;
836    let gaps = vec2(flow.gap.points(&tokens), flow.row_gap.points(&tokens));
837    let layout = Layout::left_to_right(EguiAlign::Center).with_main_wrap(true);
838    // One line high to start with, as egui's `horizontal_wrapped`: the first
839    // line sits at the top and the next ones wrap downward. Without the cap,
840    // the first line is centred in all the height left in the parent.
841    let initial = vec2(
842        ui.available_size_before_wrap().x,
843        ui.spacing().interact_size.y,
844    );
845    let InnerResponse { inner, response } = ui.allocate_ui_with_layout(initial, layout, |ui| {
846        ui.spacing_mut().item_spacing = gaps;
847        let mut cells = FlowCells {
848            ui,
849            prev,
850            next: Vec::new(),
851            spacing,
852        };
853        let inner = add(&mut cells);
854        let close = |a: &Vec2, b: &Vec2| (*a - *b).abs().max_elem() < 0.5;
855        let changed = cells.prev.len() != cells.next.len()
856            || cells
857                .prev
858                .iter()
859                .zip(&cells.next)
860                .any(|(a, b)| !close(a, b));
861        (inner, changed.then_some(cells.next))
862    });
863    let (inner, next) = inner;
864    if let Some(next) = next {
865        ui.data_mut(|d| d.insert_temp(id, FlowSizes(next)));
866        ui.ctx().request_discard("egui-pop flow sizes changed");
867    } else if measuring {
868        ui.data_mut(|d| d.insert_temp(id, FlowSizes::default()));
869    }
870    InnerResponse::new(inner, response)
871}
872
873#[cfg(test)]
874mod tests {
875    use super::*;
876
877    #[test]
878    fn fractions_share_what_is_left_and_respect_their_bounds() {
879        let em = 10.0;
880        let t = [Track::fr(1.0), Track::fr(3.0)];
881        assert_eq!(widths(&t, &[], 410.0, 10.0, em, false), vec![100.0, 300.0]);
882        let t = [Track::fr(1.0).min(Length::Em(20.0)), Track::fr(3.0)];
883        assert_eq!(widths(&t, &[], 410.0, 10.0, em, false), vec![200.0, 200.0]);
884        let t = [Track::fr(1.0), Track::fr(1.0).max(Length::Percent(10.0))];
885        assert_eq!(widths(&t, &[], 400.0, 0.0, em, false), vec![360.0, 40.0]);
886        let t = [
887            Track::CONTENT,
888            Track::em(5.0),
889            Track::percent(25.0),
890            Track::fr(1.0),
891        ];
892        assert_eq!(
893            widths(&t, &[30.0], 400.0, 10.0, em, false),
894            vec![30.0, 50.0, 100.0, 190.0]
895        );
896    }
897
898    #[test]
899    fn equal_widths_take_the_widest_content() {
900        let t = [Track::CONTENT; 3];
901        assert_eq!(
902            widths(&t, &[20.0, 50.0, 35.0], 400.0, 0.0, 10.0, true),
903            vec![50.0; 3]
904        );
905    }
906}