makeover-immediate 0.68.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, because a column is a vocabulary member and the quasi
//! hosts own the vocabulary. 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, since egui
//! paints the same pixels a browser does: 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, and makeover 5 has
//! no stripe tone. A table holding code keeps the frame and the header and
//! drops the hairlines and the tall row, which is what
//! [`TableStyle::code_row_height`] is for.

use crate::Palette;
use egui::Ui;
use makeover_geometry::{Compactness, Step, Surface};
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. The suite's one sizing type,
/// held here over points as the terminal holds it over cells.
pub type Sizing<'a> = makeover_layout::Sizing<'a, f32>;

/// The tones and metrics a table draws with.
///
/// Metrics only, and the tones come from [`Palette`]. That is the division this
/// crate already draws: [`FieldStyle`](crate::FieldStyle) carries gaps and a
/// marker while the colours stay in the palette, and a table's colours are the
/// palette's content tones rather than six new ones.
/// `makeover-tui` splits it the other way round because its palette carries no
/// text tones at all.
#[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, not the description's: packing is a fact about eyes
    /// and screen, not about what the table says.
    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, which is one line of
    /// source rather than a record.
    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`, which pads both ends of a row.
    pub edge_padding: f32,
    /// The caret drawn after the heading of an ascending column.
    ///
    /// Defaults to [`Sort::glyph`], which is where the spelling lives now:
    /// three renderers holding the same literal agreed by coincidence. Bare,
    /// with no leading space: the gap is the heading's, written once for all
    /// three states rather than baked into two strings and forgotten in the
    /// third.
    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.
    ///
    /// The one knob that is not a metric. Not every setting egui_extras has
    /// becomes a field here: a sticky heading is what `TableBuilder::header`
    /// does and there is no version that does not, and the table model draws no
    /// stripe at any host with a hairline, so a knob for either would offer a
    /// choice this renderer cannot make. Off by default: the description has no word for
    /// resizing, so a default that turned it on would be this renderer adding a
    /// claim the other two cannot make.
    ///
    /// It does not fight the narrowing. 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 can never drop 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`.
    ///
    /// Resolved from the geometry scale rather than written as literals, so a
    /// changed base moves egui tables with the webview's `--row-block` and
    /// with the heading the other hosts draw. 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: 20.0,
            edge_padding: 12.0,
            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.
///
/// Held apart from [`TableStyle`] because none of it is style and none of it
/// survives the frame: a row count changes when a folder does, a selection when
/// the user clicks, and a scroll request exists for exactly one frame. Held
/// apart from the columns because none of it is description either.
/// The description says what a table *is*, and this says what it holds right
/// now.
///
/// Both of the optional fields are here rather than left to the app because
/// egui_extras answers them on a handle the app never sees: `set_selected` is a
/// method on the row, and `scroll_to_row` a method on the builder, and the
/// table owns both. That is the same reason [`cell`] exists.
#[derive(Default)]
pub struct Body<'a> {
    /// How many rows to draw.
    pub rows: usize,
    /// Whether a row is selected, by index.
    ///
    /// A predicate rather than a set, so an app whose selection is a range, a
    /// bitmap or a single index does not have to build a collection to be asked.
    /// `None` is a table no row of which is selected, which is not the same
    /// claim as a predicate that always answers false and costs nothing to make.
    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 {
    let Some(part) = part else {
        return palette.content;
    };
    match part.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.
/// A scoping function rather than a parameter on the table, for the reason
/// [`frame`](crate::frame) is one: the part is a property of the cell, the cell
/// does not exist until the closure runs, and immediate mode has no cascade to
/// carry the answer down on its own. This is the cascade, for one scope.
///
/// ```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 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]
        );
    }
}