makeover-webview 0.130.0

The webview renderer for makeover-layout. Emits CSS, and is the one renderer that needs no palette: var() is the late binding, so resolution stays with the browser. With the build feature, writes a consumer's generated frontend files and checks the hand-written ones against them.
Documentation
//! The classes a list's or a table's columns, rows and cells carry.
//!
//! The row and cell markup is drawn by the quasi hosts (`quasi-webview` for
//! this renderer), which own the column and cell members of the vocabulary.
//! What stays here is the naming those hosts write into markup and the
//! generated stylesheet rules: a column's name as a class
//! ([`push_column_name`]), the kind, part and flow classes, the cell wrapper
//! ([`CELL_IN`]) and sizer ([`push_sizer`]), the `short-N`, `stacks-N` and
//! `drop-*-N` ladders ([`SHORT_RUNGS`], [`STACKS_RUNGS`], [`DROP_RUNGS`]), and
//! the class lists the vocabulary is checked against.
//!
//! # By priority, never by position
//!
//! A renderer narrows by what a column is worth,
//! [`Priority`](makeover_layout::Priority), as a shrink factor on the column's
//! own class (one of [`CELL_DROP_CLASSES`]), and never by counting positions:
//! inserting a column cannot hide the wrong one.

use crate::form::Markup;
use crate::{Emit, push_class};
use makeover_layout::{CellPart, ColumnKind, Flow, Prominence};

/// A column's name as the identifier half of its class.
///
/// # Reduced, not escaped
///
/// The name is an app-supplied string written into a class attribute. It is
/// reduced to identifier characters: Unicode alphanumerics, `_` and `-` pass
/// through and every other character becomes `-`. The result is a valid CSS
/// identifier, so a selector written against it matches, and it holds none of
/// the characters that can end an attribute value, so it needs no escaping.
/// `Due date` becomes `Due-date`; `a" onclick="steal()` cannot leave the
/// attribute; `Größe` is unchanged.
pub fn push_column_name(out: &mut String, name: &str) {
    for ch in name.chars() {
        // Substituted rather than dropped. Two columns called `a b` and `ab`
        // are different columns, and dropping would give them one class and one
        // set of narrowing rules between them.
        if ch.is_alphanumeric() || ch == '_' || ch == '-' {
            out.push(ch);
        } else {
            out.push('-');
        }
    }
}

/// The class saying what a column holds, or `None` for prose.
///
/// The class goes on every cell and on the heading, and the sheet rules each
/// kind once (wiki `table-model`). Text writes nothing, and a kind added
/// upstream reads as text.
#[must_use]
pub fn kind_class(kind: ColumnKind) -> Option<&'static str> {
    match kind {
        ColumnKind::Identifier => Some("kind-identifier"),
        ColumnKind::Date => Some("kind-date"),
        ColumnKind::Number => Some("kind-number"),
        ColumnKind::Code => Some("kind-code"),
        ColumnKind::Status => Some("kind-status"),
        ColumnKind::Actions => Some("kind-actions"),
        ColumnKind::Picture => Some("kind-picture"),
        _ => None,
    }
}

/// Every class [`kind_class`] can return.
pub const KIND_CLASSES: &[&str] = &[
    "kind-identifier",
    "kind-date",
    "kind-number",
    "kind-code",
    "kind-status",
    "kind-actions",
    "kind-picture",
];

/// The wrapper every cell and heading holds its contents in.
///
/// The padding lives on this, and the column, a flex item that may close to
/// nothing, clips it. It is also what a droppable column hides when it is
/// under its floor, and where the type is set, so a heading and the cells under
/// it are the same box.
pub const CELL_IN: &str = "cell-in";

/// What a kept column is as wide as, when its floor cannot say.
///
/// For a column of controls, whose drawn width a `ch` floor does not state.
/// The host that knows what a column holds writes a copy of it here, once
/// per distinct run of controls, drawn in the row's own type and taking no
/// height and no ink. A kept column holding one is as wide as its widest copy,
/// which the browser measures in the face it draws, and every cell and the
/// heading hold the same copies, so the column is one width down the table.
/// Hidden rather than absent: a hidden box still has a width.
///
/// Write it with [`push_sizer`].
pub const CELL_SIZER: &str = "cell-sizer";

/// A [`CELL_SIZER`] around `copies`, which go inside a cell's or a heading's
/// [`CELL_IN`] after what it holds.
///
/// `copies` is the host's: one block per distinct run, each drawn with the
/// classes and the element the real controls take. Nothing in it may
/// be a control anyone can reach: `aria-hidden` here and `visibility: hidden`
/// in the sheet take it out of the accessibility tree and the tab order, and a
/// copy carries no address. Empty writes nothing.
///
/// [`Markup`], because the copies are the host's markup and are written as-is.
pub fn push_sizer(out: &mut String, copies: Markup<'_>, opts: &Emit) {
    let Markup(copies) = copies;
    if copies.is_empty() {
        return;
    }
    out.push_str("<span class=\"");
    push_class(out, CELL_SIZER, opts);
    out.push_str("\" aria-hidden=\"true\">");
    out.push_str(copies);
    out.push_str("</span>");
}

/// The class a run of row parts takes when what it holds is badges.
///
/// A part's [`Prominence`] says how far forward it stands; what it holds is the
/// node's to say, and the host reads it there. A run of badges, of controls or
/// of a meter carries one of these in place of its prominence class, and no
/// part-level colour.
pub const ROW_TOKENS: &str = "row-tokens";

/// The class a run of row parts takes when what it holds is controls. See
/// [`ROW_TOKENS`].
pub const ROW_ACTIONS: &str = "row-actions";

/// The class a run of row parts takes when what it holds is a meter. See
/// [`ROW_TOKENS`].
pub const ROW_PROPORTION: &str = "row-proportion";

/// Every class [`part_class`] can return, including the fallback, and the
/// three a run takes for what it holds.
///
/// Written out beside the match, since `Prominence` is `#[non_exhaustive]`;
/// a test holds the two together.
pub const ROW_PART_CLASSES: &[&str] = &[
    "row-lead",
    "row-support",
    "row-quiet",
    ROW_ACTIONS,
    ROW_TOKENS,
    ROW_PROPORTION,
    "row-part",
];

/// Every class [`flow_class`] can return.
///
/// `Flow::Tight` has no class: one line is a run's default. Only the tier that
/// departs from it is named.
pub const FLOW_CLASSES: &[&str] = &["row-relaxed"];

/// The classes a row inside a hierarchy carries.
///
/// Part of [`crate::vocabulary::names`]; the generated sheet rules them.
pub const NESTING_CLASSES: &[&str] = &["row-nested", "row-branch", "row-disclose"];

/// The class for a part's flow, if it needs one.
///
/// `None` for [`Flow::Tight`] and for any tier added upstream that this crate
/// does not know, which lands as one line.
#[must_use]
pub fn flow_class(flow: Flow) -> Option<&'static str> {
    match flow {
        Flow::Relaxed => Some("row-relaxed"),
        _ => None,
    }
}

/// Every class saying how wide a cell of a column asks to be, including the
/// fill a column that makes no claim lands on.
///
/// Written out, since `cell-fill` carries no rule: a fill is what a cell does
/// when the sheet says nothing, so the class is not in the scraped set.
pub const CELL_WIDTH_CLASSES: &[&str] = &["cell-content", "cell-fixed", "cell-fill"];

/// Every class saying when a cell of a column drops, including the tier that
/// never does.
///
/// The class is a shrink factor: a table short of room takes the shortfall
/// from the columns worth least.
///
/// Written out, since `cell-keeps`, the tier the narrowing never hides, carries
/// no rule.
pub const CELL_DROP_CLASSES: &[&str] = &["cell-drops-first", "cell-drops-next", "cell-keeps"];

/// The rungs of the `short-N` ladder, in `rem`: the narrowest and widest table
/// width it can say, and the step between two.
///
/// Two `rem` a step, so a table is marked short at most 32px before its
/// essentials stop fitting. A table needing more than the ceiling gets no
/// class.
pub const SHORT_RUNGS: (u16, u16, u16) = (8, 160, 2);

/// The rungs of the `stacks-N` ladder, in `rem`: the width under which a
/// table's rows stop being a grid and draw as stacked records.
///
/// The [`SHORT_RUNGS`] ladder under its own name: a table can carry a rung of
/// each. One that folds its acts into a row menu is short below the
/// width its essentials need with the acts in them, and stacks below the
/// narrower width they need with the acts folded away; the host works out both
/// from the same floors.
pub const STACKS_RUNGS: (u16, u16, u16) = SHORT_RUNGS;

/// How many `rem` of `tiles-N` rungs share one width query: a table carrying
/// any rung up to the next multiple of this tiles below that multiple.
///
/// The tiles ladder takes whatever rung the host's floors land on; the sheet
/// writes one width query per band of this many `rem`, not one per rung.
pub const TILES_STEP: u16 = 16;
const _: () = assert!(
    STACKS_RUNGS.1.is_multiple_of(TILES_STEP),
    "the widest tiles rung closes a group"
);

/// The rungs of the `drop-optional-N` and `drop-secondary-N` ladders, in
/// `rem`: the width under which a table's optional, then its secondary,
/// columns close outright.
///
/// The [`SHORT_RUNGS`] ladder again. A host puts the optional rung at every
/// column's floor added up and the secondary rung at the floors of the
/// essential and secondary columns, the same budget the terminal and egui
/// renderers raise their cutoff by.
pub const DROP_RUNGS: (u16, u16, u16) = SHORT_RUNGS;

/// Every class [`cell_part_class`] can return, including the fallback.
///
/// Written out, as [`ROW_PART_CLASSES`] is.
pub const CELL_PART_CLASSES: &[&str] = &[
    "cell-value",
    "cell-tokens",
    "cell-actions",
    "cell-link",
    "cell-part",
];

/// The class for a row part, by how far forward it stands.
///
/// [`Prominence`] is `#[non_exhaustive]`, so a member added upstream does not stop
/// this compiling.
///
/// A member added upstream lands here as a bare `row-part`, which the sheet
/// lets shrink like its siblings and otherwise leaves plain.
///
/// Public for whichever host builds the row element.
#[must_use]
pub fn part_class(part: Prominence) -> &'static str {
    match part {
        Prominence::Lead => "row-lead",
        Prominence::Support => "row-support",
        Prominence::Quiet => "row-quiet",
        _ => "row-part",
    }
}

/// The class for a cell part.
///
/// [`part_class`]'s table half, for [`CellPart`]. A member added upstream
/// lands as a bare `cell-part` with no rule of its own.
#[must_use]
pub fn cell_part_class(part: CellPart) -> &'static str {
    match part {
        CellPart::Value => "cell-value",
        CellPart::Tokens => "cell-tokens",
        CellPart::Actions => "cell-actions",
        CellPart::Link => "cell-link",
        _ => "cell-part",
    }
}

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

    /// A sizer is one hidden wrapper around the host's copies, and no copies
    /// writes nothing.
    #[test]
    fn a_sizer_wraps_its_copies_and_an_empty_one_writes_nothing() {
        let opts = Emit::default();
        let mut out = String::new();
        push_sizer(&mut out, Markup(""), &opts);
        assert_eq!(out, "");

        push_sizer(&mut out, Markup("<button>Remove</button>"), &opts);
        assert_eq!(
            out,
            "<span class=\"cell-sizer\" aria-hidden=\"true\"><button>Remove</button></span>"
        );
    }

    #[test]
    fn a_column_name_cannot_break_out_of_the_class_attribute() {
        // A name written raw would emit
        // `class="cell col-a" onclick="steal() cell-fill ...">`, a live
        // handler on every cell of the column.
        let mut out = String::new();
        push_column_name(&mut out, "a\" onclick=\"steal()");
        assert_eq!(out, "a--onclick--steal--");
        assert!(!out.contains('"'), "{out}");
    }

    #[test]
    fn the_class_and_the_selector_that_names_it_agree_on_the_name() {
        // The reason the fix is a filter and not an escape: one class, not the
        // two `col-Due date` parses as, and no entity a selector cannot match.
        let mut out = String::new();
        push_column_name(&mut out, "Due date");
        assert_eq!(out, "Due-date");
    }

    #[test]
    fn a_name_already_made_of_identifier_characters_is_untouched() {
        for name in ["description", "due", "progress", "Name", "col_2", "a-b"] {
            let mut out = String::new();
            push_column_name(&mut out, name);
            assert_eq!(out, name);
        }
    }

    #[test]
    fn a_name_outside_ascii_keeps_itself() {
        // CSS identifiers admit everything from U+00A0 up, so folding these to
        // dashes would collide two columns for nothing.
        let mut out = String::new();
        push_column_name(&mut out, "Größe");
        assert_eq!(out, "Größe");
    }
}