makeover-immediate 0.70.0

The immediate-mode renderer for makeover-layout, backed by egui: no cascade, no retained tree, one stroke per widget.
Documentation
//! A table's style, its per-frame facts, and the tone each part of a cell
//! takes.
//!
//! The table itself, which takes the description's columns, narrows them for
//! the width on offer and draws the heading row over `egui_extras`, is
//! `quasi-immediate`'s, since a column is a vocabulary member. What carries
//! no column stays here and is what
//! that table is drawn with: [`TableStyle`] for the metrics, [`Body`] for the
//! rows, selection and scroll request of one frame, [`Sizing`] for the lengths
//! the description deferred, and [`cell`] with [`part_color`] for the tone a
//! cell's contents take.
//!
//! # The table model
//!
//! Wiki `table-model`, drawn the way `makeover-webview` draws it: a raised
//! ground inside a hairline
//! frame, the header a sunken strip over a `bevel-dark` edge in secondary
//! capitals, rows 45 points tall with a hairline between them and a tone under
//! the pointer. No stripe: the hairline separates the rows. A table holding
//! code keeps the frame and the header and drops the hairlines and the tall
//! row, taking [`TableStyle::code_row_height`] instead.

use crate::Palette;
use egui::Ui;
use makeover_geometry::{Compactness, Density, Gap, Step, Surface, Text};
use makeover_layout::{CellPart, Sort};

/// The lengths the description deferred, in points: the track for a
/// [`Width::Fixed`](makeover_layout::Width::Fixed) column, the floor for a [`Width::Fill`](makeover_layout::Width::Fill) one, and the
/// narrowing budget for a [`Width::Content`](makeover_layout::Width::Content) one.
pub type Sizing<'a> = makeover_layout::Sizing<'a, f32>;

/// The tones and metrics a table draws with.
///
/// Metrics only; the tones are [`Palette`]'s content tones, read through
/// [`part_color`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TableStyle {
    /// How densely the rows are packed: [`Compactness::Comfortable`] is the
    /// model's [`ROW_BLOCK`](makeover_geometry::ROW_BLOCK), [`Compactness::Compact`] a denser row. The
    /// reader's choice; the description does not carry it.
    pub compactness: Compactness,
    /// The height of the heading row.
    pub header_height: f32,
    /// The height of a body row: [`Compactness::row_block`] at
    /// `makeover-geometry`'s base.
    pub row_height: f32,
    /// The height of a row in a table holding code: one line of source, the
    /// monospace size ([`Text::Note`]) and a hair ([`Step::Hair`]) above and
    /// below it.
    pub code_row_height: f32,
    /// The ground between the table's frame and the cells at either end of a
    /// row: the webview's `gap-group` at [`Density::Pointer`], 10 points at
    /// the default base.
    pub edge_padding: f32,
    /// The caret drawn after the heading of an ascending column.
    ///
    /// Defaults to [`Sort::glyph`]. Bare, with no leading space: the heading
    /// adds the gap.
    pub ascending: &'static str,
    /// Drawn after the heading of a descending column.
    pub descending: &'static str,
    /// Whether the user can drag the divider between two columns.
    ///
    /// Off by default. A drag moves a track for the frames it is held; the
    /// narrowing still decides which columns exist, off each column's declared
    /// floor, so a resize never drops a column.
    pub resizable: bool,
}

impl Default for TableStyle {
    fn default() -> Self {
        Self::for_compactness(Surface::web(), Compactness::Comfortable)
    }
}

impl TableStyle {
    /// The default metrics on `surface`, at `compactness`.
    ///
    /// Every length is resolved from the geometry scale on `surface`, so all
    /// of them move with its base (`row_height` is the webview's
    /// `--row-block`). The web surface is the egui one: points at the default
    /// base, one point to the quantum.
    #[must_use]
    pub fn for_compactness(surface: Surface, compactness: Compactness) -> Self {
        Self {
            compactness,
            header_height: surface.resolve(Step::Vast.ratio()),
            row_height: surface.resolve(compactness.row_block()),
            code_row_height: 2.0_f32.mul_add(
                surface.resolve(Step::Hair.ratio()),
                surface.resolve(Text::Note.ratio()),
            ),
            edge_padding: surface.resolve(Gap::Group.step_at(Density::Pointer).ratio()),
            ascending: Sort::Ascending.glyph(),
            descending: Sort::Descending.glyph(),
            resizable: false,
        }
    }
}

/// The body's own facts for this frame: how many rows, which are selected, and
/// which one to bring into view.
///
/// None of it is style or description, and none of it outlives the frame.
/// egui_extras answers both optional fields on handles the table owns:
/// `set_selected` on the row, `scroll_to_row` on the builder.
#[derive(Default)]
pub struct Body<'a> {
    /// How many rows to draw.
    pub rows: usize,
    /// Whether a row is selected, by index.
    ///
    /// A predicate over row indices. `None` is a table with no row selected.
    pub selected: Option<&'a dyn Fn(usize) -> bool>,
    /// A row to bring into view this frame.
    ///
    /// Set it from a request the app then clears, the way a keyboard cursor
    /// moving off-screen raises one: held rather than taken, it would fight
    /// every scroll the user makes with the mouse.
    pub scroll_to: Option<usize>,
}

impl std::fmt::Debug for Body<'_> {
    // Hand-written because `selected` is a closure and `#[derive(Debug)]` will
    // not have it. What is worth printing is whether one was supplied.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Body")
            .field("rows", &self.rows)
            .field("selected", &self.selected.is_some())
            .field("scroll_to", &self.scroll_to)
            .finish()
    }
}

/// The colour a cell of this part takes: the content intent
/// [`CellPart::intent`] names.
///
/// A cell that says no part, and an intent outside makeover-layout's
/// `content*` set, take `content`, so a part or an intent this renderer has
/// not learned draws as text rather than as nothing.
#[must_use]
pub const fn part_color(part: Option<CellPart>, palette: &Palette) -> egui::Color32 {
    match part {
        Some(part) => content_ink(part.intent(), palette),
        None => palette.content,
    }
}

/// The palette's colour for a `content*` intent, and `content` for any other.
const fn content_ink(intent: &str, palette: &Palette) -> egui::Color32 {
    match intent.as_bytes() {
        b"content-secondary" => palette.content_secondary,
        b"content-muted" => palette.content_muted,
        b"content-disabled" => palette.content_disabled,
        _ => palette.content,
    }
}

/// Draw a cell's contents with the tone its part takes.
///
/// The app calls this inside its own cell closure, wrapping whatever it
/// draws: it sets the text colour override for the closure and restores the
/// previous one after.
///
/// ```no_run
/// # use makeover_layout::CellPart;
/// # let palette: makeover_immediate::Palette = unimplemented!();
/// # let ui: &mut egui::Ui = unimplemented!();
/// makeover_immediate::table::cell(ui, Some(CellPart::Link), &palette, |ui| {
///     ui.label("opens the item");
/// });
/// ```
pub fn cell<R>(
    ui: &mut Ui,
    part: Option<CellPart>,
    palette: &Palette,
    add_contents: impl FnOnce(&mut Ui) -> R,
) -> R {
    let restore = ui.visuals().override_text_color;
    ui.visuals_mut().override_text_color = Some(part_color(part, palette));
    let out = add_contents(ui);
    ui.visuals_mut().override_text_color = restore;
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::palette;

    #[test]
    fn a_cell_part_takes_the_colour_its_intent_names() {
        // makeover-layout's `CellPart::intent` is the rule every host reads, so
        // a link here draws as the webview's does, in the values' ink.
        let p = palette();
        for part in [
            CellPart::Value,
            CellPart::Tokens,
            CellPart::Actions,
            CellPart::Link,
        ] {
            let want = match part.intent() {
                "content" => p.content,
                "content-secondary" => p.content_secondary,
                "content-muted" => p.content_muted,
                "content-disabled" => p.content_disabled,
                other => panic!("{part:?} names {other}, which this renderer has not learned"),
            };
            assert_eq!(part_color(Some(part), &p), want, "{part:?}");
        }
        // A cell mixing parts says nothing, and takes the text colour.
        assert_eq!(part_color(None, &p), p.content);
    }

    #[test]
    fn every_content_intent_reads_its_own_ink_and_any_other_reads_content() {
        // Every intent makeover-layout's content set names, whether or not a
        // cell part names it today, so a part that starts to has its ink.
        let p = palette();
        assert_eq!(content_ink("content", &p), p.content);
        assert_eq!(content_ink("content-secondary", &p), p.content_secondary);
        assert_eq!(content_ink("content-muted", &p), p.content_muted);
        assert_eq!(content_ink("content-disabled", &p), p.content_disabled);
        assert_eq!(content_ink("status-danger", &p), p.content);
    }

    #[test]
    fn the_carets_match_the_terminal_renderers() {
        // Two crates, one glyph pair, and no dependency between them to enforce
        // it. A description sorted ascending must not point up in a window and
        // down in a terminal.
        // Composition rather than agreement: both read `Sort::glyph`, so a
        // fourth spelling cannot appear in one crate.
        let style = TableStyle::default();
        assert_eq!(style.ascending, Sort::Ascending.glyph());
        assert_eq!(style.descending, Sort::Descending.glyph());
        // Bare. The gap is the heading's, so a consumer swapping the glyph for an
        // ASCII one does not have to remember to bring a space with it.
        assert_eq!(style.ascending.trim(), style.ascending);
    }

    #[test]
    fn resizing_is_off_because_the_description_has_no_word_for_it() {
        // egui_extras offers it and the other two renderers cannot say it. A
        // default that turned it on would be this renderer adding a claim.
        assert!(!TableStyle::default().resizable);
    }

    #[test]
    fn a_record_row_is_the_models_45_and_a_code_row_is_one_line() {
        let style = TableStyle::default();
        assert!((style.row_height - 45.0).abs() < f32::EPSILON);
        assert!(style.code_row_height < style.row_height);
    }

    #[test]
    fn a_compact_table_packs_rows_at_the_dense_step() {
        // Compact is the reader's denser row, not a description claim. It is
        // Step::Broad of the base (24pt), audiofiles' historical default.
        let style = TableStyle::for_compactness(Surface::web(), Compactness::Compact);
        assert_eq!(style.compactness, Compactness::Compact);
        assert!((style.row_height - 24.0).abs() < f32::EPSILON);
    }

    #[test]
    fn a_body_claims_nothing_until_it_is_asked_to() {
        // The default is a table of no rows, no selection and no scroll
        // request. All three absences are the honest reading of an app that has
        // not said otherwise, which is why they are `Option` and not a
        // predicate that always answers false.
        let body = Body::default();
        assert_eq!(body.rows, 0);
        assert!(body.selected.is_none());
        assert!(body.scroll_to.is_none());
    }

    #[test]
    fn a_selection_is_asked_per_row_and_not_collected() {
        // A predicate, so an app whose selection is a range or a single index
        // does not build a set to be asked. Exercised the way the table asks it:
        // once per row index, in order.
        let selected = |index: usize| index.is_multiple_of(2);
        let body = Body {
            rows: 4,
            selected: Some(&selected),
            scroll_to: None,
        };
        let f = body.selected.expect("a predicate was supplied");
        assert_eq!(
            (0..body.rows).map(f).collect::<Vec<_>>(),
            vec![true, false, true, false]
        );
    }

    #[test]
    fn repro_immediate_table_edge_padding_literal() {
        // The ends of a row are padded by the webview's gap-group, and both
        // lengths move with the surface's base rather than staying put.
        let style = TableStyle::default();
        assert!(
            (style.edge_padding - f32::from(Gap::Group.px_at(Density::Pointer))).abs()
                < f32::EPSILON
        );
        let doubled = Surface {
            base: 32.0,
            quantum: 1.0,
        };
        let big = TableStyle::for_compactness(doubled, Compactness::Comfortable);
        assert!((big.edge_padding / style.edge_padding - 2.0).abs() < f32::EPSILON);
        assert!((big.code_row_height / style.code_row_height - 2.0).abs() < f32::EPSILON);
    }
}