makeover-immediate 0.60.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_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`, `content_muted` and `action` 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 {
    /// The height of the heading row.
    pub header_height: f32,
    /// The height of a body row: the model's 45, `--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 {
            header_height: 32.0,
            row_height: 45.0,
            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.
///
/// [`CellPart`] is `#[non_exhaustive]`, and a member added upstream lands on
/// `content`: a part this renderer has not learned draws as text, which is a
/// cell rendering plainly rather than a build that stops. Grep this when
/// adopting a new `makeover-layout`.
#[must_use]
pub const fn part_color(part: Option<CellPart>, palette: &Palette) -> egui::Color32 {
    match part {
        // A token paints its own background and carries its own tone. What is
        // set here is what shows between them, not what paints them.
        Some(CellPart::Tokens) => palette.content_muted,
        // The drift `CellPart` exists to end: a control in a cell inheriting the
        // cell's text colour. Both of these take the action intent instead.
        Some(CellPart::Actions | CellPart::Link) => palette.action,
        _ => 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 egui::Color32;

    fn palette() -> Palette {
        Palette {
            page: Color32::from_rgb(1, 1, 1),
            raised: Color32::from_rgb(2, 2, 2),
            overlay: Color32::from_rgb(3, 3, 3),
            well: Color32::from_rgb(4, 4, 4),
            sunken: Color32::from_rgb(5, 5, 5),
            bevel_light: Color32::WHITE,
            bevel_dark: Color32::BLACK,
            elevation: Color32::from_black_alpha(46),
            content: Color32::from_rgb(6, 6, 6),
            content_secondary: Color32::from_rgb(56, 56, 56),
            content_muted: Color32::from_rgb(7, 7, 7),
            action: Color32::from_rgb(8, 8, 8),
            content_on_action: Color32::from_rgb(250, 250, 250),
            danger: Color32::from_rgb(9, 9, 9),
            success: Color32::from_rgb(10, 10, 10),
            warning: Color32::from_rgb(11, 11, 11),
            info: Color32::from_rgb(12, 12, 12),
            border: Color32::from_rgb(200, 200, 200),
            info_surface: Color32::from_rgb(201, 201, 201),
            success_surface: Color32::from_rgb(202, 202, 202),
            warning_surface: Color32::from_rgb(203, 203, 203),
            danger_surface: Color32::from_rgb(204, 204, 204),
            row_hover: Color32::from_rgb(206, 206, 206),
            row_rule: Color32::from_rgb(207, 207, 207),
            row_selected: Color32::from_rgb(208, 208, 208),
        }
    }

    #[test]
    fn the_parts_a_cell_can_be_are_coloured_apart() {
        // The drift `CellPart` exists to end: one colour for a whole cell paints
        // a control as though it were text.
        let p = palette();
        assert_eq!(part_color(Some(CellPart::Value), &p), p.content);
        assert_eq!(part_color(Some(CellPart::Tokens), &p), p.content_muted);
        assert_eq!(part_color(Some(CellPart::Actions), &p), p.action);
        assert_eq!(part_color(Some(CellPart::Link), &p), p.action);
        assert_ne!(part_color(Some(CellPart::Link), &p), p.content);
        // 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_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]
        );
    }
}