#![forbid(unsafe_code)]
use std::fmt::Write as _;
pub const DEFAULT_BASE_PX: u16 = 16;
pub const BASE_TOKEN: &str = "geometry-base";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Ratio {
pub numerator: u16,
pub denominator: u16,
}
impl Ratio {
#[must_use]
pub const fn px_at(self, base_px: u16) -> u16 {
let (n, d) = (self.numerator as u32, self.denominator as u32);
let scaled = base_px as u32 * n;
((scaled * 2 + d) / (d * 2)) as u16
}
#[must_use]
pub fn scale(self, base: f32) -> f32 {
base * f32::from(self.numerator) / f32::from(self.denominator)
}
#[must_use]
pub fn quanta(self, base: f32, quantum: f32) -> u32 {
if !quantum.is_finite() || quantum <= 0.0 || !base.is_finite() {
return 0;
}
let exact = self.scale(base) / quantum;
if exact <= 0.0 {
0
} else {
exact.round() as u32
}
}
#[must_use]
pub fn quantize(self, base: f32, quantum: f32) -> f32 {
if !quantum.is_finite() || quantum <= 0.0 || !base.is_finite() {
return 0.0;
}
self.quanta(base, quantum) as f32 * quantum
}
#[must_use]
pub fn css(self) -> String {
match (self.numerator, self.denominator) {
(n, d) if n == d => format!("var(--{BASE_TOKEN})"),
(n, 1) => format!("calc(var(--{BASE_TOKEN}) * {n})"),
(n, d) => format!("calc(var(--{BASE_TOKEN}) * {n} / {d})"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Surface {
pub base: f32,
pub quantum: f32,
}
impl Surface {
#[must_use]
pub fn web() -> Self {
Self {
base: f32::from(DEFAULT_BASE_PX),
quantum: 1.0,
}
}
#[must_use]
pub fn terminal() -> Self {
Self {
base: 1.0,
quantum: 1.0,
}
}
#[must_use]
pub fn resolve(self, ratio: Ratio) -> f32 {
ratio.quantize(self.base, self.quantum)
}
#[must_use]
pub fn quanta(self, ratio: Ratio) -> u32 {
ratio.quanta(self.base, self.quantum)
}
#[must_use]
pub fn gap(self, gap: Gap, density: Density) -> u32 {
self.quanta(gap.step_at(density).ratio())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Density {
#[default]
Pointer,
Touch,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Gap {
Bound,
Peer,
Group,
Section,
Pane,
Page,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Step {
Hair,
Tight,
Snug,
Base,
Roomy,
Wide,
Loose,
Broad,
Vast,
Colossal,
}
impl Step {
#[must_use]
pub const fn ratio(self) -> Ratio {
let (numerator, denominator) = match self {
Self::Hair => (1, 8),
Self::Tight => (1, 4),
Self::Snug => (3, 8),
Self::Base => (1, 2),
Self::Roomy => (5, 8),
Self::Wide => (3, 4),
Self::Loose => (1, 1),
Self::Broad => (3, 2),
Self::Vast => (2, 1),
Self::Colossal => (3, 1),
};
Ratio {
numerator,
denominator,
}
}
#[must_use]
pub const fn px(self) -> u16 {
self.ratio().px_at(DEFAULT_BASE_PX)
}
#[must_use]
pub const fn token(self) -> &'static str {
match self {
Self::Hair => "step-hair",
Self::Tight => "step-tight",
Self::Snug => "step-snug",
Self::Base => "step-base",
Self::Roomy => "step-roomy",
Self::Wide => "step-wide",
Self::Loose => "step-loose",
Self::Broad => "step-broad",
Self::Vast => "step-vast",
Self::Colossal => "step-colossal",
}
}
#[must_use]
pub const fn all() -> [Self; 10] {
[
Self::Hair,
Self::Tight,
Self::Snug,
Self::Base,
Self::Roomy,
Self::Wide,
Self::Loose,
Self::Broad,
Self::Vast,
Self::Colossal,
]
}
}
impl Gap {
#[must_use]
pub const fn step_at(self, density: Density) -> Step {
match (self, density) {
(Self::Bound, _) => Step::Tight,
(Self::Peer, Density::Pointer) => Step::Snug,
(Self::Peer, Density::Touch) => Step::Roomy,
(Self::Group, Density::Pointer) => Step::Roomy,
(Self::Group, Density::Touch) => Step::Wide,
(Self::Section, Density::Pointer) => Step::Wide,
(Self::Section, Density::Touch) => Step::Loose,
(Self::Pane, Density::Pointer) => Step::Broad,
(Self::Pane, Density::Touch) => Step::Loose,
(Self::Page, Density::Pointer) => Step::Vast,
(Self::Page, Density::Touch) => Step::Broad,
}
}
#[must_use]
pub const fn step(self) -> Step {
self.step_at(Density::Pointer)
}
#[must_use]
pub const fn px_at(self, density: Density) -> u16 {
self.step_at(density).px()
}
#[must_use]
pub const fn px(self) -> u16 {
self.step().px()
}
#[must_use]
pub const fn token(self) -> &'static str {
match self {
Self::Bound => "gap-bound",
Self::Peer => "gap-peer",
Self::Group => "gap-group",
Self::Section => "gap-section",
Self::Pane => "gap-pane",
Self::Page => "gap-page",
}
}
#[must_use]
pub const fn all() -> [Self; 6] {
[
Self::Bound,
Self::Peer,
Self::Group,
Self::Section,
Self::Pane,
Self::Page,
]
}
}
#[must_use]
pub fn scale_css_declarations() -> String {
let mut out = String::new();
let _ = writeln!(
out,
" /* Every size below is a ratio of this. Scale it and the whole\n \
layout scales with it, including for a user who has asked for\n \
larger text. */\n --{BASE_TOKEN}: 1rem;\n"
);
out.push_str(" /* Raw scale. Prefer a --gap-* below; reach here only when\n");
out.push_str(" no relationship describes the distance. */\n");
for step in Step::all() {
let _ = writeln!(out, " --{}: {};", step.token(), step.ratio().css());
}
out
}
#[must_use]
pub fn gap_css_declarations(density: Density) -> String {
let mut out = String::new();
for gap in Gap::all() {
let _ = writeln!(
out,
" --{}: var(--{});",
gap.token(),
gap.step_at(density).token()
);
}
out
}
#[must_use]
pub fn geometry_css_vars(density: Density) -> String {
format!(
":root {{\n{}\n{}}}\n",
scale_css_declarations(),
gap_css_declarations(density)
)
}
#[must_use]
pub fn density_css(explicit_touch: Option<&str>) -> String {
let mut css = geometry_css_vars(Density::Pointer);
css.push_str("\n@media (hover: none), (pointer: coarse) {\n");
for line in gap_css_overrides(":root", Density::Touch).lines() {
css.push_str(" ");
css.push_str(line);
css.push('\n');
}
css.push_str("}\n");
if let Some(selector) = explicit_touch {
css.push_str("\n/* An explicit user choice, last so it wins over detection. */\n");
css.push_str(&gap_css_overrides(selector, Density::Touch));
}
css
}
#[must_use]
pub fn gap_css_overrides(selector: &str, density: Density) -> String {
format!("{selector} {{\n{}}}\n", gap_css_declarations(density))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn density_is_selected_by_capability_not_by_width_or_agent() {
let css = density_css(None);
assert!(css.contains("@media (hover: none), (pointer: coarse)"));
assert!(!css.contains("max-width"), "a breakpoint crept in");
assert!(!css.contains("min-width"), "a breakpoint crept in");
assert!(!css.contains("ui-mode"), "a device mode crept in");
}
#[test]
fn an_explicit_choice_is_emitted_after_the_detection() {
let css = density_css(Some(".ui-mode-mobile"));
let media = css.find("@media").expect("media query");
let explicit = css.find(".ui-mode-mobile").expect("explicit selector");
assert!(explicit > media, "the explicit selector must come last");
}
#[test]
fn without_an_explicit_selector_there_are_exactly_two_presets() {
assert_eq!(density_css(None).matches("--gap-peer").count(), 2);
}
#[test]
fn the_hig_relationships_land_on_the_hig_values() {
assert_eq!(Gap::Bound.px(), 4);
assert_eq!(Gap::Peer.px(), 6);
assert_eq!(Gap::Group.px(), 10);
assert_eq!(Gap::Section.px(), 12);
}
#[test]
fn every_ratio_divides_the_default_base_exactly() {
for step in Step::all() {
let r = step.ratio();
assert_eq!(
u32::from(DEFAULT_BASE_PX) * u32::from(r.numerator) % u32::from(r.denominator),
0,
"{step:?} is fractional at the default base"
);
}
}
#[test]
fn ratios_scale_linearly() {
for step in Step::all() {
assert_eq!(
step.ratio().px_at(DEFAULT_BASE_PX * 2),
step.px() * 2,
"{step:?} does not double with the base"
);
}
}
#[test]
fn steps_ascend_and_never_repeat() {
let px: Vec<u16> = Step::all().iter().map(|s| s.px()).collect();
let mut sorted = px.clone();
sorted.sort_unstable();
sorted.dedup();
assert_eq!(px, sorted, "steps must be strictly ascending");
}
#[test]
fn gaps_ascend_with_their_relationships_at_every_density() {
for density in [Density::Pointer, Density::Touch] {
let px: Vec<u16> = Gap::all().iter().map(|g| g.px_at(density)).collect();
let mut sorted = px.clone();
sorted.sort_unstable();
assert_eq!(px, sorted, "{density:?}: a looser relationship is tighter");
}
}
#[test]
fn touch_separates_targets_and_tightens_shells() {
for gap in [Gap::Peer, Gap::Section] {
assert!(
gap.px_at(Density::Touch) > gap.px_at(Density::Pointer),
"{gap:?} must open up for a fingertip"
);
}
for gap in [Gap::Pane, Gap::Page] {
assert!(
gap.px_at(Density::Touch) < gap.px_at(Density::Pointer),
"{gap:?} must tighten on a small screen"
);
}
assert_eq!(
Gap::Bound.px_at(Density::Touch),
Gap::Bound.px_at(Density::Pointer),
"bound things stay bound"
);
}
#[test]
fn a_terminal_resolves_the_vocabulary_to_whole_cells() {
let t = Surface::terminal();
let cells: Vec<u32> = Gap::all()
.iter()
.map(|g| t.gap(*g, Density::Pointer))
.collect();
assert_eq!(cells, vec![0, 0, 1, 1, 2, 2]);
}
#[test]
fn collapsing_is_allowed_but_inverting_is_not() {
for quantum in [0.5_f32, 1.0, 2.0, 3.0, 7.0] {
for density in [Density::Pointer, Density::Touch] {
let s = Surface {
base: 16.0,
quantum,
};
let v: Vec<u32> = Gap::all().iter().map(|g| s.gap(*g, density)).collect();
let mut sorted = v.clone();
sorted.sort_unstable();
assert_eq!(v, sorted, "quantum {quantum} {density:?} inverted: {v:?}");
}
}
}
#[test]
fn the_web_surface_agrees_with_the_pixel_helper() {
let w = Surface::web();
for step in Step::all() {
assert_eq!(
w.resolve(step.ratio()) as u16,
step.px(),
"{step:?} disagrees between surface and px_at"
);
}
}
#[test]
fn quantising_is_monotonic_in_the_ratio() {
let (base, quantum) = (16.0, 1.0);
let mut previous = 0;
for step in Step::all() {
let q = step.ratio().quanta(base, quantum);
assert!(q >= previous, "{step:?} went backwards");
previous = q;
}
}
#[test]
fn a_degenerate_quantum_yields_nothing_rather_than_panicking() {
let r = Step::Loose.ratio();
for bad in [0.0_f32, -1.0, f32::NAN] {
assert_eq!(r.quanta(16.0, bad), 0);
assert!(r.quantize(16.0, bad).abs() < f32::EPSILON);
}
assert_eq!(r.quanta(f32::INFINITY, 1.0), 0);
}
#[test]
fn px_at_rounds_rather_than_truncating() {
assert_eq!(Step::Snug.ratio().px_at(15), 6);
assert_eq!(Step::Snug.ratio().px_at(DEFAULT_BASE_PX), 6);
}
#[test]
fn tokens_are_unique() {
let mut names: Vec<&str> = Step::all().iter().map(|s| s.token()).collect();
names.extend(Gap::all().iter().map(|g| g.token()));
let count = names.len();
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), count, "token names collide");
}
#[test]
fn css_is_expressed_over_the_base_never_in_pixels() {
let css = geometry_css_vars(Density::Pointer);
assert!(css.starts_with(":root {\n"));
assert!(css.trim_end().ends_with('}'));
assert!(css.contains("--geometry-base: 1rem;"));
for step in Step::all() {
let line = format!("--{}: {}", step.token(), step.ratio().css());
assert!(css.contains(&line), "missing or wrong: {line}");
}
let scale = scale_css_declarations();
assert!(
!scale.contains("px;"),
"the scale must not emit pixel literals:\n{scale}"
);
}
#[test]
fn ratio_css_drops_redundant_arithmetic() {
assert_eq!(Step::Loose.ratio().css(), "var(--geometry-base)");
assert_eq!(Step::Vast.ratio().css(), "calc(var(--geometry-base) * 2)");
assert_eq!(
Step::Snug.ratio().css(),
"calc(var(--geometry-base) * 3 / 8)"
);
}
#[test]
fn gaps_reference_steps_rather_than_repeating_values() {
let css = geometry_css_vars(Density::Pointer);
assert!(css.contains("--gap-peer: var(--step-snug);"));
assert!(!css.contains("--gap-peer: calc"));
}
#[test]
fn a_density_override_emits_only_the_relational_layer() {
let css = gap_css_overrides(".ui-mode-mobile", Density::Touch);
assert!(css.contains("--gap-peer: var(--step-roomy);"));
let declared: Vec<&str> = css
.lines()
.filter_map(|l| l.trim().strip_prefix("--"))
.filter_map(|l| l.split(':').next())
.collect();
assert!(
declared.iter().all(|t| t.starts_with("gap-")),
"only the relational layer may be overridden, got {declared:?}"
);
}
}