//! Column layout and row structure for lists and tables. //! //! The other half of phase B. [`form`](crate::form) renders a field; this //! renders the frame a list of rows sits in: which columns exist, how wide they //! are, which ones survive a narrow viewport, and the cell containers a row is //! made of. //! //! # What this does not do //! //! It does not render a cell's contents. That is the crate's own limit, stated //! in `makeover_layout`'s "Where the description stops": generate the boring //! 80% so the bespoke 20% gets the attention. A goingson task row carries //! delegated action hooks with argument substitution, four nested sub-renderers, //! conditional state classes and aria labels built from data. A description //! expressive enough to emit that is a templating language wearing a //! description's name. //! //! So the split is the one [`Markup`] already draws for forms: this owns the //! structure and the app owns what goes in it. What that removes from an app is //! not small — cell order, cell classes, the grid tracks, and above all the //! narrowing rules, which is where addressing columns by position goes wrong. //! //! # Why positions are the bug //! //! goingson hides its mobile columns with `nth-child(n+5)` against a //! seven-column table, plus a separate `nth-child(3)`, plus two class-based //! rules — the same fact said three ways, two of them positional. Insert a //! column anywhere left of the cut and the wrong one disappears, silently, //! because nothing in the stylesheet knows what column five *is*. //! [`Priority`] is the fix: a renderer narrows by raising a cutoff, and never //! by counting. use crate::form::Markup; use crate::{Emit, class}; use makeover_layout::{Column, Priority, RowPart, Width}; use std::fmt::Write as _; /// The lengths the description deferred. /// /// [`Width`] says `Content`, `Fixed` or `Fill` and deliberately carries no /// magnitude, because a magnitude is a CSS answer and the description is read /// by renderers that have no pixels. So the numbers arrive here instead, the /// way a field's value arrives in [`Filling`](crate::form::Filling) rather than /// in `Field`. /// /// Looked up by column name, because an app's columns are not all one size: /// goingson's task table has six distinct fixed widths. #[derive(Debug, Clone, Copy, Default)] pub struct Sizing<'a> { /// `(column name, CSS length)`. The length is the track for a /// [`Width::Fixed`] column and the floor for a [`Width::Fill`] one. pub lengths: &'a [(&'a str, &'a str)], /// Used for a column with no entry above. Empty means `auto`. pub fallback: &'a str, } impl Sizing<'_> { /// The length for a named column. fn length_for(&self, name: &str) -> &str { self.lengths .iter() .find(|(column, _)| *column == name) .map_or_else( || { if self.fallback.is_empty() { "auto" } else { self.fallback } }, |(_, length)| *length, ) } /// The grid track for one column. fn track(&self, column: &Column<'_>) -> String { match column.width { Width::Content => "max-content".to_owned(), Width::Fixed => self.length_for(column.name).to_owned(), Width::Fill => format!("minmax({}, 1fr)", self.length_for(column.name)), // A width added to the description since this renderer was built. // `auto` is the track that makes no claim, which is the honest // answer to a claim this renderer cannot read. _ => "auto".to_owned(), } } } /// The class a cell of this column carries. /// /// Derived from the column's own name, which is what makes the narrowing rules /// addressable. `data-column` would do as well; a class is what both webview /// apps already key their cell styling on. #[must_use] pub fn column_class(column: &Column<'_>, opts: &Emit) -> String { class(&format!("col-{}", column.name), opts) } /// The `grid-template-columns` value for the columns kept at `cutoff`. /// /// Emitting only the surviving tracks is what keeps the track list and the /// hiding in agreement. An app that hides a cell with `display: none` but /// leaves its track in place gets a column of empty space, which is the other /// half of goingson's mobile bug: its narrow rule drops to four tracks by hand /// and has to be edited in step with the `nth-child` cut. #[must_use] pub fn grid_template_columns( columns: &[Column<'_>], sizing: &Sizing<'_>, cutoff: Priority, ) -> String { columns .iter() .filter(|column| column.kept_at(cutoff)) .map(|column| sizing.track(column)) .collect::>() .join(" ") } /// The rules that narrow `selector` to the columns kept at `cutoff`. /// /// Both halves together: the shortened track list, and `display: none` on each /// dropped column *by its own class*. Nothing counts positions, so inserting a /// column changes what is emitted rather than changing which column vanishes. /// /// `selector` may be a selector list. A descendant is appended to each part /// rather than to the whole, because appending to the whole changes what the /// earlier parts match: `.head, .row > .col-x` reads as "`.head`, or a `.col-x` /// inside `.row`", so `.head` itself would be hidden. #[must_use] pub fn narrowing_css( columns: &[Column<'_>], selector: &str, sizing: &Sizing<'_>, cutoff: Priority, opts: &Emit, ) -> String { let parts: Vec<&str> = selector.split(',').map(str::trim).collect(); let mut css = format!( "{} {{\n grid-template-columns: {};\n}}\n", parts.join(", "), grid_template_columns(columns, sizing, cutoff) ); for column in columns.iter().filter(|c| !c.kept_at(cutoff)) { let class = column_class(column, opts); let targets: Vec = parts .iter() .map(|part| format!("{part} > .{class}")) .collect(); let _ = write!(css, "{} {{\n display: none;\n}}\n", targets.join(",\n")); } css } /// One cell of a row. /// /// The contents are [`Markup`] rather than text, and that is the whole shape of /// this module: a cell holds whatever the app builds, and the app says so by /// naming it. Escaping a cell here would be wrong as well as impossible — a /// task row's description cell is five nested spans and a badge. #[derive(Debug, Clone, Copy)] pub struct Cell<'a> { /// Which column this fills, by name. pub column: &'a str, /// What kind of text it is, when it is text. /// /// Carries the row-part class the stylesheet half already emits, so a /// secondary cell says it is secondary in the description's own words /// rather than in the app's. pub part: Option, /// The contents. Trusted app markup. pub content: Markup<'a>, } impl<'a> Cell<'a> { /// A cell with no row part. #[must_use] pub const fn new(column: &'a str, content: Markup<'a>) -> Self { Self { column, part: None, content, } } } /// The class for a row part. /// /// This comment used to say `RowPart` was the one closed enum left here, and /// that gaining a member would stop this compiling — "the same lockstep break /// `non_exhaustive` was added elsewhere to end". makeover-layout 0.9.0 ended /// it: the enum gained [`RowPart::Tokens`] and `#[non_exhaustive]` in the same /// release, so the prediction was paid off rather than waited for. /// /// The fallback is what that costs. A member added upstream lands here as a /// bare `row-part` with no rule of its own, which is a thing rendering plainly /// rather than a build that stops. Grep this function when adopting a new /// makeover-layout. pub(crate) fn part_class(part: RowPart) -> &'static str { match part { RowPart::Primary => "row-primary", RowPart::Secondary => "row-secondary", RowPart::Meta => "row-meta", RowPart::Actions => "row-actions", RowPart::Tokens => "row-tokens", RowPart::Proportion => "row-proportion", _ => "row-part", } } /// A row's cells, in column order. /// /// Ordered by the columns and not by the cells, so a row cannot silently /// disagree with its table about what comes where. A column with no cell gets /// an empty container, which keeps the grid aligned; a cell naming no column is /// dropped, because there is nowhere to put it. /// /// Emits the cells alone, not the row element. The row carries the app's /// identity and hooks — `data-id`, a context-menu binding, a tabindex, its /// state classes — and none of that is describable here. /// /// # Not for a webview's scroll path /// /// This has no consumer in either webview app, deliberately, and wiring one in /// would be a mistake worth naming. goingson renders rows through a virtual /// scroller whose `_render` calls its row builder **synchronously** while /// scrolling; the code's own comment says scroll events fire at 60Hz+ and that /// this is the hot path. Reaching Rust from there means an IPC round trip and /// an `await` in that loop, per visible range, during a drag. /// /// So this is for the hosts where rendering already happens in Rust: an axum /// route, and the router when it lands. There the objection does not apply, /// because nothing crosses a process boundary to reach it. A webview app should /// take [`narrowing_css`] and [`column_class`] and keep building its own rows. #[must_use] pub fn cells_html(columns: &[Column<'_>], cells: &[Cell<'_>], opts: &Emit) -> String { let cell_class = class("cell", opts); let mut html = String::new(); for column in columns { let found = cells.iter().find(|cell| cell.column == column.name); let mut classes = format!("{cell_class} {}", column_class(column, opts)); if let Some(part) = found.and_then(|cell| cell.part) { let _ = write!(classes, " {}", class(part_class(part), opts)); } let _ = write!( html, "
{}
", found.map_or("", |cell| cell.content.0) ); } html } #[cfg(test)] mod tests { use super::*; fn columns() -> Vec> { vec![ Column { width: Width::Fill, priority: Priority::Essential, ..Column::new("description") }, Column { width: Width::Fixed, priority: Priority::Secondary, ..Column::new("due") }, Column { width: Width::Fixed, priority: Priority::Optional, ..Column::new("progress") }, ] } fn sizing() -> Sizing<'static> { Sizing { lengths: &[ ("description", "200px"), ("due", "110px"), ("progress", "100px"), ], fallback: "", } } #[test] fn a_fill_column_gets_a_floor_and_the_slack() { let tracks = grid_template_columns(&columns(), &sizing(), Priority::Optional); assert_eq!(tracks, "minmax(200px, 1fr) 110px 100px"); } #[test] fn a_column_with_no_length_makes_no_claim() { let sizing = Sizing::default(); let tracks = grid_template_columns(&columns(), &sizing, Priority::Optional); assert_eq!(tracks, "minmax(auto, 1fr) auto auto"); } /// The point of the module. Raising the cutoff drops columns by what they /// are worth, and the track list shortens to match, so the two cannot /// disagree the way a hand-written `nth-child` cut and a hand-written /// track list can. #[test] fn raising_the_cutoff_drops_columns_and_their_tracks_together() { let columns = columns(); let wide = grid_template_columns(&columns, &sizing(), Priority::Optional); assert_eq!(wide.split(' ').count(), 4); // minmax(200px, + 1fr) + 2 let narrow = grid_template_columns(&columns, &sizing(), Priority::Secondary); assert_eq!(narrow, "minmax(200px, 1fr) 110px"); let narrowest = grid_template_columns(&columns, &sizing(), Priority::Essential); assert_eq!(narrowest, "minmax(200px, 1fr)"); } #[test] fn narrowing_hides_a_dropped_column_by_its_own_class_not_its_position() { let css = narrowing_css( &columns(), ".ui-mode-mobile .task-row", &sizing(), Priority::Secondary, &Emit::default(), ); assert!( css.contains("grid-template-columns: minmax(200px, 1fr) 110px;"), "{css}" ); assert!( css.contains(".ui-mode-mobile .task-row > .col-progress {"), "{css}" ); assert!(!css.contains("nth-child"), "{css}"); // The kept columns are not mentioned as hidden. assert!(!css.contains(".col-due {\n display: none"), "{css}"); } /// A selector list has to distribute, or the earlier parts of it get the /// child combinator appended to the whole and start matching things they /// never named. This hid an entire table header the first time it ran. #[test] fn a_selector_list_distributes_the_hidden_column() { let css = narrowing_css( &columns(), ".task-header-row, .task-row", &sizing(), Priority::Secondary, &Emit::default(), ); assert!( css.contains(".task-header-row > .col-progress,\n.task-row > .col-progress {"), "{css}" ); // The bare header selector must never appear as a hiding target. assert!( !css.contains(".task-header-row {\n display: none"), "{css}" ); assert!( css.contains(".task-header-row, .task-row {\n grid-template-columns:"), "{css}" ); } #[test] fn cells_follow_the_columns_and_carry_their_column_class() { let cells = [ Cell { column: "due", part: Some(RowPart::Meta), content: Markup("tomorrow"), }, Cell::new("description", Markup("Ship it")), ]; let html = cells_html(&columns(), &cells, &Emit::default()); // Column order, not cell order: description was passed second. let description = html.find("Ship it").expect("description cell"); let due = html.find("tomorrow").expect("due cell"); assert!(description < due, "{html}"); assert!( html.contains(r#"
"#), "{html}" ); assert!( html.contains(r#"
"#), "{html}" ); // progress had no cell, so it is present and empty rather than absent, // or the grid would shift left by one. assert!( html.contains(r#"
"#), "{html}" ); } #[test] fn a_cell_naming_no_column_is_dropped() { let cells = [Cell::new("nonexistent", Markup("nowhere"))]; let html = cells_html(&columns(), &cells, &Emit::default()); assert!(!html.contains("nowhere"), "{html}"); } #[test] fn the_class_prefix_reaches_the_cells_and_the_narrowing() { let opts = Emit { class_prefix: "mk-", ..Emit::default() }; let cells = [Cell::new("due", Markup("x"))]; assert!( cells_html(&columns(), &cells, &opts).contains("mk-cell mk-col-due"), "prefix missing" ); assert!( narrowing_css(&columns(), ".t", &sizing(), Priority::Secondary, &opts) .contains(".mk-col-progress"), "prefix missing" ); } }