Skip to main content

makeover_geometry/
lib.rs

1//! The invariant half of the make-family design system.
2//!
3//! <!-- wiki: makeover-geometry -->
4//!
5//! [`makeover`] resolves colour, which varies by theme. This crate carries
6//! everything that does not: spacing, radius, edge width, the type scale, and the window
7//! size classes and input densities those resolve against. The rule is that
8//! *a theme overrides colour tokens only*, so the geometry every consumer
9//! shares lives here once.
10//!
11//! [`makeover`]: https://docs.rs/makeover
12//!
13//! # Spacing is relational, not numeric
14//!
15//! The Mac OS 8 Human Interface Guidelines specify white space by *what two
16//! things are being separated*, never by a size name, and define no base grid
17//! unit. A control and its satellite pop-up are set 4 pixels apart; peers
18//! stacked in a list get 6; a group box's inner margin is 10; separated groups
19//! and rows of push buttons get 12.
20//!
21//! That vocabulary is the primary interface here. [`Gap`] names the
22//! relationship and the size follows from it, exactly as `surface-raised`
23//! names an intent and the hex follows from it. The raw [`Step`] scale exists
24//! underneath for distances a relationship does not describe, but reaching for
25//! it is a smell worth a second look.
26//!
27//! Naming the relationship is what makes the rule reviewable. Whether a gap
28//! should be 6px or 8px is unanswerable in isolation; whether two things are
29//! peers is not.
30//!
31//! # Ratios, not pixel counts
32//!
33//! This is the deliberate departure from the HIG, which is specified in hard
34//! device pixels because in 1997 there was one pixel density and one text
35//! size. Every [`Step`] here is a [`Ratio`] of a single base unit, so the
36//! whole system scales from one knob: `--geometry-base`, `1rem` by default.
37//!
38//! At the default base the ratios land exactly on the HIG's numbers (`Snug` is
39//! three eighths of 16px, which is 6px), so nothing is lost in the
40//! translation. What is gained is that the layout tracks the user's text size
41//! instead of fighting it, an accessibility setting becomes one value rather
42//! than a sweep, and the scale means the same thing at any display density.
43//!
44//! # Type is relational too
45//!
46//! [`Text`] names what a piece of text is (body, note, head) and the size
47//! follows, exactly as [`Gap`] names what is being separated. It is the same
48//! argument: whether a caption should be 13px or 14px cannot be reviewed,
49//! whether a piece of text is a caption can.
50//!
51//! Type has its own rungs rather than reusing [`Step`], because the spacing
52//! scale is eighths of the base to match the HIG's distances and a type ramp
53//! wants different fractions. What the two axes share is the base, so the
54//! reader's root font size moves the text and the space around it together.
55//!
56//! Unlike spacing, type does not move with [`Density`]. The reason is in
57//! [`Text`], and it is the same one that keeps shells out of the touch preset.
58//!
59//! # Corners, same move again
60//!
61//! [`Radius`] names what the corner belongs to. The scale is deliberately the
62//! shortest of the three, because rounding carries one bit of meaning (whether
63//! the thing is meant to be pressed), and a long radius scale is one
64//! nobody can choose from. `Square` is a rung rather than the absence of one,
65//! so a container can state that it is square and a reader can tell that from
66//! a rule nobody wrote.
67//!
68//! # Edges, and the one axis that does not scale
69//!
70//! [`Stroke`] names what an edge says: it separates two surfaces, or it is
71//! there to be noticed. Two rungs, 1px and 2px, and in device pixels rather
72//! than ratios of the base, because a browser snaps a border to whole pixels
73//! and a scaled hairline draws as the same 1px with the ratio to its heavier
74//! rung blurred.
75//!
76//! # Density presets
77//!
78//! Naming relationships instead of sizes is what makes a density preset
79//! possible at all. [`Density`] changes what each relationship resolves to
80//! without touching a single call site, because no call site names a size.
81//! The mobile and desktop builds of a Tauri app should differ mostly by which
82//! preset they emit, not by a parallel set of hand-written mode-scoped rules.
83//!
84//! ## What Touch is a claim about
85//!
86//! Touch is a claim about the **contact patch and nothing else**. A fingertip
87//! is coarse where a cursor hotspot is a point, and the only consequence of
88//! that is mis-tap cost: when two adjacent things do different things, an
89//! imprecise contact needs more room between them to land on the intended one.
90//!
91//! Shells are not tap targets. Panel padding and the outer page margin separate
92//! a region from the edge of the screen, and no amount of coarseness in the
93//! pointing device makes that separation riskier. So **Touch opens the gaps
94//! that separate targets and leaves the shells exactly where Pointer put
95//! them**:
96//!
97//! | Gap | Pointer | Touch | why |
98//! |---|---|---|---|
99//! | bound | 4 | 4 | not a separation at all |
100//! | peer | 6 | 10 | adjacent distinct targets, the whole point |
101//! | group | 10 | 12 | holds the peer/group distinction open |
102//! | section | 12 | 16 | a deliberate break stays legible as one |
103//! | pane | 24 | 24 | a shell is not a target |
104//! | page | 32 | 32 | a shell is not a target |
105//!
106//! A Touch preset must never *tighten* `Pane` or `Page` on the argument that
107//! outer margin is screen you do not get. **That is a claim about screen
108//! budget, not about the input device.** Opening `Section` to 16 while
109//! tightening `Pane` below it makes any Pointer `Pane` at or under 16 an
110//! inversion, so a derived preset silently sets a floor under the one quoted
111//! from the HIG. A phone is small *and* touch; a tablet and a touchscreen
112//! laptop are big and touch. Screen budget is a separate axis and does not
113//! belong here.
114//!
115//! ## The one cross-density rule
116//!
117//! **Touch never resolves tighter than Pointer**, at any gap. Stated as a
118//! deliberate claim rather than inherited, and chosen for its direction: it
119//! constrains the *derived* preset by the *quoted* one, never the reverse. A
120//! Pointer retune downward moves freely and cannot be blocked by Touch. Only a
121//! Pointer move upward can push
122//! Touch, and that is the correct direction of authority.
123//!
124//! # Size class: the axis Density kept being asked to carry
125//!
126//! [`SizeClass`] answers **how much screen there is**, which is not the same
127//! question as what is pointing at it. A phone is small and touch; a tablet and
128//! a touchscreen laptop are big and touch; a half-width desktop window is small
129//! and pointer. Four real combinations, and one axis cannot name them.
130//!
131//! This is the home for the claim *outer margin is screen you do not get*. On
132//! the input device it lets a derived preset set a floor under a quoted one;
133//! here it is correct.
134//!
135//! Boundaries are **quoted** (Material 3 window size classes: 600 and 840)
136//! rather than derived, for the same reason the [`Gap`] values are. This crate
137//! carries the boundaries only; what appears or disappears at each is a product
138//! decision and belongs to `makeover-touch`.
139//!
140//! Size class feeds [`Gap::step_at_size`], and only the two shells listen to
141//! it: `pane` and `page` come down one step on a compact window. That is where
142//! "outer margin is screen you don't get" belongs. It does not belong in the
143//! Pointer preset, which would be the same mistake one axis over.
144//!
145//! # Surfaces, and why a TUI is not a third density
146//!
147//! [`Surface`] is the fourth axis and the one that carries this to a terminal. A
148//! terminal is not a density preset; it is a surface whose smallest
149//! representable step is one cell rather than one pixel. Give
150//! [`Ratio::quanta`] a quantum and it answers in whole units of it, so the
151//! relational vocabulary crosses to a character grid with nothing added.
152//!
153//! Quantising is not a terminal special case either: a display quantises to
154//! the pixel. It is only that rounding 6.0 to the nearest pixel is
155//! uninteresting, while rounding three eighths of a cell to the nearest cell
156//! decides the layout.
157//!
158//! On [`Surface::terminal`] the pointer preset resolves to 0, 0, 1, 1, 2, 2
159//! cells. `Bound` and `Peer` collapsing to nothing is correct rather than lossy:
160//! in a grid that dense, both relationships are expressed by adjacency. A
161//! coarse surface genuinely has fewer distinctions available, and the model
162//! should say so instead of inventing a gap to keep six names distinct.
163//!
164//! So the three axes are: [`Gap`] is what is being separated, [`Density`] is
165//! who is operating it, [`Surface`] is what it is drawn on.
166
167#![forbid(unsafe_code)]
168
169use std::fmt::Write as _;
170
171/// The default base unit in CSS pixels, at a 16px root font size.
172pub const DEFAULT_BASE_PX: u16 = 16;
173
174/// The CSS custom property every ratio scales from.
175pub const BASE_TOKEN: &str = "geometry-base";
176
177/// The least a pointer target may measure on a side.
178///
179/// WCAG 2.5.8 and the Macintosh HIG both put the floor at 24 CSS pixels, which
180/// is [`Step::Broad`] at the default base. Named rather than written as a
181/// number so a renderer spends the scale it already has: a second 24 in the
182/// system is a second thing to keep in step with the first.
183///
184/// This is a floor on the *contact patch*, not on the type. Growing the text to
185/// reach it is the wrong fix and belongs to nobody: see wiki
186/// `typography-standard`, which owns the sizes.
187///
188/// Two things it deliberately does not say. It is not density-aware: a finger
189/// wants nearer 44, and expressing that needs [`Density`] threaded through the
190/// emitters, which they do not take today. And it does not reach a link inside
191/// running prose, which must not grow, because a floor applied to every inline
192/// anchor would set the leading of any paragraph carrying one.
193pub const TARGET_LEAST: Step = Step::Broad;
194
195/// A fraction of the base unit.
196///
197/// Rational rather than floating point so the scale is exact, comparable and
198/// usable in a `const`. At the default base every ratio below divides evenly.
199#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
200pub struct Ratio {
201    /// Top of the fraction.
202    pub numerator: u16,
203    /// Bottom of the fraction. Never zero for any ratio this crate defines.
204    pub denominator: u16,
205}
206
207impl Ratio {
208    /// Resolve against a base measured in whole pixels, rounding to nearest.
209    ///
210    /// Integer maths throughout, and exact for every [`Step`] at
211    /// [`DEFAULT_BASE_PX`] because the scale is eighths. This is
212    /// [`Self::quanta`] with a quantum of one pixel, kept separate only so the
213    /// common case stays `const`.
214    ///
215    /// Saturates at `u16::MAX` rather than wrapping, and a zero denominator
216    /// yields `0`, which is [`Self::quanta`]'s answer to a caller error too:
217    /// the fields are public, so a ratio this crate never defined can reach
218    /// here.
219    #[must_use]
220    pub const fn px_at(self, base_px: u16) -> u16 {
221        let (n, d) = (self.numerator as u64, self.denominator as u64);
222        if d == 0 {
223            return 0;
224        }
225        // u64 holds u16 * u16 * 2 with room to spare, so nothing here wraps.
226        // Round half away from zero without leaving integer arithmetic.
227        let px = (base_px as u64 * n * 2 + d) / (d * 2);
228        if px > u16::MAX as u64 {
229            u16::MAX
230        } else {
231            px as u16
232        }
233    }
234
235    /// Resolve against an arbitrary base, keeping the fraction.
236    ///
237    /// The exact value, before any surface gets a say. Prefer
238    /// [`Surface::resolve`] unless you specifically want the unsnapped number.
239    ///
240    /// A zero denominator yields `0`, matching [`Self::px_at`]: the fields are
241    /// public, so a ratio this crate never defined can reach here.
242    #[must_use]
243    pub fn scale(self, base: f32) -> f32 {
244        if self.denominator == 0 {
245            return 0.0;
246        }
247        base * f32::from(self.numerator) / f32::from(self.denominator)
248    }
249
250    /// How many whole quanta this ratio is worth on a surface whose smallest
251    /// representable step is `quantum`.
252    ///
253    /// The generalisation of "round to a pixel". A display quantises to one
254    /// pixel and the answer is usually uninteresting; a terminal quantises to
255    /// one cell and the answer is the whole design. Rounds to nearest, and
256    /// does not floor at one: a gap that lands below half a quantum should
257    /// collapse to nothing, because on that surface it *is* nothing.
258    ///
259    /// A `quantum` that is zero, negative or not finite yields `0` rather than
260    /// panicking or returning infinity. A surface with no smallest step is a
261    /// caller error, not a layout to guess at. A ratio with a zero denominator
262    /// yields `0` too, as in [`Self::px_at`].
263    #[must_use]
264    pub fn quanta(self, base: f32, quantum: f32) -> u32 {
265        if !quantum.is_finite() || quantum <= 0.0 || !base.is_finite() || self.denominator == 0 {
266            return 0;
267        }
268        let exact = self.scale(base) / quantum;
269        if exact <= 0.0 {
270            0
271        } else {
272            // `as` saturates at the integer bound, so a wild base cannot wrap.
273            exact.round() as u32
274        }
275    }
276
277    /// Resolve against a base and snap to a whole number of `quantum`.
278    ///
279    /// The value [`Self::quanta`] counts, back in the surface's own units.
280    /// Guards the degenerate quantum in its own right rather than leaning on
281    /// [`Self::quanta`]: a count of zero times a non-finite quantum is NaN,
282    /// not zero.
283    #[must_use]
284    pub fn quantize(self, base: f32, quantum: f32) -> f32 {
285        if !quantum.is_finite() || quantum <= 0.0 || !base.is_finite() {
286            return 0.0;
287        }
288        self.quanta(base, quantum) as f32 * quantum
289    }
290
291    /// The CSS value, as an expression over [`BASE_TOKEN`].
292    ///
293    /// A whole multiple of the base emits without a division, and 1:1 emits
294    /// the bare `var()`, because `calc(var(--geometry-base) * 1 / 1)` is noise.
295    ///
296    /// A zero denominator emits `0`, matching [`Self::px_at`] and
297    /// [`Self::quanta`]; the `n == d` arm would otherwise read `0 / 0` as the
298    /// whole base.
299    #[must_use]
300    pub fn css(self) -> String {
301        let (n, d) = (self.numerator, self.denominator);
302        if d == 0 {
303            return format!("calc(var(--{BASE_TOKEN}) * 0)");
304        }
305        match (n, d) {
306            (n, d) if n == d => format!("var(--{BASE_TOKEN})"),
307            (n, 1) => format!("calc(var(--{BASE_TOKEN}) * {n})"),
308            (n, d) => format!("calc(var(--{BASE_TOKEN}) * {n} / {d})"),
309        }
310    }
311}
312
313/// What the layout is being drawn on: a base unit, and the smallest step the
314/// surface can actually represent.
315///
316/// Both are in the surface's own units, and the crate never assumes those are
317/// pixels. A display measures in pixels and can represent one of them; a
318/// terminal measures in cells and cannot represent less than one. That single
319/// difference is the whole of the terminal story. A TUI is not a density; it
320/// is a surface with a coarse quantum, and the relational vocabulary above
321/// crosses over untouched.
322///
323/// Quantising is not a terminal special case. A display does it too; it is
324/// just that rounding 6.0 to the nearest pixel is uninteresting, whereas
325/// rounding three eighths of a cell to the nearest cell is a design decision
326/// the surface makes for you.
327#[derive(Debug, Clone, Copy, PartialEq)]
328pub struct Surface {
329    /// The base unit, in this surface's units.
330    pub base: f32,
331    /// The smallest step this surface can represent, in the same units.
332    pub quantum: f32,
333}
334
335impl Surface {
336    /// A display measuring in CSS pixels: a 16px base, one-pixel quantum.
337    #[must_use]
338    pub fn web() -> Self {
339        Self {
340            base: f32::from(DEFAULT_BASE_PX),
341            quantum: 1.0,
342        }
343    }
344
345    /// A terminal measuring in cells: a one-cell base, one-cell quantum.
346    ///
347    /// The coarsest surface in the family, and the one that proves the
348    /// vocabulary. `bound` and `peer` collapse to no cells at all, which is
349    /// correct: in a grid this dense, "belongs to" and "is a peer of" are
350    /// both expressed by adjacency, not by a gap.
351    #[must_use]
352    pub fn terminal() -> Self {
353        Self {
354            base: 1.0,
355            quantum: 1.0,
356        }
357    }
358
359    /// Resolve a ratio on this surface, snapped to its quantum.
360    #[must_use]
361    pub fn resolve(self, ratio: Ratio) -> f32 {
362        ratio.quantize(self.base, self.quantum)
363    }
364
365    /// How many whole quanta a ratio is worth here.
366    ///
367    /// What a cell-addressed layout actually wants: the count, not the size.
368    #[must_use]
369    pub fn quanta(self, ratio: Ratio) -> u32 {
370        ratio.quanta(self.base, self.quantum)
371    }
372
373    /// Resolve a relationship on this surface at a given density, in quanta.
374    ///
375    /// The whole model in one call: *what* is being separated, *who* is
376    /// operating it, *what* it is drawn on.
377    #[must_use]
378    pub fn gap(self, gap: Gap, density: Density) -> u32 {
379        self.quanta(gap.step_at(density).ratio())
380    }
381}
382
383/// Which input the layout is being sized for.
384///
385/// A preset, not a breakpoint, and orthogonal to [`Surface`]: density decides
386/// which step a relationship picks, the surface decides how that step lands.
387/// Which density applies is the app's call, decided once and hung off the
388/// root as a class.
389#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
390pub enum Density {
391    /// Mouse or trackpad. Resolves to the Mac OS 8 HIG's own proportions.
392    #[default]
393    Pointer,
394    /// Finger. Opens the gaps that separate distinct tap targets and leaves
395    /// the shells where Pointer put them, because a coarse contact patch
396    /// raises mis-tap cost and a panel margin is not something you tap. See
397    /// the crate-level "Density presets" section for the derivation.
398    Touch,
399}
400
401impl Density {
402    /// The media condition selecting exactly this density, without the
403    /// `@media`.
404    ///
405    /// A capability question rather than a width or a device, which is the
406    /// policy this crate settles for [`density_css`].
407    ///
408    /// Touch is written as the negation of Pointer, so the two are exact
409    /// complements: every device matches one of them. Written as its own
410    /// feature list, `(hover: none), (pointer: coarse)`, a device reporting
411    /// `(hover: hover)` with `(pointer: none)` matched neither and got no
412    /// density at all.
413    ///
414    /// The two are **not** each other's textual negation, and that is the
415    /// reason they live in one place. Touch is comma-joined, so it is an OR,
416    /// and negating an OR gives an AND with both halves inverted. Deriving one
417    /// from the other by eye is how the pair drifts apart, and it drifts
418    /// silently: a wrong negation still parses, still minifies, and only shows
419    /// up as hover states surviving on a phone.
420    ///
421    /// Pointer's condition is what a renderer wraps a hover rule in.
422    /// `makeover-touch` decides *whether* a hover rule should be gated;
423    /// this decides what the gate is spelled as.
424    #[must_use]
425    pub const fn media_condition(self) -> &'static str {
426        match self {
427            Self::Pointer => "(hover: hover) and (pointer: fine)",
428            Self::Touch => "not all and (hover: hover) and (pointer: fine)",
429        }
430    }
431
432    /// The value of [`DENSITY_ATTRIBUTE`] that chooses exactly this density.
433    ///
434    /// Also the spelling a host persists the choice under, so a webview and
435    /// an egui host reading one stored preference agree on what it says.
436    #[must_use]
437    pub const fn attribute_value(self) -> &'static str {
438        match self {
439            Self::Pointer => "pointer",
440            Self::Touch => "touch",
441        }
442    }
443
444    /// Read back what [`attribute_value`](Self::attribute_value) wrote.
445    ///
446    /// Anything else, including an empty string, is no choice: the host
447    /// keeps the detected density.
448    #[must_use]
449    pub fn from_attribute_value(value: &str) -> Option<Self> {
450        [Self::Pointer, Self::Touch]
451            .into_iter()
452            .find(|d| d.attribute_value() == value)
453    }
454}
455
456/// The root-element attribute a user's density choice is written to.
457///
458/// Detection is a default rather than a verdict: a touchscreen laptop wants
459/// to be told it is a pointer machine, and someone with a mouse may still
460/// want roomier targets. [`density_css`] emits a block for each value of this
461/// attribute on `:root`, after the capability query, so setting
462/// `data-density="pointer"` or `data-density="touch"` on `<html>` wins over
463/// what the device reports in either direction, and removing it hands the
464/// choice back to detection.
465///
466/// The choice belongs to the device rather than the account, for the reason
467/// detection does: it is a claim about what is pointing at this screen.
468pub const DENSITY_ATTRIBUTE: &str = "data-density";
469
470/// How densely a reader wants table rows packed.
471///
472/// Packing is a fact about the reader's eyes and screen, not about what a
473/// description says, so it is a reader setting like [`Density`] and the
474/// description has no word for it. It moves only the row block: the row's
475/// height is the one thing a reader can trade for more rows on screen.
476#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
477pub enum Compactness {
478    /// The model's row: [`ROW_BLOCK`], the height a compact action and a menu
479    /// button both fit.
480    #[default]
481    Comfortable,
482    /// A denser row: [`Step::Broad`] of the base, audiofiles' historical
483    /// row-height default.
484    Compact,
485}
486
487impl Compactness {
488    /// The row block for this packing, as a ratio of the base.
489    #[must_use]
490    pub const fn row_block(self) -> Ratio {
491        match self {
492            Self::Comfortable => ROW_BLOCK,
493            Self::Compact => Step::Broad.ratio(),
494        }
495    }
496
497    /// The value of [`COMPACTNESS_ATTRIBUTE`] that chooses exactly this packing.
498    #[must_use]
499    pub const fn attribute_value(self) -> &'static str {
500        match self {
501            Self::Comfortable => "comfortable",
502            Self::Compact => "compact",
503        }
504    }
505
506    /// Read back what [`attribute_value`](Self::attribute_value) wrote.
507    ///
508    /// Anything else, including an empty string, is no choice: the host keeps
509    /// the comfortable default.
510    #[must_use]
511    pub fn from_attribute_value(value: &str) -> Option<Self> {
512        [Self::Comfortable, Self::Compact]
513            .into_iter()
514            .find(|c| c.attribute_value() == value)
515    }
516}
517
518/// The root-element attribute a reader's row-packing choice is written to.
519///
520/// [`compactness_css`] emits the compact arm of this attribute on `:root`, so
521/// setting `data-compactness="compact"` on `<html>` densens the rows and
522/// removing it hands the choice back to the comfortable default. Like
523/// [`DENSITY_ATTRIBUTE`], it belongs to the device rather than the account.
524pub const COMPACTNESS_ATTRIBUTE: &str = "data-compactness";
525
526/// How much screen there is, independent of what is pointing at it.
527///
528/// The second axis, and the one [`Density`] kept being asked to carry. A phone
529/// is small *and* touch; a tablet and a touchscreen laptop are big and touch; a
530/// half-width window on a desktop is small and pointer. Those are four real
531/// combinations and one axis cannot name them, which is what made the old Touch
532/// preset tighten shells it had no business tightening.
533///
534/// **Boundaries are quoted, not derived**, for the same reason the [`Gap`]
535/// values are: a derived boundary is one nobody can check. They are Material 3's
536/// window size classes, the best-known three-tier split with published numbers.
537/// Apple's size classes are two-tier and expressed as regular/compact per axis,
538/// which does not give a middle to aim at.
539///
540/// Source: <https://m3.material.io/foundations/layout/applying-layout/window-size-classes>
541///
542/// This enum carries the **boundaries only**. What appears, disappears or
543/// reflows at each is a product decision and belongs to `makeover-touch`, not
544/// here, with one exception: shells tighten on a compact window, through
545/// [`Gap::step_at_size`]. That is a look call, so it is eyeballed rather than
546/// derived.
547#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
548pub enum SizeClass {
549    /// Under 600px. Phones in either orientation, and any window narrowed to
550    /// phone width regardless of what is pointing at it.
551    Compact,
552    /// 600px to 839px. Small tablets, split-screen panes, half-width windows.
553    #[default]
554    Medium,
555    /// 840px and up. Laptops, desktops, tablets in landscape.
556    Expanded,
557}
558
559impl SizeClass {
560    /// Lower bound in CSS pixels, inclusive. [`Self::Compact`] starts at zero.
561    #[must_use]
562    pub const fn min_px(self) -> u16 {
563        match self {
564            Self::Compact => 0,
565            Self::Medium => 600,
566            Self::Expanded => 840,
567        }
568    }
569
570    /// The media condition selecting exactly this class, without the `@media`.
571    ///
572    /// Range syntax, so each bound is exclusive on one side and inclusive on
573    /// the other and the three classes partition every width: a rule cannot
574    /// land in two of them, and no width lands in none. `max-width` cannot say
575    /// that, because it is inclusive and a fractional-scaling display reaches
576    /// 599.5px, which `(max-width: 599px)` and `(min-width: 600px)` both miss.
577    #[must_use]
578    pub fn media_condition(self) -> String {
579        match self {
580            Self::Compact => format!("(width < {}px)", Self::Medium.min_px()),
581            Self::Medium => format!(
582                "({}px <= width < {}px)",
583                Self::Medium.min_px(),
584                Self::Expanded.min_px()
585            ),
586            Self::Expanded => format!("(width >= {}px)", Self::Expanded.min_px()),
587        }
588    }
589
590    /// The CSS class name an app may hang off this, without the leading dot.
591    #[must_use]
592    pub const fn token(self) -> &'static str {
593        match self {
594            Self::Compact => "size-compact",
595            Self::Medium => "size-medium",
596            Self::Expanded => "size-expanded",
597        }
598    }
599
600    /// Every class, narrowest first.
601    #[must_use]
602    pub const fn all() -> &'static [Self] {
603        &[Self::Compact, Self::Medium, Self::Expanded]
604    }
605
606    /// The class a given viewport width falls in.
607    #[must_use]
608    pub const fn at_width(px: u16) -> Self {
609        if px >= Self::Expanded.min_px() {
610            Self::Expanded
611        } else if px >= Self::Medium.min_px() {
612            Self::Medium
613        } else {
614            Self::Compact
615        }
616    }
617}
618
619/// A named separation between two things.
620///
621/// Pick by relationship. The size is a consequence of the name, not the other
622/// way round, and callers should never care what it is.
623#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
624pub enum Gap {
625    /// A control and the thing it belongs to: an edit field and its pop-up, a
626    /// checkbox and its label, an icon and the text it labels. Reads as one
627    /// object.
628    Bound,
629    /// Items of the same kind in a list: stacked checkboxes, radio buttons,
630    /// rows, chips in a row. Reads as a set.
631    Peer,
632    /// A container's inner margin, and the distance between sibling groups
633    /// side by side. Reads as "inside this box".
634    Group,
635    /// Separated groups, and rows of actions. The first gap that reads as a
636    /// deliberate break rather than as breathing room.
637    Section,
638    /// Panel padding and content shells. Layout, not controls.
639    Pane,
640    /// The outermost shell margin. One per screen, usually.
641    Page,
642}
643
644/// A raw step on the underlying scale.
645///
646/// Present because not every distance is a relationship between two controls:
647/// an optical nudge inside a badge is not a `Gap`. Prefer [`Gap`] wherever one
648/// fits: a step name says how big, a gap name says why.
649#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
650pub enum Step {
651    /// An eighth of the base. Optical nudges inside small inline elements.
652    Hair,
653    /// A quarter of the base.
654    Tight,
655    /// Three eighths of the base.
656    Snug,
657    /// Half the base.
658    Base,
659    /// Five eighths of the base.
660    Roomy,
661    /// Three quarters of the base.
662    Wide,
663    /// The base itself.
664    Loose,
665    /// One and a half times the base.
666    Broad,
667    /// Twice the base.
668    Vast,
669    /// Three times the base.
670    Colossal,
671}
672
673impl Step {
674    /// This step as a fraction of the base unit.
675    #[must_use]
676    pub const fn ratio(self) -> Ratio {
677        let (numerator, denominator) = match self {
678            Self::Hair => (1, 8),
679            Self::Tight => (1, 4),
680            Self::Snug => (3, 8),
681            Self::Base => (1, 2),
682            Self::Roomy => (5, 8),
683            Self::Wide => (3, 4),
684            Self::Loose => (1, 1),
685            Self::Broad => (3, 2),
686            Self::Vast => (2, 1),
687            Self::Colossal => (3, 1),
688        };
689        Ratio {
690            numerator,
691            denominator,
692        }
693    }
694
695    /// Size in CSS pixels at the default base.
696    #[must_use]
697    pub const fn px(self) -> u16 {
698        self.ratio().px_at(DEFAULT_BASE_PX)
699    }
700
701    /// The CSS custom-property name, without the leading `--`.
702    #[must_use]
703    pub const fn token(self) -> &'static str {
704        match self {
705            Self::Hair => "step-hair",
706            Self::Tight => "step-tight",
707            Self::Snug => "step-snug",
708            Self::Base => "step-base",
709            Self::Roomy => "step-roomy",
710            Self::Wide => "step-wide",
711            Self::Loose => "step-loose",
712            Self::Broad => "step-broad",
713            Self::Vast => "step-vast",
714            Self::Colossal => "step-colossal",
715        }
716    }
717
718    /// Every step, smallest first.
719    #[must_use]
720    pub const fn all() -> &'static [Self] {
721        &[
722            Self::Hair,
723            Self::Tight,
724            Self::Snug,
725            Self::Base,
726            Self::Roomy,
727            Self::Wide,
728            Self::Loose,
729            Self::Broad,
730            Self::Vast,
731            Self::Colossal,
732        ]
733    }
734}
735
736impl Gap {
737    /// The step this relationship resolves to at a given density, on a
738    /// [`SizeClass::Medium`] or wider window.
739    ///
740    /// [`Density::Pointer`]'s values are the HIG's own. [`Density::Touch`]
741    /// opens the three gaps that separate distinct tap targets and holds the
742    /// rest, per the crate-level "Density presets" section.
743    ///
744    /// Shells tighten on a compact window rather than at touch density. Use
745    /// [`Self::step_at_size`] where the window width is known; this is the
746    /// wider-window answer and the one every existing caller already meant.
747    #[must_use]
748    pub const fn step_at(self, density: Density) -> Step {
749        self.step_at_size(density, SizeClass::Medium)
750    }
751
752    /// The step this relationship resolves to at a given density and window
753    /// size class.
754    ///
755    /// Only the two shells move, and only on [`SizeClass::Compact`]: `pane`
756    /// 24 to 16, `page` 32 to 24, one step down each. The four gaps between
757    /// controls do not, because how much room a window has says nothing about
758    /// how far apart two tap targets should be.
759    ///
760    /// **Which axis owns this** (Max). A tighter window edge is a claim about
761    /// screen budget, and smuggling screen budget into the density axis is the
762    /// bug [`SizeClass`] exists to prevent. So the claim goes here and the
763    /// quoted Pointer values hold. Both compact values sit on the eighths
764    /// scale, so no `Step` at 7/8 = 14 is needed.
765    #[must_use]
766    pub const fn step_at_size(self, density: Density, size: SizeClass) -> Step {
767        match self {
768            // Binding is not a separation, so it does not open up on touch
769            // either: separating these would say they are two objects.
770            Self::Bound => Step::Tight,
771
772            // The three that carry mis-tap cost. Peer is the one that matters
773            // most (stacked rows, adjacent chips) and moves furthest; Group
774            // and Section follow only far enough to stay distinct from it.
775            Self::Peer => match density {
776                Density::Pointer => Step::Snug,
777                Density::Touch => Step::Roomy,
778            },
779            Self::Group => match density {
780                Density::Pointer => Step::Roomy,
781                Density::Touch => Step::Wide,
782            },
783            Self::Section => match density {
784                Density::Pointer => Step::Wide,
785                Density::Touch => Step::Loose,
786            },
787
788            // Shells. Not tap targets, so the contact patch has no opinion.
789            // Screen budget is the axis that does, and it is this one.
790            Self::Pane => match size {
791                SizeClass::Compact => Step::Loose,
792                SizeClass::Medium | SizeClass::Expanded => Step::Broad,
793            },
794            Self::Page => match size {
795                SizeClass::Compact => Step::Broad,
796                SizeClass::Medium | SizeClass::Expanded => Step::Vast,
797            },
798        }
799    }
800
801    /// The step this relationship resolves to at the default density.
802    #[must_use]
803    pub const fn step(self) -> Step {
804        self.step_at(Density::Pointer)
805    }
806
807    /// Size in CSS pixels at the default base, at a given density.
808    #[must_use]
809    pub const fn px_at(self, density: Density) -> u16 {
810        self.step_at(density).px()
811    }
812
813    /// Size in CSS pixels at the default base, at a given density and window
814    /// size class.
815    #[must_use]
816    pub const fn px_at_size(self, density: Density, size: SizeClass) -> u16 {
817        self.step_at_size(density, size).px()
818    }
819
820    /// Size in CSS pixels at the default base and density.
821    #[must_use]
822    pub const fn px(self) -> u16 {
823        self.step().px()
824    }
825
826    /// The CSS custom-property name, without the leading `--`.
827    #[must_use]
828    pub const fn token(self) -> &'static str {
829        match self {
830            Self::Bound => "gap-bound",
831            Self::Peer => "gap-peer",
832            Self::Group => "gap-group",
833            Self::Section => "gap-section",
834            Self::Pane => "gap-pane",
835            Self::Page => "gap-page",
836        }
837    }
838
839    /// Every relationship, tightest first.
840    #[must_use]
841    pub const fn all() -> &'static [Self] {
842        &[
843            Self::Bound,
844            Self::Peer,
845            Self::Group,
846            Self::Section,
847            Self::Pane,
848            Self::Page,
849        ]
850    }
851}
852
853/// What a piece of text is, from which its size follows.
854///
855/// The type axis, and the same move [`Gap`] makes on the spacing axis: name
856/// the role and let the size follow, so the choice is reviewable. Whether a
857/// caption should be 13px or 14px is unanswerable in isolation; whether a
858/// piece of text is a caption is not.
859///
860/// # Why the ratios are their own ramp
861///
862/// Type does not reuse [`Step`]. The spacing scale is built in eighths of the
863/// base because that is what the HIG's distances land on, and a type ramp
864/// needs different rungs. 7/8 and 9/8 sit either side of body copy and have
865/// no spacing meaning at all, while `Hair` and `Tight` are far below any
866/// legible size. Sharing the enum would have meant widening it for rungs
867/// spacing never asks for.
868///
869/// What is shared is the thing that matters: every rung here is a [`Ratio`]
870/// of `--geometry-base`, so text tracks the user's chosen root size exactly
871/// as spacing does, and one knob still moves the whole design.
872///
873/// # Why the floor is 3/4
874///
875/// Twelve pixels at the default base, and nothing below it. Sizes under that
876/// are a legibility problem rather than a tier, and a scale that offers one
877/// is a scale that invites it. Text that needs to recede should recede by
878/// colour or weight, which cost no legibility.
879///
880/// # Why type does not shift on touch
881///
882/// [`Density`] is a claim about the contact patch and nothing else, and text
883/// is not a tap target. The reader's own root font size is already the knob
884/// for how large text should be, and it already moves this whole ramp. So the
885/// type axis is density-invariant, and a phone gets the same tiers a desktop
886/// does.
887#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
888pub enum Text {
889    /// Three quarters of the base. Timestamps, badges, legal lines.
890    Fine,
891    /// Seven eighths of the base. Secondary text: metadata, table cells,
892    /// captions, form help.
893    Note,
894    /// The base itself. Running copy, and the size everything else is read
895    /// against.
896    Body,
897    /// Nine eighths of the base. Emphasised copy: intros, card titles.
898    Lead,
899    /// Five quarters of the base. The third heading level.
900    Subhead,
901    /// One and a half times the base. Section headings, the second level.
902    Head,
903    /// Twice the base. The page's own title, the first level.
904    Title,
905    /// Two and a half times the base. Display copy, above the document
906    /// hierarchy rather than at the top of it.
907    Display,
908    /// Three times the base. One per page at most: a landing hero.
909    Hero,
910}
911
912impl Text {
913    /// This role's size as a fraction of the base unit.
914    #[must_use]
915    pub const fn ratio(self) -> Ratio {
916        let (numerator, denominator) = match self {
917            Self::Fine => (3, 4),
918            Self::Note => (7, 8),
919            Self::Body => (1, 1),
920            Self::Lead => (9, 8),
921            Self::Subhead => (5, 4),
922            Self::Head => (3, 2),
923            Self::Title => (2, 1),
924            Self::Display => (5, 2),
925            Self::Hero => (3, 1),
926        };
927        Ratio {
928            numerator,
929            denominator,
930        }
931    }
932
933    /// Size in CSS pixels at the default base.
934    #[must_use]
935    pub const fn px(self) -> u16 {
936        self.ratio().px_at(DEFAULT_BASE_PX)
937    }
938
939    /// The CSS custom-property name, without the leading `--`.
940    #[must_use]
941    pub const fn token(self) -> &'static str {
942        match self {
943            Self::Fine => "text-fine",
944            Self::Note => "text-note",
945            Self::Body => "text-body",
946            Self::Lead => "text-lead",
947            Self::Subhead => "text-subhead",
948            Self::Head => "text-head",
949            Self::Title => "text-title",
950            Self::Display => "text-display",
951            Self::Hero => "text-hero",
952        }
953    }
954
955    /// Every role, smallest first.
956    #[must_use]
957    pub const fn all() -> &'static [Self] {
958        &[
959            Self::Fine,
960            Self::Note,
961            Self::Body,
962            Self::Lead,
963            Self::Subhead,
964            Self::Head,
965            Self::Title,
966            Self::Display,
967            Self::Hero,
968        ]
969    }
970}
971
972/// How rounded a corner is, named for what the corner belongs to.
973///
974/// The third axis to make the same move as [`Gap`] and [`Text`]: name the
975/// thing and let the value follow. Whether a corner should be 3px or 4px is
976/// unanswerable in isolation, and answering it once per component is how a
977/// stylesheet ends up with 2, 3, 4, 6, 8 and 12 all meaning "slightly
978/// rounded".
979///
980/// # Rounding is an affordance
981///
982/// The scale is deliberately short, because a corner radius carries one bit
983/// of meaning: whether the thing is meant to be pressed. [`Self::Square`]
984/// exists as a named rung rather than as the absence of a radius so that a
985/// container states that it is square, and a reader can tell a deliberate
986/// zero from a rule nobody wrote.
987#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
988pub enum Radius {
989    /// No rounding. Containers: cards, panels, dropdowns, page shells.
990    Square,
991    /// An eighth of the base. The tightest corner still visible: inline code,
992    /// small badges, status chips.
993    Fine,
994    /// A quarter of the base. Controls: buttons, inputs, selects.
995    Control,
996    /// Half the base. Surfaces that round rather than sit square: media
997    /// covers, callout boxes, feature cards.
998    Panel,
999    /// A circle, whatever the element's size.
1000    Round,
1001}
1002
1003impl Radius {
1004    /// This corner as a fraction of the base unit.
1005    ///
1006    /// [`Self::Round`] has none, and that is not an oversight: 50% is a
1007    /// proportion of the element's own box rather than of the base, so it
1008    /// does not scale with `--geometry-base` and cannot be written as a
1009    /// [`Ratio`]. Use [`Self::css`], which spells every rung.
1010    #[must_use]
1011    pub const fn ratio(self) -> Option<Ratio> {
1012        let (numerator, denominator) = match self {
1013            Self::Square => (0, 1),
1014            Self::Fine => (1, 8),
1015            Self::Control => (1, 4),
1016            Self::Panel => (1, 2),
1017            Self::Round => return None,
1018        };
1019        Some(Ratio {
1020            numerator,
1021            denominator,
1022        })
1023    }
1024
1025    /// Size in CSS pixels at the default base, or `None` for [`Self::Round`].
1026    #[must_use]
1027    pub const fn px(self) -> Option<u16> {
1028        match self.ratio() {
1029            Some(r) => Some(r.px_at(DEFAULT_BASE_PX)),
1030            None => None,
1031        }
1032    }
1033
1034    /// The CSS value for this rung.
1035    ///
1036    /// `Square` emits a bare `0` rather than a `calc()` that multiplies the
1037    /// base by nothing, and `Round` emits the percentage.
1038    #[must_use]
1039    pub fn css(self) -> String {
1040        match self {
1041            Self::Square => "0".to_owned(),
1042            Self::Round => "50%".to_owned(),
1043            other => other
1044                .ratio()
1045                .expect("every rung but Round has a ratio")
1046                .css(),
1047        }
1048    }
1049
1050    /// The CSS custom-property name, without the leading `--`.
1051    #[must_use]
1052    pub const fn token(self) -> &'static str {
1053        match self {
1054            Self::Square => "radius-square",
1055            Self::Fine => "radius-fine",
1056            Self::Control => "radius-control",
1057            Self::Panel => "radius-panel",
1058            Self::Round => "radius-round",
1059        }
1060    }
1061
1062    /// Every rung, squarest first.
1063    #[must_use]
1064    pub const fn all() -> &'static [Self] {
1065        &[
1066            Self::Square,
1067            Self::Fine,
1068            Self::Control,
1069            Self::Panel,
1070            Self::Round,
1071        ]
1072    }
1073}
1074
1075/// How heavy an edge is, named for what the edge is saying.
1076///
1077/// The fourth axis, and the same move as [`Radius`]: name the thing, let the
1078/// width follow. Measured across the tree before it existed, edges were 1px,
1079/// 2px, 3px and 4px with no token for any of them, and the 3px and 4px ones
1080/// were all the same thing (a status stripe down one side) spelled two ways.
1081///
1082/// # Two rungs
1083///
1084/// An edge says one of two things. Either it separates two surfaces, and wants
1085/// to be the least ink that still reads as a line, or it marks something the
1086/// reader has to notice: a focus ring, a status, a selection. Nothing between
1087/// those is a third meaning, so there is no third rung. `none` is not a rung
1088/// either, unlike [`Radius::Square`]: an absent edge is `border: none`, which
1089/// states itself without a width.
1090///
1091/// # Pixels, not ratios of the base
1092///
1093/// The one axis here that does not scale with `--geometry-base`, and on
1094/// purpose. A browser snaps a border's width to whole device pixels, so a
1095/// hairline at a 20px root would ask for 1.25px and draw 1, while the mark
1096/// would ask for 2.5 and draw 2: the scaling would buy nothing and blur the
1097/// ratio between the rungs. A hairline is the device's own unit of line, and
1098/// stays one at any text size.
1099///
1100/// On a terminal both rungs are one cell edge; the box-drawing set has a
1101/// heavy line for [`Self::Mark`] where the surface can draw it.
1102///
1103/// # Not `--border-*`
1104///
1105/// The tokens are `--stroke-*` because `--border` and `--border-strong` are
1106/// already colour tokens in `makeover`, and `border-strong` beside a
1107/// `border-mark` would read as two halves of one scale when they are two axes.
1108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1109pub enum Stroke {
1110    /// The edge between two surfaces: dividers, rules, input outlines, a
1111    /// bevel's edge. 1px.
1112    Hairline,
1113    /// An edge that has to be noticed: the focus ring, a status stripe, a
1114    /// selected or latched outline. 2px, twice the hairline so the two never
1115    /// read as the same weight.
1116    Mark,
1117}
1118
1119impl Stroke {
1120    /// Width in CSS pixels. The same at every base, for the reason in the
1121    /// type's docs.
1122    #[must_use]
1123    pub const fn px(self) -> u16 {
1124        match self {
1125            Self::Hairline => 1,
1126            Self::Mark => 2,
1127        }
1128    }
1129
1130    /// The CSS value for this rung.
1131    #[must_use]
1132    pub fn css(self) -> String {
1133        format!("{}px", self.px())
1134    }
1135
1136    /// The CSS custom-property name, without the leading `--`.
1137    #[must_use]
1138    pub const fn token(self) -> &'static str {
1139        match self {
1140            Self::Hairline => "stroke-hairline",
1141            Self::Mark => "stroke-mark",
1142        }
1143    }
1144
1145    /// Every rung, lightest first.
1146    #[must_use]
1147    pub const fn all() -> &'static [Self] {
1148        &[Self::Hairline, Self::Mark]
1149    }
1150}
1151
1152/// Which floating surface sits over which, named by what floats.
1153///
1154/// Two roles and no ladder: an overlay is a scrim and the panel in it (a
1155/// modal, a picker that covers the page); a notice is a transient message,
1156/// which stays readable over an open overlay. Everything else stacks in
1157/// document order. Unitless `z-index` values, the same at every density.
1158#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1159pub enum Layer {
1160    /// A scrim over the page and the panel it holds.
1161    Overlay,
1162    /// A transient message, above an open overlay.
1163    Notice,
1164}
1165
1166impl Layer {
1167    /// The `z-index` this role takes.
1168    #[must_use]
1169    pub const fn z(self) -> u16 {
1170        match self {
1171            Self::Overlay => 100,
1172            Self::Notice => 200,
1173        }
1174    }
1175
1176    /// The CSS custom-property name, without the leading `--`.
1177    #[must_use]
1178    pub const fn token(self) -> &'static str {
1179        match self {
1180            Self::Overlay => "layer-overlay",
1181            Self::Notice => "layer-notice",
1182        }
1183    }
1184
1185    /// Every role, lowest first.
1186    #[must_use]
1187    pub const fn all() -> &'static [Self] {
1188        &[Self::Overlay, Self::Notice]
1189    }
1190}
1191
1192/// Emit the stacking roles as CSS declarations, no selector.
1193#[must_use]
1194pub fn layer_css_declarations() -> String {
1195    Layer::all()
1196        .iter()
1197        .map(|l| format!("  --{}: {};\n", l.token(), l.z()))
1198        .collect::<Vec<_>>()
1199        .concat()
1200}
1201
1202/// Emit the base unit and the raw scale as CSS declarations, no selector.
1203///
1204/// Density-invariant: the steps are the vocabulary, and only which step a
1205/// relationship picks changes between presets.
1206#[must_use]
1207pub fn scale_css_declarations() -> String {
1208    let mut out = String::new();
1209    let _ = writeln!(
1210        out,
1211        "  /* Every size below is a ratio of this. Scale it and the whole\n     \
1212         layout scales with it, including for a user who has asked for\n     \
1213         larger text. */\n  --{BASE_TOKEN}: 1rem;\n"
1214    );
1215    out.push_str("  /* Raw scale. Prefer a --gap-* below; reach here only when\n");
1216    out.push_str("     no relationship describes the distance. */\n");
1217    for step in Step::all() {
1218        let _ = writeln!(out, "  --{}: {};", step.token(), step.ratio().css());
1219    }
1220    out
1221}
1222
1223/// Emit the type axis as CSS declarations, no selector.
1224///
1225/// Takes no [`Density`]: text is not a tap target, so the contact patch has no
1226/// opinion on it. See [`Text`] for the derivation.
1227#[must_use]
1228pub fn text_css_declarations() -> String {
1229    let mut out = String::new();
1230    out.push_str("  /* Type. Named for what the text is; the size follows.\n");
1231    out.push_str("     Ratios of the base, so text tracks the reader's own\n");
1232    out.push_str("     root size. Density-invariant: text is not a target. */\n");
1233    for text in Text::all() {
1234        let _ = writeln!(out, "  --{}: {};", text.token(), text.ratio().css());
1235    }
1236    out
1237}
1238
1239/// Emit the corner scale as CSS declarations, no selector.
1240///
1241/// Takes no [`Density`] for the same reason [`text_css_declarations`] does
1242/// not: a corner is not a tap target.
1243#[must_use]
1244pub fn radius_css_declarations() -> String {
1245    let mut out = String::new();
1246    out.push_str("  /* Corners. Rounding says a thing is meant to be pressed,\n");
1247    out.push_str("     so the scale is short on purpose and square is a rung\n");
1248    out.push_str("     rather than the absence of one. */\n");
1249    for radius in Radius::all() {
1250        let _ = writeln!(out, "  --{}: {};", radius.token(), radius.css());
1251    }
1252    out
1253}
1254
1255/// Emit the edge scale as CSS declarations, no selector.
1256///
1257/// Takes no [`Density`]: an edge is not a tap target. Pixel literals, the one
1258/// emitter here that writes them, for the reason on [`Stroke`].
1259#[must_use]
1260pub fn stroke_css_declarations() -> String {
1261    let mut out = String::new();
1262    out.push_str("  /* Edges. Hairline separates, mark is to be noticed.\n");
1263    out.push_str("     Device pixels rather than ratios of the base: a border\n");
1264    out.push_str("     snaps to whole pixels, so scaling it buys nothing. */\n");
1265    for stroke in Stroke::all() {
1266        let _ = writeln!(out, "  --{}: {};", stroke.token(), stroke.css());
1267    }
1268    out
1269}
1270
1271/// The block size of one table row: 45px at the default base.
1272///
1273/// wiki `table-model`: one compact action and a menu button fit a row at this
1274/// size, with both always visible. The renderers apply it as a minimum rather
1275/// than a height, so a row holding more than one line grows. Off the step
1276/// scale on purpose: it is the size the ruled row measures, not a spacing
1277/// relationship, so it is named here once rather than approximated by the
1278/// nearest step in three renderers.
1279pub const ROW_BLOCK: Ratio = Ratio {
1280    numerator: 45,
1281    denominator: 16,
1282};
1283
1284/// The CSS custom-property name [`ROW_BLOCK`] is emitted under, without `--`.
1285pub const ROW_BLOCK_TOKEN: &str = "row-block";
1286
1287/// Emit the named block sizes as CSS declarations, no selector.
1288#[must_use]
1289pub fn block_css_declarations() -> String {
1290    format!("  --{ROW_BLOCK_TOKEN}: {};\n", ROW_BLOCK.css())
1291}
1292
1293/// Emit the relational layer for one density as CSS declarations, no selector.
1294///
1295/// Gaps reference their step rather than repeating a value, so the scale has
1296/// exactly one definition and a reader can see which relationship maps where.
1297#[must_use]
1298pub fn gap_css_declarations(density: Density) -> String {
1299    gap_declarations(Gap::all(), density)
1300}
1301
1302/// The gaps a density preset moves: the three that separate distinct tap
1303/// targets.
1304///
1305/// `Bound` binds two things into one and does not move on touch either. The two
1306/// shells answer to the window size class, so a density override that
1307/// re-declared them would be a claim about screen budget on the wrong axis; it
1308/// would also outrank the compact block, whose `:root` is less specific than an
1309/// attribute selector on the same element.
1310const fn density_varying_gaps() -> &'static [Gap] {
1311    &[Gap::Peer, Gap::Group, Gap::Section]
1312}
1313
1314/// Emit the given relationships as CSS declarations, no selector.
1315fn gap_declarations(gaps: &[Gap], density: Density) -> String {
1316    let mut out = String::new();
1317    for &gap in gaps {
1318        let _ = writeln!(
1319            out,
1320            "  --{}: var(--{});",
1321            gap.token(),
1322            gap.step_at(density).token()
1323        );
1324    }
1325    out
1326}
1327
1328/// The cascade layer every stylesheet the make-family generates is wrapped in.
1329///
1330/// One name shared by every emitter in the family, so an app writes it once and
1331/// the design system's output lands in one place it can order against:
1332///
1333/// ```css
1334/// @layer makeover, base, components, responsive;
1335/// ```
1336///
1337/// # Why a layer at all
1338///
1339/// The cascade resolves origin and importance, then layer, then specificity,
1340/// then source order, and **unlayered normal declarations outrank every named
1341/// layer**. So the moment an app declares any layer of its own, every rule it
1342/// owns loses to unlayered generated CSS regardless of specificity or of
1343/// loading last. Emitting into a layer is what stops that, and putting the name
1344/// here rather than in each app is what stops three apps picking three names.
1345///
1346/// # Why this constant lives in the geometry crate
1347///
1348/// Not because spacing owns it. This crate is the only one every CSS-emitting
1349/// crate in the family already depends on, and it is already the crate that
1350/// spells CSS for the family (`media_condition`, `Step::token`, `Ratio::css`).
1351/// A second copy in `makeover-webview` is exactly the drift
1352/// [`Density::media_condition`] exists to prevent, one layer up.
1353pub const CSS_LAYER: &str = "makeover";
1354
1355/// Wrap generated CSS in [`CSS_LAYER`].
1356///
1357/// Every whole-stylesheet emitter in the family ends with this call. Exposed
1358/// rather than kept private because an app that assembles its own stylesheet
1359/// out of this family's pieces has to put it in the same layer, since rules an
1360/// app generates in its own `build.rs` are as generated as the family's.
1361#[must_use]
1362pub fn in_css_layer(css: &str) -> String {
1363    let mut out = format!("@layer {CSS_LAYER} {{\n");
1364    for line in css.lines() {
1365        // Blank lines stay blank; indenting one leaves trailing whitespace.
1366        if line.is_empty() {
1367            out.push('\n');
1368        } else {
1369            let _ = writeln!(out, "    {line}");
1370        }
1371    }
1372    out.push_str("}\n");
1373    out
1374}
1375
1376/// Emit the whole geometry layer as a `:root { … }` block at one density.
1377///
1378/// Mirrors `makeover::intent_css_vars`. Unlike the colour layer this is
1379/// constant, so a web consumer should bake it in at build time rather than
1380/// apply it from JS on every load.
1381///
1382/// The density argument reaches the gaps only. The scale and the type ramp are
1383/// the same at every density, which is why neither takes one.
1384#[must_use]
1385pub fn geometry_css_vars(density: Density) -> String {
1386    format!(
1387        ":root {{\n{}\n{}\n{}\n{}\n{}\n{}\n{}}}\n",
1388        scale_css_declarations(),
1389        gap_css_declarations(density),
1390        text_css_declarations(),
1391        radius_css_declarations(),
1392        stroke_css_declarations(),
1393        layer_css_declarations(),
1394        block_css_declarations()
1395    )
1396}
1397
1398/// The whole spacing layer with the canonical density selection, as CSS.
1399///
1400/// **Density is a capability, not a device and not a width.** A narrow window
1401/// on a desktop still has a pointer in it and a tablet at full width still has
1402/// a finger, so the touch preset hangs off "not a fine hovering pointer"
1403/// rather than off a breakpoint or a user-agent string. That is the question
1404/// the platform actually answers, and it is the one [`Density`] is asking.
1405///
1406/// A user's choice is [`DENSITY_ATTRIBUTE`] on the root element, honoured in
1407/// both directions: a block per value follows the capability query, so a
1408/// touchscreen laptop can be told it is a pointer machine and a mouse user
1409/// can ask for roomier targets. Neither is visible to a media query.
1410///
1411/// `explicit_touch` is for an app that already carries its own class for the
1412/// touch choice. It is emitted last and wins at equal specificity.
1413///
1414/// Never sniff the user agent for this: that asks what device this is as a
1415/// proxy for a capability the browser already reports.
1416///
1417/// Emitted inside [`CSS_LAYER`]. Custom properties follow the
1418/// ordinary cascade, so unlayered ones outrank layered ones: an app that puts
1419/// its own `:root` overrides in a named layer while this file stayed unlayered
1420/// would find the generated tokens beating the overrides meant to replace them.
1421/// That is the same trap the component sheet had, and it is not visible until
1422/// the app adopts layers.
1423#[must_use]
1424pub fn density_css(explicit_touch: Option<&str>) -> String {
1425    in_css_layer(&density_declarations(explicit_touch))
1426}
1427
1428/// [`density_css`] without the layer wrapper.
1429fn density_declarations(explicit_touch: Option<&str>) -> String {
1430    let mut css = geometry_css_vars(Density::Pointer);
1431    css.push_str("\n/* Touch: targets separate, shells hold. */\n");
1432    css.push_str("@media ");
1433    css.push_str(Density::Touch.media_condition());
1434    css.push_str(" {\n");
1435    for line in gap_css_overrides(":root", Density::Touch).lines() {
1436        css.push_str("    ");
1437        css.push_str(line);
1438        css.push('\n');
1439    }
1440    css.push_str("}\n");
1441    css.push_str("\n/* A user's choice, either way. Higher specificity than the query. */\n");
1442    for density in [Density::Pointer, Density::Touch] {
1443        let selector = format!(
1444            ":root[{DENSITY_ATTRIBUTE}=\"{}\"]",
1445            density.attribute_value()
1446        );
1447        css.push_str(&gap_css_overrides(&selector, density));
1448    }
1449    if let Some(selector) = explicit_touch {
1450        css.push_str("\n/* An explicit user choice, last so it wins over detection. */\n");
1451        css.push_str(&gap_css_overrides(selector, Density::Touch));
1452    }
1453    css
1454}
1455
1456/// The denser-row override for the row block.
1457///
1458/// The comfortable default is [`block_css_declarations`], which writes
1459/// `--row-block` as [`ROW_BLOCK`] in the `:root` block; this emits only the
1460/// compact arm, keyed on [`COMPACTNESS_ATTRIBUTE`]. Unlayered on purpose: a
1461/// reader's explicit packing choice must beat the default wherever the default
1462/// was emitted.
1463///
1464/// ```
1465/// # use makeover_geometry::compactness_css;
1466/// let css = compactness_css();
1467/// assert!(css.contains("--row-block"));
1468/// ```
1469#[must_use]
1470pub fn compactness_css() -> String {
1471    format!(
1472        ":root[{COMPACTNESS_ATTRIBUTE}=\"{}\"] {{\n  --{ROW_BLOCK_TOKEN}: {};\n}}\n",
1473        Compactness::Compact.attribute_value(),
1474        Compactness::Compact.row_block().css()
1475    )
1476}
1477
1478/// Emit the compact-window shell override.
1479///
1480/// The one place this crate is allowed to ask how wide the window is. Density
1481/// must never be selected by width ([`density_css`] has a test forbidding a
1482/// breakpoint from appearing in it at all), because a capability query answers
1483/// "what is pointing at this" and a breakpoint does not. Size class is the
1484/// opposite: width is exactly what it means, so it gets its own emitter and
1485/// its own media query rather than being folded into that file.
1486///
1487/// Only the two shells move, and only below [`SizeClass::Medium`]'s boundary:
1488/// `pane` 24 to 16, `page` 32 to 24. The four gaps between controls are absent
1489/// from the block, so a narrow window never reasons about tap targets.
1490///
1491/// Emitted inside [`CSS_LAYER`] for the same reason [`density_css`] is: an
1492/// unlayered custom property outranks a layered one, so an app that layers its
1493/// own overrides would otherwise lose to this.
1494///
1495/// ```
1496/// # use makeover_geometry::size_class_css;
1497/// let css = size_class_css();
1498/// assert!(css.contains("--gap-pane"));
1499/// assert!(!css.contains("--gap-peer"), "a control gap crept into a width query");
1500/// ```
1501#[must_use]
1502pub fn size_class_css() -> String {
1503    in_css_layer(&size_class_declarations())
1504}
1505
1506/// [`size_class_css`] without the layer wrapper.
1507fn size_class_declarations() -> String {
1508    let mut css = String::new();
1509    css.push_str("/* Compact window: shells tighten. Outer margin is screen you\n");
1510    css.push_str("   don't get, which is a claim about the window and not about\n");
1511    css.push_str("   what is pointing at it, so it lives here and not in the\n");
1512    css.push_str("   density presets. Targets are untouched. */\n");
1513    let _ = writeln!(css, "@media {} {{", SizeClass::Compact.media_condition());
1514    css.push_str("    :root {\n");
1515    for gap in [Gap::Pane, Gap::Page] {
1516        let _ = writeln!(
1517            css,
1518            "        --{}: var(--{});",
1519            gap.token(),
1520            gap.step_at_size(Density::Pointer, SizeClass::Compact)
1521                .token()
1522        );
1523    }
1524    css.push_str("    }\n}\n");
1525    css
1526}
1527
1528/// Emit a density preset as a scoped override block.
1529///
1530/// Only the relational layer is emitted: the scale and the base do not change
1531/// between presets, so an app ships [`geometry_css_vars`] at its default
1532/// density and one of these per mode class it supports. Of the gaps, only
1533/// [`Gap::Peer`], [`Gap::Group`] and [`Gap::Section`] move with the input
1534/// device; [`Gap::Bound`] and the two shells keep the value the base declared,
1535/// so a touch preset never overrides a compact-window shell.
1536///
1537/// ```
1538/// # use makeover_geometry::{Density, gap_css_overrides};
1539/// let css = gap_css_overrides(".ui-mode-mobile", Density::Touch);
1540/// assert!(css.starts_with(".ui-mode-mobile {\n"));
1541/// ```
1542#[must_use]
1543pub fn gap_css_overrides(selector: &str, density: Density) -> String {
1544    format!(
1545        "{selector} {{\n{}}}\n",
1546        gap_declarations(density_varying_gaps(), density)
1547    )
1548}
1549
1550#[cfg(test)]
1551mod tests {
1552    use super::*;
1553
1554    #[test]
1555    fn density_is_selected_by_capability_not_by_width_or_agent() {
1556        let css = density_css(None);
1557        assert!(css.contains("@media not all and (hover: hover) and (pointer: fine)"));
1558        // The three things density must never be selected by.
1559        assert!(!css.contains("width"), "a breakpoint crept in");
1560        assert!(!css.contains("ui-mode"), "a device mode crept in");
1561    }
1562
1563    #[test]
1564    fn compactness_moves_only_the_row_block() {
1565        // Comfortable is the model's row, compact the dense step; the two read
1566        // back from the attribute the emitters write.
1567        assert_eq!(Compactness::Comfortable.row_block(), ROW_BLOCK);
1568        assert_eq!(Compactness::Compact.row_block(), Step::Broad.ratio());
1569        assert_eq!(
1570            Compactness::from_attribute_value("compact"),
1571            Some(Compactness::Compact)
1572        );
1573        assert_eq!(Compactness::from_attribute_value("nonsense"), None);
1574        let css = compactness_css();
1575        assert!(css.contains(&format!(":root[{COMPACTNESS_ATTRIBUTE}=\"compact\"]")));
1576        assert!(css.contains("--row-block"));
1577        assert!(
1578            !css.contains("--gap-"),
1579            "a gap crept into the packing preset"
1580        );
1581    }
1582
1583    #[test]
1584    fn the_spacing_layer_is_emitted_inside_the_family_layer() {
1585        // Unlayered declarations outrank layered ones, so an app that layers
1586        // its own :root overrides would lose to an unlayered geometry.css.
1587        let css = density_css(None);
1588        assert!(css.starts_with(&format!("@layer {CSS_LAYER} {{\n")));
1589        assert!(css.trim_end().ends_with('}'));
1590        // Everything still there, one level in.
1591        assert!(css.contains("    :root {"));
1592        assert!(css.contains("--gap-peer"));
1593    }
1594
1595    #[test]
1596    fn the_type_ramp_ascends_and_never_repeats_a_size() {
1597        // A tier that resolves to the same size as its neighbour is a name
1598        // with no distinction behind it, which is how a scale grows rungs
1599        // nobody can choose between.
1600        let sizes: Vec<u16> = Text::all().iter().map(|t| t.px()).collect();
1601        assert!(sizes.windows(2).all(|w| w[0] < w[1]), "{sizes:?}");
1602        assert_eq!(sizes, vec![12, 14, 16, 18, 20, 24, 32, 40, 48]);
1603    }
1604
1605    #[test]
1606    fn the_type_ramp_has_a_legibility_floor() {
1607        // Nothing under 12px at the default base. Text that should recede
1608        // recedes by colour or weight, not by shrinking out of legibility.
1609        assert_eq!(Text::Fine.px(), 12);
1610        assert!(Text::all().iter().all(|t| t.px() >= 12));
1611    }
1612
1613    #[test]
1614    fn the_corner_scale_is_short_and_ordered() {
1615        // A radius carries one bit of meaning, whether the thing is meant to
1616        // be pressed, so a long scale is a scale nobody can choose from.
1617        let px: Vec<Option<u16>> = Radius::all().iter().map(|r| r.px()).collect();
1618        assert_eq!(px, vec![Some(0), Some(2), Some(4), Some(8), None]);
1619    }
1620
1621    #[test]
1622    fn square_and_round_are_spelled_not_calculated() {
1623        // `calc(var(--geometry-base) * 0 / 1)` is a zero nobody can read, and
1624        // 50% is a proportion of the element rather than of the base.
1625        assert_eq!(Radius::Square.css(), "0");
1626        assert_eq!(Radius::Round.css(), "50%");
1627        assert_eq!(Radius::Round.ratio(), None);
1628        assert!(Radius::Control.css().contains(BASE_TOKEN));
1629    }
1630
1631    #[test]
1632    fn the_edge_scale_is_two_rungs_in_device_pixels() {
1633        // Separate or be noticed; a third rung has no third meaning. And the
1634        // mark is never the hairline's weight, or a focus ring reads as an
1635        // outline.
1636        let px: Vec<u16> = Stroke::all().iter().map(|s| s.px()).collect();
1637        assert_eq!(px, vec![1, 2]);
1638        let css = geometry_css_vars(Density::Pointer);
1639        assert!(css.contains("--stroke-hairline: 1px;"), "{css}");
1640        assert!(css.contains("--stroke-mark: 2px;"), "{css}");
1641        // Not scaled by the base, for the reason on Stroke.
1642        assert!(!stroke_css_declarations().contains(BASE_TOKEN));
1643    }
1644
1645    #[test]
1646    fn edges_do_not_move_with_density() {
1647        let css = density_css(Some(".ui-mode-mobile"));
1648        assert_eq!(css.matches("--stroke-hairline:").count(), 1, "{css}");
1649    }
1650
1651    #[test]
1652    fn type_does_not_move_with_density() {
1653        // Density is a claim about the contact patch, and text is not a
1654        // target. A --text-* inside the touch override means that argument
1655        // was lost somewhere.
1656        let css = density_css(Some(".ui-mode-mobile"));
1657        let root_end = css.find("@media").expect("a touch block");
1658        assert!(css[..root_end].contains("--text-body"));
1659        assert!(!css[root_end..].contains("--text-"), "{}", &css[root_end..]);
1660    }
1661
1662    #[test]
1663    fn every_type_token_scales_from_the_one_base() {
1664        // A literal rem here would be a size that stops tracking the reader's
1665        // root font size, which is the whole point of the base.
1666        for text in Text::all() {
1667            let css = text.ratio().css();
1668            assert!(css.contains(BASE_TOKEN), "{}: {css}", text.token());
1669        }
1670    }
1671
1672    #[test]
1673    fn wrapping_leaves_no_trailing_whitespace_on_blank_lines() {
1674        // A formatter strips these later and calls it a diff.
1675        let css = in_css_layer("a {\n\nb\n}\n");
1676        assert!(!css.lines().any(|l| l != l.trim_end()), "{css:?}");
1677    }
1678
1679    #[test]
1680    fn the_two_density_conditions_are_complements_and_not_negations() {
1681        let pointer = Density::Pointer.media_condition();
1682        let touch = Density::Touch.media_condition();
1683
1684        // Touch is the negation of the whole Pointer query, not a feature
1685        // list of its own: that is what makes every device land in one.
1686        assert_eq!(touch, format!("not all and {pointer}"));
1687        assert!(pointer.contains(" and "), "pointer must be an AND");
1688        assert!(
1689            !pointer.contains(','),
1690            "a comma is an OR and would match touchscreens"
1691        );
1692    }
1693
1694    #[test]
1695    fn the_emitted_touch_block_is_the_condition_and_not_a_second_copy_of_it() {
1696        // The literal used to be inline here. Nothing may re-spell it.
1697        let css = density_css(None);
1698        assert!(css.contains(&format!("@media {}", Density::Touch.media_condition())));
1699    }
1700
1701    #[test]
1702    fn an_explicit_choice_is_emitted_after_the_detection() {
1703        let css = density_css(Some(".ui-mode-mobile"));
1704        let media = css.find("@media").expect("media query");
1705        let explicit = css.find(".ui-mode-mobile").expect("explicit selector");
1706        // Equal specificity, so order is the whole mechanism: the user's
1707        // choice has to come last or detection quietly overrides it.
1708        assert!(explicit > media, "the explicit selector must come last");
1709    }
1710
1711    #[test]
1712    fn without_an_explicit_selector_there_are_the_default_the_query_and_two_choices() {
1713        assert_eq!(density_css(None).matches("--gap-peer").count(), 4);
1714    }
1715
1716    #[test]
1717    fn a_choice_wins_over_detection_in_both_directions() {
1718        let css = density_css(None);
1719        let media = css.find("@media").expect("media query");
1720        for density in [Density::Pointer, Density::Touch] {
1721            let selector = format!(
1722                ":root[{DENSITY_ATTRIBUTE}=\"{}\"]",
1723                density.attribute_value()
1724            );
1725            let at = css
1726                .find(&format!("{selector} {{"))
1727                .expect("a block per choice");
1728            assert!(at > media, "{selector} must follow the query");
1729            // The block carries this density's gaps and not the other's.
1730            let block = &css[at..at + css[at..].find('}').expect("closed")];
1731            let peer = Gap::Peer.step_at(density).token();
1732            assert!(
1733                block.contains(&format!("--gap-peer: var(--{peer});")),
1734                "{block}"
1735            );
1736        }
1737    }
1738
1739    #[test]
1740    fn a_stored_choice_reads_back_and_nothing_else_is_one() {
1741        for density in [Density::Pointer, Density::Touch] {
1742            assert_eq!(
1743                Density::from_attribute_value(density.attribute_value()),
1744                Some(density)
1745            );
1746        }
1747        for junk in ["", "auto", "Touch", " touch"] {
1748            assert_eq!(Density::from_attribute_value(junk), None, "{junk:?}");
1749        }
1750    }
1751
1752    #[test]
1753    fn the_hig_relationships_land_on_the_hig_values() {
1754        // Mac OS 8 HIG, Control Layout Guidelines. The ratios are ours, but at
1755        // the default base they must resolve to the numbers the HIG specifies,
1756        // or the departure has cost us the thing it was translating.
1757        assert_eq!(Gap::Bound.px(), 4);
1758        assert_eq!(Gap::Peer.px(), 6);
1759        assert_eq!(Gap::Group.px(), 10);
1760        assert_eq!(Gap::Section.px(), 12);
1761    }
1762
1763    #[test]
1764    fn every_ratio_divides_the_default_base_exactly() {
1765        for step in Step::all() {
1766            let r = step.ratio();
1767            assert_eq!(
1768                u32::from(DEFAULT_BASE_PX) * u32::from(r.numerator) % u32::from(r.denominator),
1769                0,
1770                "{step:?} is fractional at the default base"
1771            );
1772        }
1773    }
1774
1775    #[test]
1776    fn ratios_scale_linearly() {
1777        for step in Step::all() {
1778            assert_eq!(
1779                step.ratio().px_at(DEFAULT_BASE_PX * 2),
1780                step.px() * 2,
1781                "{step:?} does not double with the base"
1782            );
1783        }
1784    }
1785
1786    #[test]
1787    fn steps_ascend_and_never_repeat() {
1788        let px: Vec<u16> = Step::all().iter().map(|s| s.px()).collect();
1789        let mut sorted = px.clone();
1790        sorted.sort_unstable();
1791        sorted.dedup();
1792        assert_eq!(px, sorted, "steps must be strictly ascending");
1793    }
1794
1795    #[test]
1796    fn gaps_ascend_with_their_relationships_at_every_density() {
1797        for density in [Density::Pointer, Density::Touch] {
1798            let px: Vec<u16> = Gap::all().iter().map(|g| g.px_at(density)).collect();
1799            let mut sorted = px.clone();
1800            sorted.sort_unstable();
1801            assert_eq!(px, sorted, "{density:?}: a looser relationship is tighter");
1802        }
1803    }
1804
1805    #[test]
1806    fn touch_separates_targets_and_holds_the_shells() {
1807        // The derivation, asserted so that changing it has to come here and say
1808        // so. Touch is a claim about the contact patch: the gaps between
1809        // distinct tap targets open, and the gaps that are not tap targets do
1810        // not move.
1811        for gap in [Gap::Peer, Gap::Group, Gap::Section] {
1812            assert!(
1813                gap.px_at(Density::Touch) > gap.px_at(Density::Pointer),
1814                "{gap:?} separates tap targets and must open on touch"
1815            );
1816        }
1817        for gap in [Gap::Bound, Gap::Pane, Gap::Page] {
1818            assert_eq!(
1819                gap.px_at(Density::Touch),
1820                gap.px_at(Density::Pointer),
1821                "{gap:?} is not a tap target and must not move with the input device"
1822            );
1823        }
1824    }
1825
1826    #[test]
1827    fn touch_never_resolves_tighter_than_pointer() {
1828        // The one cross-density rule, and its direction is the point: a derived
1829        // preset must never set a floor under the one quoted from the HIG.
1830        //
1831        // Constraining Touch by Pointer instead cannot do that. A Pointer
1832        // retune downward moves freely; only a Pointer move upward pushes
1833        // Touch, which is the correct direction of authority.
1834        for gap in Gap::all() {
1835            assert!(
1836                gap.px_at(Density::Touch) >= gap.px_at(Density::Pointer),
1837                "{gap:?}: Touch resolved tighter than Pointer"
1838            );
1839        }
1840    }
1841
1842    #[test]
1843    fn the_pointer_retune_is_not_blocked_by_touch() {
1844        // Touch's own ordering must hold using Touch values only, so that a
1845        // Pointer Pane at or below Touch's Section is legal.
1846        assert!(
1847            Gap::Section.px_at(Density::Touch) <= Gap::Pane.px_at(Density::Touch),
1848            "Touch inverted internally, which is what set the old floor"
1849        );
1850        // Shells tighten by size class rather than by moving the quoted Pointer
1851        // values, so Pointer pane holds at 24. This holds the direction of
1852        // authority: a derived preset never sets a floor under a quoted one.
1853        assert!(Gap::Section.px_at(Density::Touch) >= 16);
1854    }
1855
1856    #[test]
1857    fn shells_tighten_on_a_compact_window_and_nothing_else_does() {
1858        // Shells come down
1859        // one step on a compact window; the four gaps that separate controls
1860        // do not move, because how much room a window has says nothing about
1861        // how far apart two tap targets belong.
1862        for density in [Density::Pointer, Density::Touch] {
1863            assert_eq!(Gap::Pane.px_at_size(density, SizeClass::Compact), 16);
1864            assert_eq!(Gap::Page.px_at_size(density, SizeClass::Compact), 24);
1865
1866            for class in [SizeClass::Medium, SizeClass::Expanded] {
1867                assert_eq!(Gap::Pane.px_at_size(density, class), 24);
1868                assert_eq!(Gap::Page.px_at_size(density, class), 32);
1869            }
1870
1871            for gap in [Gap::Bound, Gap::Peer, Gap::Group, Gap::Section] {
1872                for &class in SizeClass::all() {
1873                    assert_eq!(
1874                        gap.px_at_size(density, class),
1875                        gap.px_at(density),
1876                        "{gap:?} moved on {class:?}, and only shells may"
1877                    );
1878                }
1879            }
1880        }
1881    }
1882
1883    #[test]
1884    fn the_widths_never_needed_a_step_at_seven_eighths() {
1885        // The retune wanted pane 14, which is 7/8 of the base and off an
1886        // eighths scale that runs 2/4/6/8/10/12/16/24/32/48. It would have
1887        // needed a new public Step variant, and naming one is a cost paid
1888        // forever. Putting the claim on the size-class axis lands both compact
1889        // values on steps that already exist.
1890        for gap in [Gap::Pane, Gap::Page] {
1891            for density in [Density::Pointer, Density::Touch] {
1892                let step = gap.step_at_size(density, SizeClass::Compact);
1893                assert!(
1894                    Step::all().contains(&step),
1895                    "{gap:?} compact resolved off the scale"
1896                );
1897            }
1898        }
1899    }
1900
1901    #[test]
1902    fn no_size_class_inverts_the_ordering() {
1903        // Collapse is allowed, inversion is not: the same rule the surface
1904        // quantum test applies, now across the third axis. Touch on a compact
1905        // window is the tight one: Section opens to 16 and Pane comes down to
1906        // 16, so they meet. Meeting is fine. Crossing is not.
1907        for density in [Density::Pointer, Density::Touch] {
1908            for &class in SizeClass::all() {
1909                let v: Vec<u16> = Gap::all()
1910                    .iter()
1911                    .map(|g| g.px_at_size(density, class))
1912                    .collect();
1913                let mut sorted = v.clone();
1914                sorted.sort_unstable();
1915                assert_eq!(v, sorted, "{density:?} {class:?} inverted: {v:?}");
1916            }
1917        }
1918    }
1919
1920    #[test]
1921    fn step_at_is_the_wider_window_answer() {
1922        // Every caller that predates the size-class axis meant the wide
1923        // window, so the old entry point has to keep resolving to it or a
1924        // consumer tightens silently on a bump it did not read about.
1925        for gap in Gap::all() {
1926            for density in [Density::Pointer, Density::Touch] {
1927                assert_eq!(
1928                    gap.step_at(density),
1929                    gap.step_at_size(density, SizeClass::Medium)
1930                );
1931                assert_eq!(
1932                    gap.step_at(density),
1933                    gap.step_at_size(density, SizeClass::Expanded)
1934                );
1935            }
1936        }
1937    }
1938
1939    #[test]
1940    fn the_width_query_lives_outside_the_density_file() {
1941        // density_is_selected_by_capability_not_by_width_or_agent forbids a
1942        // breakpoint in density_css. This is the other half of that rule: the
1943        // width query has to exist somewhere, and somewhere is here.
1944        let css = size_class_css();
1945        assert!(css.contains(&SizeClass::Compact.media_condition()));
1946        assert!(css.contains("--gap-pane"));
1947        assert!(css.contains("--gap-page"));
1948        // Targets never appear in a width query.
1949        for token in ["--gap-bound", "--gap-peer", "--gap-group", "--gap-section"] {
1950            assert!(!css.contains(token), "{token} crept into a width query");
1951        }
1952        // And it stays out of the density file.
1953        assert!(!density_css(None).contains("width"));
1954    }
1955
1956    #[test]
1957    fn size_classes_partition_every_width_exactly_once() {
1958        // Mutually exclusive and exhaustive, or a rule lands in two classes and
1959        // whichever is emitted last silently wins. Checked at every width up to
1960        // well past the top boundary rather than at the boundaries alone.
1961        for px in 0..=4000u16 {
1962            let hits: Vec<SizeClass> = SizeClass::all()
1963                .iter()
1964                .copied()
1965                .filter(|c| {
1966                    let lo = c.min_px();
1967                    let hi = match c {
1968                        SizeClass::Compact => SizeClass::Medium.min_px() - 1,
1969                        SizeClass::Medium => SizeClass::Expanded.min_px() - 1,
1970                        SizeClass::Expanded => u16::MAX,
1971                    };
1972                    px >= lo && px <= hi
1973                })
1974                .collect();
1975            assert_eq!(hits.len(), 1, "{px}px matched {hits:?}");
1976            assert_eq!(hits[0], SizeClass::at_width(px), "{px}px disagrees");
1977        }
1978    }
1979
1980    #[test]
1981    fn the_quoted_boundaries_are_the_ones_material_publishes() {
1982        // Quoted, not derived. Changing these means departing from the source,
1983        // which is a decision to record rather than a value to nudge.
1984        assert_eq!(SizeClass::Compact.min_px(), 0);
1985        assert_eq!(SizeClass::Medium.min_px(), 600);
1986        assert_eq!(SizeClass::Expanded.min_px(), 840);
1987    }
1988
1989    #[test]
1990    fn the_media_conditions_do_not_overlap_at_the_boundary() {
1991        // Each boundary is written once, exclusive below and inclusive above,
1992        // so 599.5px is Compact and 839.5px is Medium.
1993        assert_eq!(SizeClass::Compact.media_condition(), "(width < 600px)");
1994        assert_eq!(
1995            SizeClass::Medium.media_condition(),
1996            "(600px <= width < 840px)"
1997        );
1998        assert_eq!(SizeClass::Expanded.media_condition(), "(width >= 840px)");
1999    }
2000
2001    #[test]
2002    fn the_gap_scale_is_reachable_without_naming_a_size_class() {
2003        // The reasoning for size classes reaching the shells is in the docs on
2004        // Gap::step_at_size. This holds the other half: the whole spacing layer stays reachable without naming a size class. A
2005        // caller that has no idea how wide the window is still gets an answer,
2006        // and it is the wide-window one. Only step_at_size asks.
2007        let _ = geometry_css_vars(Density::Pointer);
2008        let _ = Gap::Page.px_at(Density::Touch);
2009        assert_eq!(SizeClass::all().len(), 3);
2010
2011        // And no size class may reach the four control gaps.
2012        for gap in [Gap::Bound, Gap::Peer, Gap::Group, Gap::Section] {
2013            for &class in SizeClass::all() {
2014                for density in [Density::Pointer, Density::Touch] {
2015                    assert_eq!(
2016                        gap.step_at_size(density, class),
2017                        gap.step_at(density),
2018                        "{gap:?} moved on {class:?}: screen budget reached a target gap"
2019                    );
2020                }
2021            }
2022        }
2023    }
2024
2025    #[test]
2026    fn a_terminal_resolves_the_vocabulary_to_whole_cells() {
2027        let t = Surface::terminal();
2028        let cells: Vec<u32> = Gap::all()
2029            .iter()
2030            .map(|g| t.gap(*g, Density::Pointer))
2031            .collect();
2032        // bound, peer | group, section | pane, page
2033        assert_eq!(cells, vec![0, 0, 1, 1, 2, 2]);
2034    }
2035
2036    #[test]
2037    fn collapsing_is_allowed_but_inverting_is_not() {
2038        // A coarse surface has fewer distinctions, so neighbouring gaps may
2039        // land on the same quantum. What must never happen is a looser
2040        // relationship coming out tighter than a closer one.
2041        for quantum in [0.5_f32, 1.0, 2.0, 3.0, 7.0] {
2042            for density in [Density::Pointer, Density::Touch] {
2043                let s = Surface {
2044                    base: 16.0,
2045                    quantum,
2046                };
2047                let v: Vec<u32> = Gap::all().iter().map(|g| s.gap(*g, density)).collect();
2048                let mut sorted = v.clone();
2049                sorted.sort_unstable();
2050                assert_eq!(v, sorted, "quantum {quantum} {density:?} inverted: {v:?}");
2051            }
2052        }
2053    }
2054
2055    #[test]
2056    fn the_web_surface_agrees_with_the_pixel_helper() {
2057        let w = Surface::web();
2058        for step in Step::all() {
2059            assert_eq!(
2060                w.resolve(step.ratio()) as u16,
2061                step.px(),
2062                "{step:?} disagrees between surface and px_at"
2063            );
2064        }
2065    }
2066
2067    #[test]
2068    fn quantising_is_monotonic_in_the_ratio() {
2069        let (base, quantum) = (16.0, 1.0);
2070        let mut previous = 0;
2071        for step in Step::all() {
2072            let q = step.ratio().quanta(base, quantum);
2073            assert!(q >= previous, "{step:?} went backwards");
2074            previous = q;
2075        }
2076    }
2077
2078    #[test]
2079    fn a_degenerate_quantum_yields_nothing_rather_than_panicking() {
2080        let r = Step::Loose.ratio();
2081        for bad in [0.0_f32, -1.0, f32::NAN] {
2082            assert_eq!(r.quanta(16.0, bad), 0);
2083            assert!(r.quantize(16.0, bad).abs() < f32::EPSILON);
2084        }
2085        assert_eq!(r.quanta(f32::INFINITY, 1.0), 0);
2086    }
2087
2088    #[test]
2089    fn px_at_saturates_and_survives_a_zero_denominator() {
2090        assert_eq!(Step::Colossal.ratio().px_at(30_000), u16::MAX);
2091        assert_eq!(ROW_BLOCK.px_at(u16::MAX), u16::MAX);
2092        let big = Ratio {
2093            numerator: u16::MAX,
2094            denominator: 1,
2095        };
2096        assert_eq!(big.px_at(u16::MAX), u16::MAX);
2097        let broken = Ratio {
2098            numerator: 3,
2099            denominator: 0,
2100        };
2101        assert_eq!(broken.px_at(16), 0);
2102    }
2103
2104    #[test]
2105    fn a_zero_denominator_is_nothing_from_every_axis() {
2106        // 3/0 and 0/0 both mean nothing, and every resolver must say so rather
2107        // than one call saturating and another emitting the whole base.
2108        for r in [
2109            Ratio {
2110                numerator: 3,
2111                denominator: 0,
2112            },
2113            Ratio {
2114                numerator: 0,
2115                denominator: 0,
2116            },
2117        ] {
2118            assert_eq!(r.px_at(16), 0, "{r:?}");
2119            assert!(r.scale(16.0).abs() < f32::EPSILON, "{r:?}");
2120            assert_eq!(r.quanta(16.0, 1.0), 0, "{r:?}");
2121            assert!(r.quantize(16.0, 1.0).abs() < f32::EPSILON, "{r:?}");
2122            assert_eq!(r.css(), "calc(var(--geometry-base) * 0)", "{r:?}");
2123        }
2124    }
2125
2126    #[test]
2127    fn px_at_rounds_rather_than_truncating() {
2128        // Eighths divide 16 exactly, so the rounding only shows on a base
2129        // that does not: 3/8 of 15 is 5.625, which is 6px, not 5.
2130        assert_eq!(Step::Snug.ratio().px_at(15), 6);
2131        assert_eq!(Step::Snug.ratio().px_at(DEFAULT_BASE_PX), 6);
2132    }
2133
2134    #[test]
2135    fn a_notice_reads_over_an_open_overlay() {
2136        assert!(Layer::Notice.z() > Layer::Overlay.z());
2137        let css = geometry_css_vars(Density::Pointer);
2138        assert!(css.contains("--layer-overlay: 100;"), "{css}");
2139        assert!(css.contains("--layer-notice: 200;"), "{css}");
2140    }
2141
2142    #[test]
2143    fn tokens_are_unique() {
2144        let mut names: Vec<&str> = Step::all().iter().map(|s| s.token()).collect();
2145        names.extend(Gap::all().iter().map(|g| g.token()));
2146        names.extend(Text::all().iter().map(|t| t.token()));
2147        names.extend(Radius::all().iter().map(|r| r.token()));
2148        names.extend(Stroke::all().iter().map(|s| s.token()));
2149        names.extend(Layer::all().iter().map(|l| l.token()));
2150        let count = names.len();
2151        names.sort_unstable();
2152        names.dedup();
2153        assert_eq!(names.len(), count, "token names collide");
2154    }
2155
2156    #[test]
2157    fn css_is_expressed_over_the_base_never_in_pixels() {
2158        let css = geometry_css_vars(Density::Pointer);
2159        assert!(css.starts_with(":root {\n"));
2160        assert!(css.trim_end().ends_with('}'));
2161        assert!(css.contains("--geometry-base: 1rem;"));
2162        for step in Step::all() {
2163            let line = format!("--{}: {}", step.token(), step.ratio().css());
2164            assert!(css.contains(&line), "missing or wrong: {line}");
2165        }
2166        // A hard pixel count anywhere in the scale defeats the point.
2167        let scale = scale_css_declarations();
2168        assert!(
2169            !scale.contains("px;"),
2170            "the scale must not emit pixel literals:\n{scale}"
2171        );
2172    }
2173
2174    #[test]
2175    fn ratio_css_drops_redundant_arithmetic() {
2176        assert_eq!(Step::Loose.ratio().css(), "var(--geometry-base)");
2177        assert_eq!(Step::Vast.ratio().css(), "calc(var(--geometry-base) * 2)");
2178        assert_eq!(
2179            Step::Snug.ratio().css(),
2180            "calc(var(--geometry-base) * 3 / 8)"
2181        );
2182    }
2183
2184    #[test]
2185    fn gaps_reference_steps_rather_than_repeating_values() {
2186        let css = geometry_css_vars(Density::Pointer);
2187        assert!(css.contains("--gap-peer: var(--step-snug);"));
2188        assert!(!css.contains("--gap-peer: calc"));
2189    }
2190
2191    #[test]
2192    fn a_density_override_emits_only_the_relational_layer() {
2193        let css = gap_css_overrides(".ui-mode-mobile", Density::Touch);
2194        // Which step Peer lands on is the preset's business, asserted in
2195        // touch_separates_targets_and_holds_the_shells. This says only that the
2196        // gap is emitted and references a step.
2197        assert!(css.contains("--gap-peer: var(--step-"));
2198        // Referencing a step is the point; re-declaring one would fork the
2199        // scale, so the check is on declarations, not on mentions.
2200        let declared: Vec<&str> = css
2201            .lines()
2202            .filter_map(|l| l.trim().strip_prefix("--"))
2203            .filter_map(|l| l.split(':').next())
2204            .collect();
2205        assert!(
2206            declared.iter().all(|t| t.starts_with("gap-")),
2207            "only the relational layer may be overridden, got {declared:?}"
2208        );
2209    }
2210
2211    #[test]
2212    fn a_density_override_leaves_the_shells_to_the_size_class() {
2213        // The shells answer to window width, so a density block that
2214        // re-declared them would outrank the compact block: its attribute
2215        // selector on :root is more specific than the plain :root the width
2216        // query uses, and an explicit touch choice on a phone would then lose
2217        // the compact shells. Only the base :root may name them.
2218        let css = density_css(Some(".ui-mode-mobile"));
2219        assert_eq!(css.matches("--gap-pane").count(), 1, "{css}");
2220        assert_eq!(css.matches("--gap-page").count(), 1, "{css}");
2221        assert_eq!(css.matches("--gap-bound").count(), 1, "{css}");
2222        let explicit = css
2223            .rsplit(".ui-mode-mobile {")
2224            .next()
2225            .expect("an explicit block");
2226        assert!(explicit.contains("--gap-peer:"), "{explicit}");
2227        for shell in ["--gap-pane", "--gap-page", "--gap-bound"] {
2228            assert!(!explicit.contains(shell), "{shell} in {explicit}");
2229        }
2230    }
2231
2232    #[test]
2233    fn a_table_row_is_45px_at_the_default_base_and_emitted_once() {
2234        assert_eq!(ROW_BLOCK.px_at(DEFAULT_BASE_PX), 45);
2235        let css = geometry_css_vars(Density::Pointer);
2236        assert_eq!(css.matches("--row-block:").count(), 1, "{css}");
2237        assert!(
2238            css.contains("--row-block: calc(var(--geometry-base) * 45 / 16);"),
2239            "{css}"
2240        );
2241    }
2242}