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 alloy_tui. 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 much screen there is, independent of what is pointing at it.
471///
472/// The second axis, and the one [`Density`] kept being asked to carry. A phone
473/// is small *and* touch; a tablet and a touchscreen laptop are big and touch; a
474/// half-width window on a desktop is small and pointer. Those are four real
475/// combinations and one axis cannot name them, which is what made the old Touch
476/// preset tighten shells it had no business tightening.
477///
478/// **Boundaries are quoted, not derived**, for the same reason the [`Gap`]
479/// values are: a derived boundary is one nobody can check. They are Material 3's
480/// window size classes, the best-known three-tier split with published numbers.
481/// Apple's size classes are two-tier and expressed as regular/compact per axis,
482/// which does not give a middle to aim at.
483///
484/// Source: <https://m3.material.io/foundations/layout/applying-layout/window-size-classes>
485///
486/// This enum carries the **boundaries only**. What appears, disappears or
487/// reflows at each is a product decision and belongs to `makeover-touch`, not
488/// here, with one exception: shells tighten on a compact window, through
489/// [`Gap::step_at_size`]. That is a look call, so it is eyeballed rather than
490/// derived.
491#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
492pub enum SizeClass {
493 /// Under 600px. Phones in either orientation, and any window narrowed to
494 /// phone width regardless of what is pointing at it.
495 Compact,
496 /// 600px to 839px. Small tablets, split-screen panes, half-width windows.
497 #[default]
498 Medium,
499 /// 840px and up. Laptops, desktops, tablets in landscape.
500 Expanded,
501}
502
503impl SizeClass {
504 /// Lower bound in CSS pixels, inclusive. [`Self::Compact`] starts at zero.
505 #[must_use]
506 pub const fn min_px(self) -> u16 {
507 match self {
508 Self::Compact => 0,
509 Self::Medium => 600,
510 Self::Expanded => 840,
511 }
512 }
513
514 /// The media condition selecting exactly this class, without the `@media`.
515 ///
516 /// Range syntax, so each bound is exclusive on one side and inclusive on
517 /// the other and the three classes partition every width: a rule cannot
518 /// land in two of them, and no width lands in none. `max-width` cannot say
519 /// that, because it is inclusive and a fractional-scaling display reaches
520 /// 599.5px, which `(max-width: 599px)` and `(min-width: 600px)` both miss.
521 #[must_use]
522 pub fn media_condition(self) -> String {
523 match self {
524 Self::Compact => format!("(width < {}px)", Self::Medium.min_px()),
525 Self::Medium => format!(
526 "({}px <= width < {}px)",
527 Self::Medium.min_px(),
528 Self::Expanded.min_px()
529 ),
530 Self::Expanded => format!("(width >= {}px)", Self::Expanded.min_px()),
531 }
532 }
533
534 /// The CSS class name an app may hang off this, without the leading dot.
535 #[must_use]
536 pub const fn token(self) -> &'static str {
537 match self {
538 Self::Compact => "size-compact",
539 Self::Medium => "size-medium",
540 Self::Expanded => "size-expanded",
541 }
542 }
543
544 /// Every class, narrowest first.
545 #[must_use]
546 pub const fn all() -> &'static [Self] {
547 &[Self::Compact, Self::Medium, Self::Expanded]
548 }
549
550 /// The class a given viewport width falls in.
551 #[must_use]
552 pub const fn at_width(px: u16) -> Self {
553 if px >= Self::Expanded.min_px() {
554 Self::Expanded
555 } else if px >= Self::Medium.min_px() {
556 Self::Medium
557 } else {
558 Self::Compact
559 }
560 }
561}
562
563/// A named separation between two things.
564///
565/// Pick by relationship. The size is a consequence of the name, not the other
566/// way round, and callers should never care what it is.
567#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
568pub enum Gap {
569 /// A control and the thing it belongs to: an edit field and its pop-up, a
570 /// checkbox and its label, an icon and the text it labels. Reads as one
571 /// object.
572 Bound,
573 /// Items of the same kind in a list: stacked checkboxes, radio buttons,
574 /// rows, chips in a row. Reads as a set.
575 Peer,
576 /// A container's inner margin, and the distance between sibling groups
577 /// side by side. Reads as "inside this box".
578 Group,
579 /// Separated groups, and rows of actions. The first gap that reads as a
580 /// deliberate break rather than as breathing room.
581 Section,
582 /// Panel padding and content shells. Layout, not controls.
583 Pane,
584 /// The outermost shell margin. One per screen, usually.
585 Page,
586}
587
588/// A raw step on the underlying scale.
589///
590/// Present because not every distance is a relationship between two controls:
591/// an optical nudge inside a badge is not a `Gap`. Prefer [`Gap`] wherever one
592/// fits: a step name says how big, a gap name says why.
593#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
594pub enum Step {
595 /// An eighth of the base. Optical nudges inside small inline elements.
596 Hair,
597 /// A quarter of the base.
598 Tight,
599 /// Three eighths of the base.
600 Snug,
601 /// Half the base.
602 Base,
603 /// Five eighths of the base.
604 Roomy,
605 /// Three quarters of the base.
606 Wide,
607 /// The base itself.
608 Loose,
609 /// One and a half times the base.
610 Broad,
611 /// Twice the base.
612 Vast,
613 /// Three times the base.
614 Colossal,
615}
616
617impl Step {
618 /// This step as a fraction of the base unit.
619 #[must_use]
620 pub const fn ratio(self) -> Ratio {
621 let (numerator, denominator) = match self {
622 Self::Hair => (1, 8),
623 Self::Tight => (1, 4),
624 Self::Snug => (3, 8),
625 Self::Base => (1, 2),
626 Self::Roomy => (5, 8),
627 Self::Wide => (3, 4),
628 Self::Loose => (1, 1),
629 Self::Broad => (3, 2),
630 Self::Vast => (2, 1),
631 Self::Colossal => (3, 1),
632 };
633 Ratio {
634 numerator,
635 denominator,
636 }
637 }
638
639 /// Size in CSS pixels at the default base.
640 #[must_use]
641 pub const fn px(self) -> u16 {
642 self.ratio().px_at(DEFAULT_BASE_PX)
643 }
644
645 /// The CSS custom-property name, without the leading `--`.
646 #[must_use]
647 pub const fn token(self) -> &'static str {
648 match self {
649 Self::Hair => "step-hair",
650 Self::Tight => "step-tight",
651 Self::Snug => "step-snug",
652 Self::Base => "step-base",
653 Self::Roomy => "step-roomy",
654 Self::Wide => "step-wide",
655 Self::Loose => "step-loose",
656 Self::Broad => "step-broad",
657 Self::Vast => "step-vast",
658 Self::Colossal => "step-colossal",
659 }
660 }
661
662 /// Every step, smallest first.
663 #[must_use]
664 pub const fn all() -> &'static [Self] {
665 &[
666 Self::Hair,
667 Self::Tight,
668 Self::Snug,
669 Self::Base,
670 Self::Roomy,
671 Self::Wide,
672 Self::Loose,
673 Self::Broad,
674 Self::Vast,
675 Self::Colossal,
676 ]
677 }
678}
679
680impl Gap {
681 /// The step this relationship resolves to at a given density, on a
682 /// [`SizeClass::Medium`] or wider window.
683 ///
684 /// [`Density::Pointer`]'s values are the HIG's own. [`Density::Touch`]
685 /// opens the three gaps that separate distinct tap targets and holds the
686 /// rest, per the crate-level "Density presets" section.
687 ///
688 /// Shells tighten on a compact window rather than at touch density. Use
689 /// [`Self::step_at_size`] where the window width is known; this is the
690 /// wider-window answer and the one every existing caller already meant.
691 #[must_use]
692 pub const fn step_at(self, density: Density) -> Step {
693 self.step_at_size(density, SizeClass::Medium)
694 }
695
696 /// The step this relationship resolves to at a given density and window
697 /// size class.
698 ///
699 /// Only the two shells move, and only on [`SizeClass::Compact`]: `pane`
700 /// 24 to 16, `page` 32 to 24, one step down each. The four gaps between
701 /// controls do not, because how much room a window has says nothing about
702 /// how far apart two tap targets should be.
703 ///
704 /// **Which axis owns this** (Max). A tighter window edge is a claim about
705 /// screen budget, and smuggling screen budget into the density axis is the
706 /// bug [`SizeClass`] exists to prevent. So the claim goes here and the
707 /// quoted Pointer values hold. Both compact values sit on the eighths
708 /// scale, so no `Step` at 7/8 = 14 is needed.
709 #[must_use]
710 pub const fn step_at_size(self, density: Density, size: SizeClass) -> Step {
711 match self {
712 // Binding is not a separation, so it does not open up on touch
713 // either: separating these would say they are two objects.
714 Self::Bound => Step::Tight,
715
716 // The three that carry mis-tap cost. Peer is the one that matters
717 // most (stacked rows, adjacent chips) and moves furthest; Group
718 // and Section follow only far enough to stay distinct from it.
719 Self::Peer => match density {
720 Density::Pointer => Step::Snug,
721 Density::Touch => Step::Roomy,
722 },
723 Self::Group => match density {
724 Density::Pointer => Step::Roomy,
725 Density::Touch => Step::Wide,
726 },
727 Self::Section => match density {
728 Density::Pointer => Step::Wide,
729 Density::Touch => Step::Loose,
730 },
731
732 // Shells. Not tap targets, so the contact patch has no opinion.
733 // Screen budget is the axis that does, and it is this one.
734 Self::Pane => match size {
735 SizeClass::Compact => Step::Loose,
736 SizeClass::Medium | SizeClass::Expanded => Step::Broad,
737 },
738 Self::Page => match size {
739 SizeClass::Compact => Step::Broad,
740 SizeClass::Medium | SizeClass::Expanded => Step::Vast,
741 },
742 }
743 }
744
745 /// The step this relationship resolves to at the default density.
746 #[must_use]
747 pub const fn step(self) -> Step {
748 self.step_at(Density::Pointer)
749 }
750
751 /// Size in CSS pixels at the default base, at a given density.
752 #[must_use]
753 pub const fn px_at(self, density: Density) -> u16 {
754 self.step_at(density).px()
755 }
756
757 /// Size in CSS pixels at the default base, at a given density and window
758 /// size class.
759 #[must_use]
760 pub const fn px_at_size(self, density: Density, size: SizeClass) -> u16 {
761 self.step_at_size(density, size).px()
762 }
763
764 /// Size in CSS pixels at the default base and density.
765 #[must_use]
766 pub const fn px(self) -> u16 {
767 self.step().px()
768 }
769
770 /// The CSS custom-property name, without the leading `--`.
771 #[must_use]
772 pub const fn token(self) -> &'static str {
773 match self {
774 Self::Bound => "gap-bound",
775 Self::Peer => "gap-peer",
776 Self::Group => "gap-group",
777 Self::Section => "gap-section",
778 Self::Pane => "gap-pane",
779 Self::Page => "gap-page",
780 }
781 }
782
783 /// Every relationship, tightest first.
784 #[must_use]
785 pub const fn all() -> &'static [Self] {
786 &[
787 Self::Bound,
788 Self::Peer,
789 Self::Group,
790 Self::Section,
791 Self::Pane,
792 Self::Page,
793 ]
794 }
795}
796
797/// What a piece of text is, from which its size follows.
798///
799/// The type axis, and the same move [`Gap`] makes on the spacing axis: name
800/// the role and let the size follow, so the choice is reviewable. Whether a
801/// caption should be 13px or 14px is unanswerable in isolation; whether a
802/// piece of text is a caption is not.
803///
804/// # Why the ratios are their own ramp
805///
806/// Type does not reuse [`Step`]. The spacing scale is built in eighths of the
807/// base because that is what the HIG's distances land on, and a type ramp
808/// needs different rungs. 7/8 and 9/8 sit either side of body copy and have
809/// no spacing meaning at all, while `Hair` and `Tight` are far below any
810/// legible size. Sharing the enum would have meant widening it for rungs
811/// spacing never asks for.
812///
813/// What is shared is the thing that matters: every rung here is a [`Ratio`]
814/// of `--geometry-base`, so text tracks the user's chosen root size exactly
815/// as spacing does, and one knob still moves the whole design.
816///
817/// # Why the floor is 3/4
818///
819/// Twelve pixels at the default base, and nothing below it. Sizes under that
820/// are a legibility problem rather than a tier, and a scale that offers one
821/// is a scale that invites it. Text that needs to recede should recede by
822/// colour or weight, which cost no legibility.
823///
824/// # Why type does not shift on touch
825///
826/// [`Density`] is a claim about the contact patch and nothing else, and text
827/// is not a tap target. The reader's own root font size is already the knob
828/// for how large text should be, and it already moves this whole ramp. So the
829/// type axis is density-invariant, and a phone gets the same tiers a desktop
830/// does.
831#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
832pub enum Text {
833 /// Three quarters of the base. Timestamps, badges, legal lines.
834 Fine,
835 /// Seven eighths of the base. Secondary text: metadata, table cells,
836 /// captions, form help.
837 Note,
838 /// The base itself. Running copy, and the size everything else is read
839 /// against.
840 Body,
841 /// Nine eighths of the base. Emphasised copy: intros, card titles.
842 Lead,
843 /// Five quarters of the base. The third heading level.
844 Subhead,
845 /// One and a half times the base. Section headings, the second level.
846 Head,
847 /// Twice the base. The page's own title, the first level.
848 Title,
849 /// Two and a half times the base. Display copy, above the document
850 /// hierarchy rather than at the top of it.
851 Display,
852 /// Three times the base. One per page at most: a landing hero.
853 Hero,
854}
855
856impl Text {
857 /// This role's size as a fraction of the base unit.
858 #[must_use]
859 pub const fn ratio(self) -> Ratio {
860 let (numerator, denominator) = match self {
861 Self::Fine => (3, 4),
862 Self::Note => (7, 8),
863 Self::Body => (1, 1),
864 Self::Lead => (9, 8),
865 Self::Subhead => (5, 4),
866 Self::Head => (3, 2),
867 Self::Title => (2, 1),
868 Self::Display => (5, 2),
869 Self::Hero => (3, 1),
870 };
871 Ratio {
872 numerator,
873 denominator,
874 }
875 }
876
877 /// Size in CSS pixels at the default base.
878 #[must_use]
879 pub const fn px(self) -> u16 {
880 self.ratio().px_at(DEFAULT_BASE_PX)
881 }
882
883 /// The CSS custom-property name, without the leading `--`.
884 #[must_use]
885 pub const fn token(self) -> &'static str {
886 match self {
887 Self::Fine => "text-fine",
888 Self::Note => "text-note",
889 Self::Body => "text-body",
890 Self::Lead => "text-lead",
891 Self::Subhead => "text-subhead",
892 Self::Head => "text-head",
893 Self::Title => "text-title",
894 Self::Display => "text-display",
895 Self::Hero => "text-hero",
896 }
897 }
898
899 /// Every role, smallest first.
900 #[must_use]
901 pub const fn all() -> &'static [Self] {
902 &[
903 Self::Fine,
904 Self::Note,
905 Self::Body,
906 Self::Lead,
907 Self::Subhead,
908 Self::Head,
909 Self::Title,
910 Self::Display,
911 Self::Hero,
912 ]
913 }
914}
915
916/// How rounded a corner is, named for what the corner belongs to.
917///
918/// The third axis to make the same move as [`Gap`] and [`Text`]: name the
919/// thing and let the value follow. Whether a corner should be 3px or 4px is
920/// unanswerable in isolation, and answering it once per component is how a
921/// stylesheet ends up with 2, 3, 4, 6, 8 and 12 all meaning "slightly
922/// rounded".
923///
924/// # Rounding is an affordance
925///
926/// The scale is deliberately short, because a corner radius carries one bit
927/// of meaning: whether the thing is meant to be pressed. [`Self::Square`]
928/// exists as a named rung rather than as the absence of a radius so that a
929/// container states that it is square, and a reader can tell a deliberate
930/// zero from a rule nobody wrote.
931#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
932pub enum Radius {
933 /// No rounding. Containers: cards, panels, dropdowns, page shells.
934 Square,
935 /// An eighth of the base. The tightest corner still visible: inline code,
936 /// small badges, status chips.
937 Fine,
938 /// A quarter of the base. Controls: buttons, inputs, selects.
939 Control,
940 /// Half the base. Surfaces that round rather than sit square: media
941 /// covers, callout boxes, feature cards.
942 Panel,
943 /// A circle, whatever the element's size.
944 Round,
945}
946
947impl Radius {
948 /// This corner as a fraction of the base unit.
949 ///
950 /// [`Self::Round`] has none, and that is not an oversight: 50% is a
951 /// proportion of the element's own box rather than of the base, so it
952 /// does not scale with `--geometry-base` and cannot be written as a
953 /// [`Ratio`]. Use [`Self::css`], which spells every rung.
954 #[must_use]
955 pub const fn ratio(self) -> Option<Ratio> {
956 let (numerator, denominator) = match self {
957 Self::Square => (0, 1),
958 Self::Fine => (1, 8),
959 Self::Control => (1, 4),
960 Self::Panel => (1, 2),
961 Self::Round => return None,
962 };
963 Some(Ratio {
964 numerator,
965 denominator,
966 })
967 }
968
969 /// Size in CSS pixels at the default base, or `None` for [`Self::Round`].
970 #[must_use]
971 pub const fn px(self) -> Option<u16> {
972 match self.ratio() {
973 Some(r) => Some(r.px_at(DEFAULT_BASE_PX)),
974 None => None,
975 }
976 }
977
978 /// The CSS value for this rung.
979 ///
980 /// `Square` emits a bare `0` rather than a `calc()` that multiplies the
981 /// base by nothing, and `Round` emits the percentage.
982 #[must_use]
983 pub fn css(self) -> String {
984 match self {
985 Self::Square => "0".to_owned(),
986 Self::Round => "50%".to_owned(),
987 other => other
988 .ratio()
989 .expect("every rung but Round has a ratio")
990 .css(),
991 }
992 }
993
994 /// The CSS custom-property name, without the leading `--`.
995 #[must_use]
996 pub const fn token(self) -> &'static str {
997 match self {
998 Self::Square => "radius-square",
999 Self::Fine => "radius-fine",
1000 Self::Control => "radius-control",
1001 Self::Panel => "radius-panel",
1002 Self::Round => "radius-round",
1003 }
1004 }
1005
1006 /// Every rung, squarest first.
1007 #[must_use]
1008 pub const fn all() -> &'static [Self] {
1009 &[
1010 Self::Square,
1011 Self::Fine,
1012 Self::Control,
1013 Self::Panel,
1014 Self::Round,
1015 ]
1016 }
1017}
1018
1019/// How heavy an edge is, named for what the edge is saying.
1020///
1021/// The fourth axis, and the same move as [`Radius`]: name the thing, let the
1022/// width follow. Measured across the tree before it existed, edges were 1px,
1023/// 2px, 3px and 4px with no token for any of them, and the 3px and 4px ones
1024/// were all the same thing (a status stripe down one side) spelled two ways.
1025///
1026/// # Two rungs
1027///
1028/// An edge says one of two things. Either it separates two surfaces, and wants
1029/// to be the least ink that still reads as a line, or it marks something the
1030/// reader has to notice: a focus ring, a status, a selection. Nothing between
1031/// those is a third meaning, so there is no third rung. `none` is not a rung
1032/// either, unlike [`Radius::Square`]: an absent edge is `border: none`, which
1033/// states itself without a width.
1034///
1035/// # Pixels, not ratios of the base
1036///
1037/// The one axis here that does not scale with `--geometry-base`, and on
1038/// purpose. A browser snaps a border's width to whole device pixels, so a
1039/// hairline at a 20px root would ask for 1.25px and draw 1, while the mark
1040/// would ask for 2.5 and draw 2: the scaling would buy nothing and blur the
1041/// ratio between the rungs. A hairline is the device's own unit of line, and
1042/// stays one at any text size.
1043///
1044/// On a terminal both rungs are one cell edge; the box-drawing set has a
1045/// heavy line for [`Self::Mark`] where the surface can draw it.
1046///
1047/// # Not `--border-*`
1048///
1049/// The tokens are `--stroke-*` because `--border` and `--border-strong` are
1050/// already colour tokens in `makeover`, and `border-strong` beside a
1051/// `border-mark` would read as two halves of one scale when they are two axes.
1052#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1053pub enum Stroke {
1054 /// The edge between two surfaces: dividers, rules, input outlines, a
1055 /// bevel's edge. 1px.
1056 Hairline,
1057 /// An edge that has to be noticed: the focus ring, a status stripe, a
1058 /// selected or latched outline. 2px, twice the hairline so the two never
1059 /// read as the same weight.
1060 Mark,
1061}
1062
1063impl Stroke {
1064 /// Width in CSS pixels. The same at every base, for the reason in the
1065 /// type's docs.
1066 #[must_use]
1067 pub const fn px(self) -> u16 {
1068 match self {
1069 Self::Hairline => 1,
1070 Self::Mark => 2,
1071 }
1072 }
1073
1074 /// The CSS value for this rung.
1075 #[must_use]
1076 pub fn css(self) -> String {
1077 format!("{}px", self.px())
1078 }
1079
1080 /// The CSS custom-property name, without the leading `--`.
1081 #[must_use]
1082 pub const fn token(self) -> &'static str {
1083 match self {
1084 Self::Hairline => "stroke-hairline",
1085 Self::Mark => "stroke-mark",
1086 }
1087 }
1088
1089 /// Every rung, lightest first.
1090 #[must_use]
1091 pub const fn all() -> &'static [Self] {
1092 &[Self::Hairline, Self::Mark]
1093 }
1094}
1095
1096/// Emit the base unit and the raw scale as CSS declarations, no selector.
1097///
1098/// Density-invariant: the steps are the vocabulary, and only which step a
1099/// relationship picks changes between presets.
1100#[must_use]
1101pub fn scale_css_declarations() -> String {
1102 let mut out = String::new();
1103 let _ = writeln!(
1104 out,
1105 " /* Every size below is a ratio of this. Scale it and the whole\n \
1106 layout scales with it, including for a user who has asked for\n \
1107 larger text. */\n --{BASE_TOKEN}: 1rem;\n"
1108 );
1109 out.push_str(" /* Raw scale. Prefer a --gap-* below; reach here only when\n");
1110 out.push_str(" no relationship describes the distance. */\n");
1111 for step in Step::all() {
1112 let _ = writeln!(out, " --{}: {};", step.token(), step.ratio().css());
1113 }
1114 out
1115}
1116
1117/// Emit the type axis as CSS declarations, no selector.
1118///
1119/// Takes no [`Density`]: text is not a tap target, so the contact patch has no
1120/// opinion on it. See [`Text`] for the derivation.
1121#[must_use]
1122pub fn text_css_declarations() -> String {
1123 let mut out = String::new();
1124 out.push_str(" /* Type. Named for what the text is; the size follows.\n");
1125 out.push_str(" Ratios of the base, so text tracks the reader's own\n");
1126 out.push_str(" root size. Density-invariant: text is not a target. */\n");
1127 for text in Text::all() {
1128 let _ = writeln!(out, " --{}: {};", text.token(), text.ratio().css());
1129 }
1130 out
1131}
1132
1133/// Emit the corner scale as CSS declarations, no selector.
1134///
1135/// Takes no [`Density`] for the same reason [`text_css_declarations`] does
1136/// not: a corner is not a tap target.
1137#[must_use]
1138pub fn radius_css_declarations() -> String {
1139 let mut out = String::new();
1140 out.push_str(" /* Corners. Rounding says a thing is meant to be pressed,\n");
1141 out.push_str(" so the scale is short on purpose and square is a rung\n");
1142 out.push_str(" rather than the absence of one. */\n");
1143 for radius in Radius::all() {
1144 let _ = writeln!(out, " --{}: {};", radius.token(), radius.css());
1145 }
1146 out
1147}
1148
1149/// Emit the edge scale as CSS declarations, no selector.
1150///
1151/// Takes no [`Density`]: an edge is not a tap target. Pixel literals, the one
1152/// emitter here that writes them, for the reason on [`Stroke`].
1153#[must_use]
1154pub fn stroke_css_declarations() -> String {
1155 let mut out = String::new();
1156 out.push_str(" /* Edges. Hairline separates, mark is to be noticed.\n");
1157 out.push_str(" Device pixels rather than ratios of the base: a border\n");
1158 out.push_str(" snaps to whole pixels, so scaling it buys nothing. */\n");
1159 for stroke in Stroke::all() {
1160 let _ = writeln!(out, " --{}: {};", stroke.token(), stroke.css());
1161 }
1162 out
1163}
1164
1165/// The block size of one table row: 45px at the default base.
1166///
1167/// wiki `table-model`: one compact action and a menu button fit a row at this
1168/// size, with both always visible. The renderers apply it as a minimum rather
1169/// than a height, so a row holding more than one line grows. Off the step
1170/// scale on purpose: it is the size the ruled row measures, not a spacing
1171/// relationship, so it is named here once rather than approximated by the
1172/// nearest step in three renderers.
1173pub const ROW_BLOCK: Ratio = Ratio {
1174 numerator: 45,
1175 denominator: 16,
1176};
1177
1178/// The CSS custom-property name [`ROW_BLOCK`] is emitted under, without `--`.
1179pub const ROW_BLOCK_TOKEN: &str = "row-block";
1180
1181/// Emit the named block sizes as CSS declarations, no selector.
1182#[must_use]
1183pub fn block_css_declarations() -> String {
1184 format!(" --{ROW_BLOCK_TOKEN}: {};\n", ROW_BLOCK.css())
1185}
1186
1187/// Emit the relational layer for one density as CSS declarations, no selector.
1188///
1189/// Gaps reference their step rather than repeating a value, so the scale has
1190/// exactly one definition and a reader can see which relationship maps where.
1191#[must_use]
1192pub fn gap_css_declarations(density: Density) -> String {
1193 gap_declarations(Gap::all(), density)
1194}
1195
1196/// The gaps a density preset moves: the three that separate distinct tap
1197/// targets.
1198///
1199/// `Bound` binds two things into one and does not move on touch either. The two
1200/// shells answer to the window size class, so a density override that
1201/// re-declared them would be a claim about screen budget on the wrong axis; it
1202/// would also outrank the compact block, whose `:root` is less specific than an
1203/// attribute selector on the same element.
1204const fn density_varying_gaps() -> &'static [Gap] {
1205 &[Gap::Peer, Gap::Group, Gap::Section]
1206}
1207
1208/// Emit the given relationships as CSS declarations, no selector.
1209fn gap_declarations(gaps: &[Gap], density: Density) -> String {
1210 let mut out = String::new();
1211 for &gap in gaps {
1212 let _ = writeln!(
1213 out,
1214 " --{}: var(--{});",
1215 gap.token(),
1216 gap.step_at(density).token()
1217 );
1218 }
1219 out
1220}
1221
1222/// The cascade layer every stylesheet the make-family generates is wrapped in.
1223///
1224/// One name shared by every emitter in the family, so an app writes it once and
1225/// the design system's output lands in one place it can order against:
1226///
1227/// ```css
1228/// @layer makeover, base, components, responsive;
1229/// ```
1230///
1231/// # Why a layer at all
1232///
1233/// The cascade resolves origin and importance, then layer, then specificity,
1234/// then source order, and **unlayered normal declarations outrank every named
1235/// layer**. So the moment an app declares any layer of its own, every rule it
1236/// owns loses to unlayered generated CSS regardless of specificity or of
1237/// loading last. Emitting into a layer is what stops that, and putting the name
1238/// here rather than in each app is what stops three apps picking three names.
1239///
1240/// # Why this constant lives in the geometry crate
1241///
1242/// Not because spacing owns it. This crate is the only one every CSS-emitting
1243/// crate in the family already depends on, and it is already the crate that
1244/// spells CSS for the family (`media_condition`, `Step::token`, `Ratio::css`).
1245/// A second copy in `makeover-webview` is exactly the drift
1246/// [`Density::media_condition`] exists to prevent, one layer up.
1247pub const CSS_LAYER: &str = "makeover";
1248
1249/// Wrap generated CSS in [`CSS_LAYER`].
1250///
1251/// Every whole-stylesheet emitter in the family ends with this call. Exposed
1252/// rather than kept private because an app that assembles its own stylesheet
1253/// out of this family's pieces has to put it in the same layer, since rules an
1254/// app generates in its own `build.rs` are as generated as the family's.
1255#[must_use]
1256pub fn in_css_layer(css: &str) -> String {
1257 let mut out = format!("@layer {CSS_LAYER} {{\n");
1258 for line in css.lines() {
1259 // Blank lines stay blank; indenting one leaves trailing whitespace.
1260 if line.is_empty() {
1261 out.push('\n');
1262 } else {
1263 let _ = writeln!(out, " {line}");
1264 }
1265 }
1266 out.push_str("}\n");
1267 out
1268}
1269
1270/// Emit the whole geometry layer as a `:root { … }` block at one density.
1271///
1272/// Mirrors `makeover::intent_css_vars`. Unlike the colour layer this is
1273/// constant, so a web consumer should bake it in at build time rather than
1274/// apply it from JS on every load.
1275///
1276/// The density argument reaches the gaps only. The scale and the type ramp are
1277/// the same at every density, which is why neither takes one.
1278#[must_use]
1279pub fn geometry_css_vars(density: Density) -> String {
1280 format!(
1281 ":root {{\n{}\n{}\n{}\n{}\n{}\n{}}}\n",
1282 scale_css_declarations(),
1283 gap_css_declarations(density),
1284 text_css_declarations(),
1285 radius_css_declarations(),
1286 stroke_css_declarations(),
1287 block_css_declarations()
1288 )
1289}
1290
1291/// The whole spacing layer with the canonical density selection, as CSS.
1292///
1293/// **Density is a capability, not a device and not a width.** A narrow window
1294/// on a desktop still has a pointer in it and a tablet at full width still has
1295/// a finger, so the touch preset hangs off "not a fine hovering pointer"
1296/// rather than off a breakpoint or a user-agent string. That is the question
1297/// the platform actually answers, and it is the one [`Density`] is asking.
1298///
1299/// A user's choice is [`DENSITY_ATTRIBUTE`] on the root element, honoured in
1300/// both directions: a block per value follows the capability query, so a
1301/// touchscreen laptop can be told it is a pointer machine and a mouse user
1302/// can ask for roomier targets. Neither is visible to a media query.
1303///
1304/// `explicit_touch` is for an app that already carries its own class for the
1305/// touch choice. It is emitted last and wins at equal specificity.
1306///
1307/// Never sniff the user agent for this: that asks what device this is as a
1308/// proxy for a capability the browser already reports.
1309///
1310/// Emitted inside [`CSS_LAYER`]. Custom properties follow the
1311/// ordinary cascade, so unlayered ones outrank layered ones: an app that puts
1312/// its own `:root` overrides in a named layer while this file stayed unlayered
1313/// would find the generated tokens beating the overrides meant to replace them.
1314/// That is the same trap the component sheet had, and it is not visible until
1315/// the app adopts layers.
1316#[must_use]
1317pub fn density_css(explicit_touch: Option<&str>) -> String {
1318 in_css_layer(&density_declarations(explicit_touch))
1319}
1320
1321/// [`density_css`] without the layer wrapper.
1322fn density_declarations(explicit_touch: Option<&str>) -> String {
1323 let mut css = geometry_css_vars(Density::Pointer);
1324 css.push_str("\n/* Touch: targets separate, shells hold. */\n");
1325 css.push_str("@media ");
1326 css.push_str(Density::Touch.media_condition());
1327 css.push_str(" {\n");
1328 for line in gap_css_overrides(":root", Density::Touch).lines() {
1329 css.push_str(" ");
1330 css.push_str(line);
1331 css.push('\n');
1332 }
1333 css.push_str("}\n");
1334 css.push_str("\n/* A user's choice, either way. Higher specificity than the query. */\n");
1335 for density in [Density::Pointer, Density::Touch] {
1336 let selector = format!(
1337 ":root[{DENSITY_ATTRIBUTE}=\"{}\"]",
1338 density.attribute_value()
1339 );
1340 css.push_str(&gap_css_overrides(&selector, density));
1341 }
1342 if let Some(selector) = explicit_touch {
1343 css.push_str("\n/* An explicit user choice, last so it wins over detection. */\n");
1344 css.push_str(&gap_css_overrides(selector, Density::Touch));
1345 }
1346 css
1347}
1348
1349/// Emit the compact-window shell override.
1350///
1351/// The one place this crate is allowed to ask how wide the window is. Density
1352/// must never be selected by width ([`density_css`] has a test forbidding a
1353/// breakpoint from appearing in it at all), because a capability query answers
1354/// "what is pointing at this" and a breakpoint does not. Size class is the
1355/// opposite: width is exactly what it means, so it gets its own emitter and
1356/// its own media query rather than being folded into that file.
1357///
1358/// Only the two shells move, and only below [`SizeClass::Medium`]'s boundary:
1359/// `pane` 24 to 16, `page` 32 to 24. The four gaps between controls are absent
1360/// from the block, so a narrow window never reasons about tap targets.
1361///
1362/// Emitted inside [`CSS_LAYER`] for the same reason [`density_css`] is: an
1363/// unlayered custom property outranks a layered one, so an app that layers its
1364/// own overrides would otherwise lose to this.
1365///
1366/// ```
1367/// # use makeover_geometry::size_class_css;
1368/// let css = size_class_css();
1369/// assert!(css.contains("--gap-pane"));
1370/// assert!(!css.contains("--gap-peer"), "a control gap crept into a width query");
1371/// ```
1372#[must_use]
1373pub fn size_class_css() -> String {
1374 in_css_layer(&size_class_declarations())
1375}
1376
1377/// [`size_class_css`] without the layer wrapper.
1378fn size_class_declarations() -> String {
1379 let mut css = String::new();
1380 css.push_str("/* Compact window: shells tighten. Outer margin is screen you\n");
1381 css.push_str(" don't get, which is a claim about the window and not about\n");
1382 css.push_str(" what is pointing at it, so it lives here and not in the\n");
1383 css.push_str(" density presets. Targets are untouched. */\n");
1384 let _ = writeln!(css, "@media {} {{", SizeClass::Compact.media_condition());
1385 css.push_str(" :root {\n");
1386 for gap in [Gap::Pane, Gap::Page] {
1387 let _ = writeln!(
1388 css,
1389 " --{}: var(--{});",
1390 gap.token(),
1391 gap.step_at_size(Density::Pointer, SizeClass::Compact)
1392 .token()
1393 );
1394 }
1395 css.push_str(" }\n}\n");
1396 css
1397}
1398
1399/// Emit a density preset as a scoped override block.
1400///
1401/// Only the relational layer is emitted: the scale and the base do not change
1402/// between presets, so an app ships [`geometry_css_vars`] at its default
1403/// density and one of these per mode class it supports. Of the gaps, only
1404/// [`Gap::Peer`], [`Gap::Group`] and [`Gap::Section`] move with the input
1405/// device; [`Gap::Bound`] and the two shells keep the value the base declared,
1406/// so a touch preset never overrides a compact-window shell.
1407///
1408/// ```
1409/// # use makeover_geometry::{Density, gap_css_overrides};
1410/// let css = gap_css_overrides(".ui-mode-mobile", Density::Touch);
1411/// assert!(css.starts_with(".ui-mode-mobile {\n"));
1412/// ```
1413#[must_use]
1414pub fn gap_css_overrides(selector: &str, density: Density) -> String {
1415 format!(
1416 "{selector} {{\n{}}}\n",
1417 gap_declarations(density_varying_gaps(), density)
1418 )
1419}
1420
1421#[cfg(test)]
1422mod tests {
1423 use super::*;
1424
1425 #[test]
1426 fn density_is_selected_by_capability_not_by_width_or_agent() {
1427 let css = density_css(None);
1428 assert!(css.contains("@media not all and (hover: hover) and (pointer: fine)"));
1429 // The three things density must never be selected by.
1430 assert!(!css.contains("width"), "a breakpoint crept in");
1431 assert!(!css.contains("ui-mode"), "a device mode crept in");
1432 }
1433
1434 #[test]
1435 fn the_spacing_layer_is_emitted_inside_the_family_layer() {
1436 // Unlayered declarations outrank layered ones, so an app that layers
1437 // its own :root overrides would lose to an unlayered geometry.css.
1438 let css = density_css(None);
1439 assert!(css.starts_with(&format!("@layer {CSS_LAYER} {{\n")));
1440 assert!(css.trim_end().ends_with('}'));
1441 // Everything still there, one level in.
1442 assert!(css.contains(" :root {"));
1443 assert!(css.contains("--gap-peer"));
1444 }
1445
1446 #[test]
1447 fn the_type_ramp_ascends_and_never_repeats_a_size() {
1448 // A tier that resolves to the same size as its neighbour is a name
1449 // with no distinction behind it, which is how a scale grows rungs
1450 // nobody can choose between.
1451 let sizes: Vec<u16> = Text::all().iter().map(|t| t.px()).collect();
1452 assert!(sizes.windows(2).all(|w| w[0] < w[1]), "{sizes:?}");
1453 assert_eq!(sizes, vec![12, 14, 16, 18, 20, 24, 32, 40, 48]);
1454 }
1455
1456 #[test]
1457 fn the_type_ramp_has_a_legibility_floor() {
1458 // Nothing under 12px at the default base. Text that should recede
1459 // recedes by colour or weight, not by shrinking out of legibility.
1460 assert_eq!(Text::Fine.px(), 12);
1461 assert!(Text::all().iter().all(|t| t.px() >= 12));
1462 }
1463
1464 #[test]
1465 fn the_corner_scale_is_short_and_ordered() {
1466 // A radius carries one bit of meaning, whether the thing is meant to
1467 // be pressed, so a long scale is a scale nobody can choose from.
1468 let px: Vec<Option<u16>> = Radius::all().iter().map(|r| r.px()).collect();
1469 assert_eq!(px, vec![Some(0), Some(2), Some(4), Some(8), None]);
1470 }
1471
1472 #[test]
1473 fn square_and_round_are_spelled_not_calculated() {
1474 // `calc(var(--geometry-base) * 0 / 1)` is a zero nobody can read, and
1475 // 50% is a proportion of the element rather than of the base.
1476 assert_eq!(Radius::Square.css(), "0");
1477 assert_eq!(Radius::Round.css(), "50%");
1478 assert_eq!(Radius::Round.ratio(), None);
1479 assert!(Radius::Control.css().contains(BASE_TOKEN));
1480 }
1481
1482 #[test]
1483 fn the_edge_scale_is_two_rungs_in_device_pixels() {
1484 // Separate or be noticed; a third rung has no third meaning. And the
1485 // mark is never the hairline's weight, or a focus ring reads as an
1486 // outline.
1487 let px: Vec<u16> = Stroke::all().iter().map(|s| s.px()).collect();
1488 assert_eq!(px, vec![1, 2]);
1489 let css = geometry_css_vars(Density::Pointer);
1490 assert!(css.contains("--stroke-hairline: 1px;"), "{css}");
1491 assert!(css.contains("--stroke-mark: 2px;"), "{css}");
1492 // Not scaled by the base, for the reason on Stroke.
1493 assert!(!stroke_css_declarations().contains(BASE_TOKEN));
1494 }
1495
1496 #[test]
1497 fn edges_do_not_move_with_density() {
1498 let css = density_css(Some(".ui-mode-mobile"));
1499 assert_eq!(css.matches("--stroke-hairline:").count(), 1, "{css}");
1500 }
1501
1502 #[test]
1503 fn type_does_not_move_with_density() {
1504 // Density is a claim about the contact patch, and text is not a
1505 // target. A --text-* inside the touch override means that argument
1506 // was lost somewhere.
1507 let css = density_css(Some(".ui-mode-mobile"));
1508 let root_end = css.find("@media").expect("a touch block");
1509 assert!(css[..root_end].contains("--text-body"));
1510 assert!(!css[root_end..].contains("--text-"), "{}", &css[root_end..]);
1511 }
1512
1513 #[test]
1514 fn every_type_token_scales_from_the_one_base() {
1515 // A literal rem here would be a size that stops tracking the reader's
1516 // root font size, which is the whole point of the base.
1517 for text in Text::all() {
1518 let css = text.ratio().css();
1519 assert!(css.contains(BASE_TOKEN), "{}: {css}", text.token());
1520 }
1521 }
1522
1523 #[test]
1524 fn wrapping_leaves_no_trailing_whitespace_on_blank_lines() {
1525 // A formatter strips these later and calls it a diff.
1526 let css = in_css_layer("a {\n\nb\n}\n");
1527 assert!(!css.lines().any(|l| l != l.trim_end()), "{css:?}");
1528 }
1529
1530 #[test]
1531 fn the_two_density_conditions_are_complements_and_not_negations() {
1532 let pointer = Density::Pointer.media_condition();
1533 let touch = Density::Touch.media_condition();
1534
1535 // Touch is the negation of the whole Pointer query, not a feature
1536 // list of its own: that is what makes every device land in one.
1537 assert_eq!(touch, format!("not all and {pointer}"));
1538 assert!(pointer.contains(" and "), "pointer must be an AND");
1539 assert!(
1540 !pointer.contains(','),
1541 "a comma is an OR and would match touchscreens"
1542 );
1543 }
1544
1545 #[test]
1546 fn the_emitted_touch_block_is_the_condition_and_not_a_second_copy_of_it() {
1547 // The literal used to be inline here. Nothing may re-spell it.
1548 let css = density_css(None);
1549 assert!(css.contains(&format!("@media {}", Density::Touch.media_condition())));
1550 }
1551
1552 #[test]
1553 fn an_explicit_choice_is_emitted_after_the_detection() {
1554 let css = density_css(Some(".ui-mode-mobile"));
1555 let media = css.find("@media").expect("media query");
1556 let explicit = css.find(".ui-mode-mobile").expect("explicit selector");
1557 // Equal specificity, so order is the whole mechanism: the user's
1558 // choice has to come last or detection quietly overrides it.
1559 assert!(explicit > media, "the explicit selector must come last");
1560 }
1561
1562 #[test]
1563 fn without_an_explicit_selector_there_are_the_default_the_query_and_two_choices() {
1564 assert_eq!(density_css(None).matches("--gap-peer").count(), 4);
1565 }
1566
1567 #[test]
1568 fn a_choice_wins_over_detection_in_both_directions() {
1569 let css = density_css(None);
1570 let media = css.find("@media").expect("media query");
1571 for density in [Density::Pointer, Density::Touch] {
1572 let selector = format!(
1573 ":root[{DENSITY_ATTRIBUTE}=\"{}\"]",
1574 density.attribute_value()
1575 );
1576 let at = css
1577 .find(&format!("{selector} {{"))
1578 .expect("a block per choice");
1579 assert!(at > media, "{selector} must follow the query");
1580 // The block carries this density's gaps and not the other's.
1581 let block = &css[at..at + css[at..].find('}').expect("closed")];
1582 let peer = Gap::Peer.step_at(density).token();
1583 assert!(
1584 block.contains(&format!("--gap-peer: var(--{peer});")),
1585 "{block}"
1586 );
1587 }
1588 }
1589
1590 #[test]
1591 fn a_stored_choice_reads_back_and_nothing_else_is_one() {
1592 for density in [Density::Pointer, Density::Touch] {
1593 assert_eq!(
1594 Density::from_attribute_value(density.attribute_value()),
1595 Some(density)
1596 );
1597 }
1598 for junk in ["", "auto", "Touch", " touch"] {
1599 assert_eq!(Density::from_attribute_value(junk), None, "{junk:?}");
1600 }
1601 }
1602
1603 #[test]
1604 fn the_hig_relationships_land_on_the_hig_values() {
1605 // Mac OS 8 HIG, Control Layout Guidelines. The ratios are ours, but at
1606 // the default base they must resolve to the numbers the HIG specifies,
1607 // or the departure has cost us the thing it was translating.
1608 assert_eq!(Gap::Bound.px(), 4);
1609 assert_eq!(Gap::Peer.px(), 6);
1610 assert_eq!(Gap::Group.px(), 10);
1611 assert_eq!(Gap::Section.px(), 12);
1612 }
1613
1614 #[test]
1615 fn every_ratio_divides_the_default_base_exactly() {
1616 for step in Step::all() {
1617 let r = step.ratio();
1618 assert_eq!(
1619 u32::from(DEFAULT_BASE_PX) * u32::from(r.numerator) % u32::from(r.denominator),
1620 0,
1621 "{step:?} is fractional at the default base"
1622 );
1623 }
1624 }
1625
1626 #[test]
1627 fn ratios_scale_linearly() {
1628 for step in Step::all() {
1629 assert_eq!(
1630 step.ratio().px_at(DEFAULT_BASE_PX * 2),
1631 step.px() * 2,
1632 "{step:?} does not double with the base"
1633 );
1634 }
1635 }
1636
1637 #[test]
1638 fn steps_ascend_and_never_repeat() {
1639 let px: Vec<u16> = Step::all().iter().map(|s| s.px()).collect();
1640 let mut sorted = px.clone();
1641 sorted.sort_unstable();
1642 sorted.dedup();
1643 assert_eq!(px, sorted, "steps must be strictly ascending");
1644 }
1645
1646 #[test]
1647 fn gaps_ascend_with_their_relationships_at_every_density() {
1648 for density in [Density::Pointer, Density::Touch] {
1649 let px: Vec<u16> = Gap::all().iter().map(|g| g.px_at(density)).collect();
1650 let mut sorted = px.clone();
1651 sorted.sort_unstable();
1652 assert_eq!(px, sorted, "{density:?}: a looser relationship is tighter");
1653 }
1654 }
1655
1656 #[test]
1657 fn touch_separates_targets_and_holds_the_shells() {
1658 // The derivation, asserted so that changing it has to come here and say
1659 // so. Touch is a claim about the contact patch: the gaps between
1660 // distinct tap targets open, and the gaps that are not tap targets do
1661 // not move.
1662 for gap in [Gap::Peer, Gap::Group, Gap::Section] {
1663 assert!(
1664 gap.px_at(Density::Touch) > gap.px_at(Density::Pointer),
1665 "{gap:?} separates tap targets and must open on touch"
1666 );
1667 }
1668 for gap in [Gap::Bound, Gap::Pane, Gap::Page] {
1669 assert_eq!(
1670 gap.px_at(Density::Touch),
1671 gap.px_at(Density::Pointer),
1672 "{gap:?} is not a tap target and must not move with the input device"
1673 );
1674 }
1675 }
1676
1677 #[test]
1678 fn touch_never_resolves_tighter_than_pointer() {
1679 // The one cross-density rule, and its direction is the point: a derived
1680 // preset must never set a floor under the one quoted from the HIG.
1681 //
1682 // Constraining Touch by Pointer instead cannot do that. A Pointer
1683 // retune downward moves freely; only a Pointer move upward pushes
1684 // Touch, which is the correct direction of authority.
1685 for gap in Gap::all() {
1686 assert!(
1687 gap.px_at(Density::Touch) >= gap.px_at(Density::Pointer),
1688 "{gap:?}: Touch resolved tighter than Pointer"
1689 );
1690 }
1691 }
1692
1693 #[test]
1694 fn the_pointer_retune_is_not_blocked_by_touch() {
1695 // Touch's own ordering must hold using Touch values only, so that a
1696 // Pointer Pane at or below Touch's Section is legal.
1697 assert!(
1698 Gap::Section.px_at(Density::Touch) <= Gap::Pane.px_at(Density::Touch),
1699 "Touch inverted internally, which is what set the old floor"
1700 );
1701 // Shells tighten by size class rather than by moving the quoted Pointer
1702 // values, so Pointer pane holds at 24. This holds the direction of
1703 // authority: a derived preset never sets a floor under a quoted one.
1704 assert!(Gap::Section.px_at(Density::Touch) >= 16);
1705 }
1706
1707 #[test]
1708 fn shells_tighten_on_a_compact_window_and_nothing_else_does() {
1709 // Shells come down
1710 // one step on a compact window; the four gaps that separate controls
1711 // do not move, because how much room a window has says nothing about
1712 // how far apart two tap targets belong.
1713 for density in [Density::Pointer, Density::Touch] {
1714 assert_eq!(Gap::Pane.px_at_size(density, SizeClass::Compact), 16);
1715 assert_eq!(Gap::Page.px_at_size(density, SizeClass::Compact), 24);
1716
1717 for class in [SizeClass::Medium, SizeClass::Expanded] {
1718 assert_eq!(Gap::Pane.px_at_size(density, class), 24);
1719 assert_eq!(Gap::Page.px_at_size(density, class), 32);
1720 }
1721
1722 for gap in [Gap::Bound, Gap::Peer, Gap::Group, Gap::Section] {
1723 for &class in SizeClass::all() {
1724 assert_eq!(
1725 gap.px_at_size(density, class),
1726 gap.px_at(density),
1727 "{gap:?} moved on {class:?}, and only shells may"
1728 );
1729 }
1730 }
1731 }
1732 }
1733
1734 #[test]
1735 fn the_widths_never_needed_a_step_at_seven_eighths() {
1736 // The retune wanted pane 14, which is 7/8 of the base and off an
1737 // eighths scale that runs 2/4/6/8/10/12/16/24/32/48. It would have
1738 // needed a new public Step variant, and naming one is a cost paid
1739 // forever. Putting the claim on the size-class axis lands both compact
1740 // values on steps that already exist.
1741 for gap in [Gap::Pane, Gap::Page] {
1742 for density in [Density::Pointer, Density::Touch] {
1743 let step = gap.step_at_size(density, SizeClass::Compact);
1744 assert!(
1745 Step::all().contains(&step),
1746 "{gap:?} compact resolved off the scale"
1747 );
1748 }
1749 }
1750 }
1751
1752 #[test]
1753 fn no_size_class_inverts_the_ordering() {
1754 // Collapse is allowed, inversion is not: the same rule the surface
1755 // quantum test applies, now across the third axis. Touch on a compact
1756 // window is the tight one: Section opens to 16 and Pane comes down to
1757 // 16, so they meet. Meeting is fine. Crossing is not.
1758 for density in [Density::Pointer, Density::Touch] {
1759 for &class in SizeClass::all() {
1760 let v: Vec<u16> = Gap::all()
1761 .iter()
1762 .map(|g| g.px_at_size(density, class))
1763 .collect();
1764 let mut sorted = v.clone();
1765 sorted.sort_unstable();
1766 assert_eq!(v, sorted, "{density:?} {class:?} inverted: {v:?}");
1767 }
1768 }
1769 }
1770
1771 #[test]
1772 fn step_at_is_the_wider_window_answer() {
1773 // Every caller that predates the size-class axis meant the wide
1774 // window, so the old entry point has to keep resolving to it or a
1775 // consumer tightens silently on a bump it did not read about.
1776 for gap in Gap::all() {
1777 for density in [Density::Pointer, Density::Touch] {
1778 assert_eq!(
1779 gap.step_at(density),
1780 gap.step_at_size(density, SizeClass::Medium)
1781 );
1782 assert_eq!(
1783 gap.step_at(density),
1784 gap.step_at_size(density, SizeClass::Expanded)
1785 );
1786 }
1787 }
1788 }
1789
1790 #[test]
1791 fn the_width_query_lives_outside_the_density_file() {
1792 // density_is_selected_by_capability_not_by_width_or_agent forbids a
1793 // breakpoint in density_css. This is the other half of that rule: the
1794 // width query has to exist somewhere, and somewhere is here.
1795 let css = size_class_css();
1796 assert!(css.contains(&SizeClass::Compact.media_condition()));
1797 assert!(css.contains("--gap-pane"));
1798 assert!(css.contains("--gap-page"));
1799 // Targets never appear in a width query.
1800 for token in ["--gap-bound", "--gap-peer", "--gap-group", "--gap-section"] {
1801 assert!(!css.contains(token), "{token} crept into a width query");
1802 }
1803 // And it stays out of the density file.
1804 assert!(!density_css(None).contains("width"));
1805 }
1806
1807 #[test]
1808 fn size_classes_partition_every_width_exactly_once() {
1809 // Mutually exclusive and exhaustive, or a rule lands in two classes and
1810 // whichever is emitted last silently wins. Checked at every width up to
1811 // well past the top boundary rather than at the boundaries alone.
1812 for px in 0..=4000u16 {
1813 let hits: Vec<SizeClass> = SizeClass::all()
1814 .iter()
1815 .copied()
1816 .filter(|c| {
1817 let lo = c.min_px();
1818 let hi = match c {
1819 SizeClass::Compact => SizeClass::Medium.min_px() - 1,
1820 SizeClass::Medium => SizeClass::Expanded.min_px() - 1,
1821 SizeClass::Expanded => u16::MAX,
1822 };
1823 px >= lo && px <= hi
1824 })
1825 .collect();
1826 assert_eq!(hits.len(), 1, "{px}px matched {hits:?}");
1827 assert_eq!(hits[0], SizeClass::at_width(px), "{px}px disagrees");
1828 }
1829 }
1830
1831 #[test]
1832 fn the_quoted_boundaries_are_the_ones_material_publishes() {
1833 // Quoted, not derived. Changing these means departing from the source,
1834 // which is a decision to record rather than a value to nudge.
1835 assert_eq!(SizeClass::Compact.min_px(), 0);
1836 assert_eq!(SizeClass::Medium.min_px(), 600);
1837 assert_eq!(SizeClass::Expanded.min_px(), 840);
1838 }
1839
1840 #[test]
1841 fn the_media_conditions_do_not_overlap_at_the_boundary() {
1842 // Each boundary is written once, exclusive below and inclusive above,
1843 // so 599.5px is Compact and 839.5px is Medium.
1844 assert_eq!(SizeClass::Compact.media_condition(), "(width < 600px)");
1845 assert_eq!(
1846 SizeClass::Medium.media_condition(),
1847 "(600px <= width < 840px)"
1848 );
1849 assert_eq!(SizeClass::Expanded.media_condition(), "(width >= 840px)");
1850 }
1851
1852 #[test]
1853 fn the_gap_scale_is_reachable_without_naming_a_size_class() {
1854 // The reasoning for size classes reaching the shells is in the docs on
1855 // Gap::step_at_size. This holds the other half: the whole spacing layer stays reachable without naming a size class. A
1856 // caller that has no idea how wide the window is still gets an answer,
1857 // and it is the wide-window one. Only step_at_size asks.
1858 let _ = geometry_css_vars(Density::Pointer);
1859 let _ = Gap::Page.px_at(Density::Touch);
1860 assert_eq!(SizeClass::all().len(), 3);
1861
1862 // And no size class may reach the four control gaps.
1863 for gap in [Gap::Bound, Gap::Peer, Gap::Group, Gap::Section] {
1864 for &class in SizeClass::all() {
1865 for density in [Density::Pointer, Density::Touch] {
1866 assert_eq!(
1867 gap.step_at_size(density, class),
1868 gap.step_at(density),
1869 "{gap:?} moved on {class:?}: screen budget reached a target gap"
1870 );
1871 }
1872 }
1873 }
1874 }
1875
1876 #[test]
1877 fn a_terminal_resolves_the_vocabulary_to_whole_cells() {
1878 let t = Surface::terminal();
1879 let cells: Vec<u32> = Gap::all()
1880 .iter()
1881 .map(|g| t.gap(*g, Density::Pointer))
1882 .collect();
1883 // bound, peer | group, section | pane, page
1884 assert_eq!(cells, vec![0, 0, 1, 1, 2, 2]);
1885 }
1886
1887 #[test]
1888 fn collapsing_is_allowed_but_inverting_is_not() {
1889 // A coarse surface has fewer distinctions, so neighbouring gaps may
1890 // land on the same quantum. What must never happen is a looser
1891 // relationship coming out tighter than a closer one.
1892 for quantum in [0.5_f32, 1.0, 2.0, 3.0, 7.0] {
1893 for density in [Density::Pointer, Density::Touch] {
1894 let s = Surface {
1895 base: 16.0,
1896 quantum,
1897 };
1898 let v: Vec<u32> = Gap::all().iter().map(|g| s.gap(*g, density)).collect();
1899 let mut sorted = v.clone();
1900 sorted.sort_unstable();
1901 assert_eq!(v, sorted, "quantum {quantum} {density:?} inverted: {v:?}");
1902 }
1903 }
1904 }
1905
1906 #[test]
1907 fn the_web_surface_agrees_with_the_pixel_helper() {
1908 let w = Surface::web();
1909 for step in Step::all() {
1910 assert_eq!(
1911 w.resolve(step.ratio()) as u16,
1912 step.px(),
1913 "{step:?} disagrees between surface and px_at"
1914 );
1915 }
1916 }
1917
1918 #[test]
1919 fn quantising_is_monotonic_in_the_ratio() {
1920 let (base, quantum) = (16.0, 1.0);
1921 let mut previous = 0;
1922 for step in Step::all() {
1923 let q = step.ratio().quanta(base, quantum);
1924 assert!(q >= previous, "{step:?} went backwards");
1925 previous = q;
1926 }
1927 }
1928
1929 #[test]
1930 fn a_degenerate_quantum_yields_nothing_rather_than_panicking() {
1931 let r = Step::Loose.ratio();
1932 for bad in [0.0_f32, -1.0, f32::NAN] {
1933 assert_eq!(r.quanta(16.0, bad), 0);
1934 assert!(r.quantize(16.0, bad).abs() < f32::EPSILON);
1935 }
1936 assert_eq!(r.quanta(f32::INFINITY, 1.0), 0);
1937 }
1938
1939 #[test]
1940 fn px_at_saturates_and_survives_a_zero_denominator() {
1941 assert_eq!(Step::Colossal.ratio().px_at(30_000), u16::MAX);
1942 assert_eq!(ROW_BLOCK.px_at(u16::MAX), u16::MAX);
1943 let big = Ratio {
1944 numerator: u16::MAX,
1945 denominator: 1,
1946 };
1947 assert_eq!(big.px_at(u16::MAX), u16::MAX);
1948 let broken = Ratio {
1949 numerator: 3,
1950 denominator: 0,
1951 };
1952 assert_eq!(broken.px_at(16), 0);
1953 }
1954
1955 #[test]
1956 fn a_zero_denominator_is_nothing_from_every_axis() {
1957 // 3/0 and 0/0 both mean nothing, and every resolver must say so rather
1958 // than one call saturating and another emitting the whole base.
1959 for r in [
1960 Ratio {
1961 numerator: 3,
1962 denominator: 0,
1963 },
1964 Ratio {
1965 numerator: 0,
1966 denominator: 0,
1967 },
1968 ] {
1969 assert_eq!(r.px_at(16), 0, "{r:?}");
1970 assert!(r.scale(16.0).abs() < f32::EPSILON, "{r:?}");
1971 assert_eq!(r.quanta(16.0, 1.0), 0, "{r:?}");
1972 assert!(r.quantize(16.0, 1.0).abs() < f32::EPSILON, "{r:?}");
1973 assert_eq!(r.css(), "calc(var(--geometry-base) * 0)", "{r:?}");
1974 }
1975 }
1976
1977 #[test]
1978 fn px_at_rounds_rather_than_truncating() {
1979 // Eighths divide 16 exactly, so the rounding only shows on a base
1980 // that does not: 3/8 of 15 is 5.625, which is 6px, not 5.
1981 assert_eq!(Step::Snug.ratio().px_at(15), 6);
1982 assert_eq!(Step::Snug.ratio().px_at(DEFAULT_BASE_PX), 6);
1983 }
1984
1985 #[test]
1986 fn tokens_are_unique() {
1987 let mut names: Vec<&str> = Step::all().iter().map(|s| s.token()).collect();
1988 names.extend(Gap::all().iter().map(|g| g.token()));
1989 names.extend(Text::all().iter().map(|t| t.token()));
1990 names.extend(Radius::all().iter().map(|r| r.token()));
1991 names.extend(Stroke::all().iter().map(|s| s.token()));
1992 let count = names.len();
1993 names.sort_unstable();
1994 names.dedup();
1995 assert_eq!(names.len(), count, "token names collide");
1996 }
1997
1998 #[test]
1999 fn css_is_expressed_over_the_base_never_in_pixels() {
2000 let css = geometry_css_vars(Density::Pointer);
2001 assert!(css.starts_with(":root {\n"));
2002 assert!(css.trim_end().ends_with('}'));
2003 assert!(css.contains("--geometry-base: 1rem;"));
2004 for step in Step::all() {
2005 let line = format!("--{}: {}", step.token(), step.ratio().css());
2006 assert!(css.contains(&line), "missing or wrong: {line}");
2007 }
2008 // A hard pixel count anywhere in the scale defeats the point.
2009 let scale = scale_css_declarations();
2010 assert!(
2011 !scale.contains("px;"),
2012 "the scale must not emit pixel literals:\n{scale}"
2013 );
2014 }
2015
2016 #[test]
2017 fn ratio_css_drops_redundant_arithmetic() {
2018 assert_eq!(Step::Loose.ratio().css(), "var(--geometry-base)");
2019 assert_eq!(Step::Vast.ratio().css(), "calc(var(--geometry-base) * 2)");
2020 assert_eq!(
2021 Step::Snug.ratio().css(),
2022 "calc(var(--geometry-base) * 3 / 8)"
2023 );
2024 }
2025
2026 #[test]
2027 fn gaps_reference_steps_rather_than_repeating_values() {
2028 let css = geometry_css_vars(Density::Pointer);
2029 assert!(css.contains("--gap-peer: var(--step-snug);"));
2030 assert!(!css.contains("--gap-peer: calc"));
2031 }
2032
2033 #[test]
2034 fn a_density_override_emits_only_the_relational_layer() {
2035 let css = gap_css_overrides(".ui-mode-mobile", Density::Touch);
2036 // Which step Peer lands on is the preset's business, asserted in
2037 // touch_separates_targets_and_holds_the_shells. This says only that the
2038 // gap is emitted and references a step.
2039 assert!(css.contains("--gap-peer: var(--step-"));
2040 // Referencing a step is the point; re-declaring one would fork the
2041 // scale, so the check is on declarations, not on mentions.
2042 let declared: Vec<&str> = css
2043 .lines()
2044 .filter_map(|l| l.trim().strip_prefix("--"))
2045 .filter_map(|l| l.split(':').next())
2046 .collect();
2047 assert!(
2048 declared.iter().all(|t| t.starts_with("gap-")),
2049 "only the relational layer may be overridden, got {declared:?}"
2050 );
2051 }
2052
2053 #[test]
2054 fn a_density_override_leaves_the_shells_to_the_size_class() {
2055 // The shells answer to window width, so a density block that
2056 // re-declared them would outrank the compact block: its attribute
2057 // selector on :root is more specific than the plain :root the width
2058 // query uses, and an explicit touch choice on a phone would then lose
2059 // the compact shells. Only the base :root may name them.
2060 let css = density_css(Some(".ui-mode-mobile"));
2061 assert_eq!(css.matches("--gap-pane").count(), 1, "{css}");
2062 assert_eq!(css.matches("--gap-page").count(), 1, "{css}");
2063 assert_eq!(css.matches("--gap-bound").count(), 1, "{css}");
2064 let explicit = css
2065 .rsplit(".ui-mode-mobile {")
2066 .next()
2067 .expect("an explicit block");
2068 assert!(explicit.contains("--gap-peer:"), "{explicit}");
2069 for shell in ["--gap-pane", "--gap-page", "--gap-bound"] {
2070 assert!(!explicit.contains(shell), "{shell} in {explicit}");
2071 }
2072 }
2073
2074 #[test]
2075 fn a_table_row_is_45px_at_the_default_base_and_emitted_once() {
2076 assert_eq!(ROW_BLOCK.px_at(DEFAULT_BASE_PX), 45);
2077 let css = geometry_css_vars(Density::Pointer);
2078 assert_eq!(css.matches("--row-block:").count(), 1, "{css}");
2079 assert!(
2080 css.contains("--row-block: calc(var(--geometry-base) * 45 / 16);"),
2081 "{css}"
2082 );
2083 }
2084}