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 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/// Emit the base unit and the raw scale as CSS declarations, no selector.
1153///
1154/// Density-invariant: the steps are the vocabulary, and only which step a
1155/// relationship picks changes between presets.
1156#[must_use]
1157pub fn scale_css_declarations() -> String {
1158 let mut out = String::new();
1159 let _ = writeln!(
1160 out,
1161 " /* Every size below is a ratio of this. Scale it and the whole\n \
1162 layout scales with it, including for a user who has asked for\n \
1163 larger text. */\n --{BASE_TOKEN}: 1rem;\n"
1164 );
1165 out.push_str(" /* Raw scale. Prefer a --gap-* below; reach here only when\n");
1166 out.push_str(" no relationship describes the distance. */\n");
1167 for step in Step::all() {
1168 let _ = writeln!(out, " --{}: {};", step.token(), step.ratio().css());
1169 }
1170 out
1171}
1172
1173/// Emit the type axis as CSS declarations, no selector.
1174///
1175/// Takes no [`Density`]: text is not a tap target, so the contact patch has no
1176/// opinion on it. See [`Text`] for the derivation.
1177#[must_use]
1178pub fn text_css_declarations() -> String {
1179 let mut out = String::new();
1180 out.push_str(" /* Type. Named for what the text is; the size follows.\n");
1181 out.push_str(" Ratios of the base, so text tracks the reader's own\n");
1182 out.push_str(" root size. Density-invariant: text is not a target. */\n");
1183 for text in Text::all() {
1184 let _ = writeln!(out, " --{}: {};", text.token(), text.ratio().css());
1185 }
1186 out
1187}
1188
1189/// Emit the corner scale as CSS declarations, no selector.
1190///
1191/// Takes no [`Density`] for the same reason [`text_css_declarations`] does
1192/// not: a corner is not a tap target.
1193#[must_use]
1194pub fn radius_css_declarations() -> String {
1195 let mut out = String::new();
1196 out.push_str(" /* Corners. Rounding says a thing is meant to be pressed,\n");
1197 out.push_str(" so the scale is short on purpose and square is a rung\n");
1198 out.push_str(" rather than the absence of one. */\n");
1199 for radius in Radius::all() {
1200 let _ = writeln!(out, " --{}: {};", radius.token(), radius.css());
1201 }
1202 out
1203}
1204
1205/// Emit the edge scale as CSS declarations, no selector.
1206///
1207/// Takes no [`Density`]: an edge is not a tap target. Pixel literals, the one
1208/// emitter here that writes them, for the reason on [`Stroke`].
1209#[must_use]
1210pub fn stroke_css_declarations() -> String {
1211 let mut out = String::new();
1212 out.push_str(" /* Edges. Hairline separates, mark is to be noticed.\n");
1213 out.push_str(" Device pixels rather than ratios of the base: a border\n");
1214 out.push_str(" snaps to whole pixels, so scaling it buys nothing. */\n");
1215 for stroke in Stroke::all() {
1216 let _ = writeln!(out, " --{}: {};", stroke.token(), stroke.css());
1217 }
1218 out
1219}
1220
1221/// The block size of one table row: 45px at the default base.
1222///
1223/// wiki `table-model`: one compact action and a menu button fit a row at this
1224/// size, with both always visible. The renderers apply it as a minimum rather
1225/// than a height, so a row holding more than one line grows. Off the step
1226/// scale on purpose: it is the size the ruled row measures, not a spacing
1227/// relationship, so it is named here once rather than approximated by the
1228/// nearest step in three renderers.
1229pub const ROW_BLOCK: Ratio = Ratio {
1230 numerator: 45,
1231 denominator: 16,
1232};
1233
1234/// The CSS custom-property name [`ROW_BLOCK`] is emitted under, without `--`.
1235pub const ROW_BLOCK_TOKEN: &str = "row-block";
1236
1237/// Emit the named block sizes as CSS declarations, no selector.
1238#[must_use]
1239pub fn block_css_declarations() -> String {
1240 format!(" --{ROW_BLOCK_TOKEN}: {};\n", ROW_BLOCK.css())
1241}
1242
1243/// Emit the relational layer for one density as CSS declarations, no selector.
1244///
1245/// Gaps reference their step rather than repeating a value, so the scale has
1246/// exactly one definition and a reader can see which relationship maps where.
1247#[must_use]
1248pub fn gap_css_declarations(density: Density) -> String {
1249 gap_declarations(Gap::all(), density)
1250}
1251
1252/// The gaps a density preset moves: the three that separate distinct tap
1253/// targets.
1254///
1255/// `Bound` binds two things into one and does not move on touch either. The two
1256/// shells answer to the window size class, so a density override that
1257/// re-declared them would be a claim about screen budget on the wrong axis; it
1258/// would also outrank the compact block, whose `:root` is less specific than an
1259/// attribute selector on the same element.
1260const fn density_varying_gaps() -> &'static [Gap] {
1261 &[Gap::Peer, Gap::Group, Gap::Section]
1262}
1263
1264/// Emit the given relationships as CSS declarations, no selector.
1265fn gap_declarations(gaps: &[Gap], density: Density) -> String {
1266 let mut out = String::new();
1267 for &gap in gaps {
1268 let _ = writeln!(
1269 out,
1270 " --{}: var(--{});",
1271 gap.token(),
1272 gap.step_at(density).token()
1273 );
1274 }
1275 out
1276}
1277
1278/// The cascade layer every stylesheet the make-family generates is wrapped in.
1279///
1280/// One name shared by every emitter in the family, so an app writes it once and
1281/// the design system's output lands in one place it can order against:
1282///
1283/// ```css
1284/// @layer makeover, base, components, responsive;
1285/// ```
1286///
1287/// # Why a layer at all
1288///
1289/// The cascade resolves origin and importance, then layer, then specificity,
1290/// then source order, and **unlayered normal declarations outrank every named
1291/// layer**. So the moment an app declares any layer of its own, every rule it
1292/// owns loses to unlayered generated CSS regardless of specificity or of
1293/// loading last. Emitting into a layer is what stops that, and putting the name
1294/// here rather than in each app is what stops three apps picking three names.
1295///
1296/// # Why this constant lives in the geometry crate
1297///
1298/// Not because spacing owns it. This crate is the only one every CSS-emitting
1299/// crate in the family already depends on, and it is already the crate that
1300/// spells CSS for the family (`media_condition`, `Step::token`, `Ratio::css`).
1301/// A second copy in `makeover-webview` is exactly the drift
1302/// [`Density::media_condition`] exists to prevent, one layer up.
1303pub const CSS_LAYER: &str = "makeover";
1304
1305/// Wrap generated CSS in [`CSS_LAYER`].
1306///
1307/// Every whole-stylesheet emitter in the family ends with this call. Exposed
1308/// rather than kept private because an app that assembles its own stylesheet
1309/// out of this family's pieces has to put it in the same layer, since rules an
1310/// app generates in its own `build.rs` are as generated as the family's.
1311#[must_use]
1312pub fn in_css_layer(css: &str) -> String {
1313 let mut out = format!("@layer {CSS_LAYER} {{\n");
1314 for line in css.lines() {
1315 // Blank lines stay blank; indenting one leaves trailing whitespace.
1316 if line.is_empty() {
1317 out.push('\n');
1318 } else {
1319 let _ = writeln!(out, " {line}");
1320 }
1321 }
1322 out.push_str("}\n");
1323 out
1324}
1325
1326/// Emit the whole geometry layer as a `:root { … }` block at one density.
1327///
1328/// Mirrors `makeover::intent_css_vars`. Unlike the colour layer this is
1329/// constant, so a web consumer should bake it in at build time rather than
1330/// apply it from JS on every load.
1331///
1332/// The density argument reaches the gaps only. The scale and the type ramp are
1333/// the same at every density, which is why neither takes one.
1334#[must_use]
1335pub fn geometry_css_vars(density: Density) -> String {
1336 format!(
1337 ":root {{\n{}\n{}\n{}\n{}\n{}\n{}}}\n",
1338 scale_css_declarations(),
1339 gap_css_declarations(density),
1340 text_css_declarations(),
1341 radius_css_declarations(),
1342 stroke_css_declarations(),
1343 block_css_declarations()
1344 )
1345}
1346
1347/// The whole spacing layer with the canonical density selection, as CSS.
1348///
1349/// **Density is a capability, not a device and not a width.** A narrow window
1350/// on a desktop still has a pointer in it and a tablet at full width still has
1351/// a finger, so the touch preset hangs off "not a fine hovering pointer"
1352/// rather than off a breakpoint or a user-agent string. That is the question
1353/// the platform actually answers, and it is the one [`Density`] is asking.
1354///
1355/// A user's choice is [`DENSITY_ATTRIBUTE`] on the root element, honoured in
1356/// both directions: a block per value follows the capability query, so a
1357/// touchscreen laptop can be told it is a pointer machine and a mouse user
1358/// can ask for roomier targets. Neither is visible to a media query.
1359///
1360/// `explicit_touch` is for an app that already carries its own class for the
1361/// touch choice. It is emitted last and wins at equal specificity.
1362///
1363/// Never sniff the user agent for this: that asks what device this is as a
1364/// proxy for a capability the browser already reports.
1365///
1366/// Emitted inside [`CSS_LAYER`]. Custom properties follow the
1367/// ordinary cascade, so unlayered ones outrank layered ones: an app that puts
1368/// its own `:root` overrides in a named layer while this file stayed unlayered
1369/// would find the generated tokens beating the overrides meant to replace them.
1370/// That is the same trap the component sheet had, and it is not visible until
1371/// the app adopts layers.
1372#[must_use]
1373pub fn density_css(explicit_touch: Option<&str>) -> String {
1374 in_css_layer(&density_declarations(explicit_touch))
1375}
1376
1377/// [`density_css`] without the layer wrapper.
1378fn density_declarations(explicit_touch: Option<&str>) -> String {
1379 let mut css = geometry_css_vars(Density::Pointer);
1380 css.push_str("\n/* Touch: targets separate, shells hold. */\n");
1381 css.push_str("@media ");
1382 css.push_str(Density::Touch.media_condition());
1383 css.push_str(" {\n");
1384 for line in gap_css_overrides(":root", Density::Touch).lines() {
1385 css.push_str(" ");
1386 css.push_str(line);
1387 css.push('\n');
1388 }
1389 css.push_str("}\n");
1390 css.push_str("\n/* A user's choice, either way. Higher specificity than the query. */\n");
1391 for density in [Density::Pointer, Density::Touch] {
1392 let selector = format!(
1393 ":root[{DENSITY_ATTRIBUTE}=\"{}\"]",
1394 density.attribute_value()
1395 );
1396 css.push_str(&gap_css_overrides(&selector, density));
1397 }
1398 if let Some(selector) = explicit_touch {
1399 css.push_str("\n/* An explicit user choice, last so it wins over detection. */\n");
1400 css.push_str(&gap_css_overrides(selector, Density::Touch));
1401 }
1402 css
1403}
1404
1405/// The denser-row override for the row block.
1406///
1407/// The comfortable default is [`block_css_declarations`], which writes
1408/// `--row-block` as [`ROW_BLOCK`] in the `:root` block; this emits only the
1409/// compact arm, keyed on [`COMPACTNESS_ATTRIBUTE`]. Unlayered on purpose: a
1410/// reader's explicit packing choice must beat the default wherever the default
1411/// was emitted.
1412///
1413/// ```
1414/// # use makeover_geometry::compactness_css;
1415/// let css = compactness_css();
1416/// assert!(css.contains("--row-block"));
1417/// ```
1418#[must_use]
1419pub fn compactness_css() -> String {
1420 format!(
1421 ":root[{COMPACTNESS_ATTRIBUTE}=\"{}\"] {{\n --{ROW_BLOCK_TOKEN}: {};\n}}\n",
1422 Compactness::Compact.attribute_value(),
1423 Compactness::Compact.row_block().css()
1424 )
1425}
1426
1427/// Emit the compact-window shell override.
1428///
1429/// The one place this crate is allowed to ask how wide the window is. Density
1430/// must never be selected by width ([`density_css`] has a test forbidding a
1431/// breakpoint from appearing in it at all), because a capability query answers
1432/// "what is pointing at this" and a breakpoint does not. Size class is the
1433/// opposite: width is exactly what it means, so it gets its own emitter and
1434/// its own media query rather than being folded into that file.
1435///
1436/// Only the two shells move, and only below [`SizeClass::Medium`]'s boundary:
1437/// `pane` 24 to 16, `page` 32 to 24. The four gaps between controls are absent
1438/// from the block, so a narrow window never reasons about tap targets.
1439///
1440/// Emitted inside [`CSS_LAYER`] for the same reason [`density_css`] is: an
1441/// unlayered custom property outranks a layered one, so an app that layers its
1442/// own overrides would otherwise lose to this.
1443///
1444/// ```
1445/// # use makeover_geometry::size_class_css;
1446/// let css = size_class_css();
1447/// assert!(css.contains("--gap-pane"));
1448/// assert!(!css.contains("--gap-peer"), "a control gap crept into a width query");
1449/// ```
1450#[must_use]
1451pub fn size_class_css() -> String {
1452 in_css_layer(&size_class_declarations())
1453}
1454
1455/// [`size_class_css`] without the layer wrapper.
1456fn size_class_declarations() -> String {
1457 let mut css = String::new();
1458 css.push_str("/* Compact window: shells tighten. Outer margin is screen you\n");
1459 css.push_str(" don't get, which is a claim about the window and not about\n");
1460 css.push_str(" what is pointing at it, so it lives here and not in the\n");
1461 css.push_str(" density presets. Targets are untouched. */\n");
1462 let _ = writeln!(css, "@media {} {{", SizeClass::Compact.media_condition());
1463 css.push_str(" :root {\n");
1464 for gap in [Gap::Pane, Gap::Page] {
1465 let _ = writeln!(
1466 css,
1467 " --{}: var(--{});",
1468 gap.token(),
1469 gap.step_at_size(Density::Pointer, SizeClass::Compact)
1470 .token()
1471 );
1472 }
1473 css.push_str(" }\n}\n");
1474 css
1475}
1476
1477/// Emit a density preset as a scoped override block.
1478///
1479/// Only the relational layer is emitted: the scale and the base do not change
1480/// between presets, so an app ships [`geometry_css_vars`] at its default
1481/// density and one of these per mode class it supports. Of the gaps, only
1482/// [`Gap::Peer`], [`Gap::Group`] and [`Gap::Section`] move with the input
1483/// device; [`Gap::Bound`] and the two shells keep the value the base declared,
1484/// so a touch preset never overrides a compact-window shell.
1485///
1486/// ```
1487/// # use makeover_geometry::{Density, gap_css_overrides};
1488/// let css = gap_css_overrides(".ui-mode-mobile", Density::Touch);
1489/// assert!(css.starts_with(".ui-mode-mobile {\n"));
1490/// ```
1491#[must_use]
1492pub fn gap_css_overrides(selector: &str, density: Density) -> String {
1493 format!(
1494 "{selector} {{\n{}}}\n",
1495 gap_declarations(density_varying_gaps(), density)
1496 )
1497}
1498
1499#[cfg(test)]
1500mod tests {
1501 use super::*;
1502
1503 #[test]
1504 fn density_is_selected_by_capability_not_by_width_or_agent() {
1505 let css = density_css(None);
1506 assert!(css.contains("@media not all and (hover: hover) and (pointer: fine)"));
1507 // The three things density must never be selected by.
1508 assert!(!css.contains("width"), "a breakpoint crept in");
1509 assert!(!css.contains("ui-mode"), "a device mode crept in");
1510 }
1511
1512 #[test]
1513 fn compactness_moves_only_the_row_block() {
1514 // Comfortable is the model's row, compact the dense step; the two read
1515 // back from the attribute the emitters write.
1516 assert_eq!(Compactness::Comfortable.row_block(), ROW_BLOCK);
1517 assert_eq!(Compactness::Compact.row_block(), Step::Broad.ratio());
1518 assert_eq!(
1519 Compactness::from_attribute_value("compact"),
1520 Some(Compactness::Compact)
1521 );
1522 assert_eq!(Compactness::from_attribute_value("nonsense"), None);
1523 let css = compactness_css();
1524 assert!(css.contains(&format!(":root[{COMPACTNESS_ATTRIBUTE}=\"compact\"]")));
1525 assert!(css.contains("--row-block"));
1526 assert!(
1527 !css.contains("--gap-"),
1528 "a gap crept into the packing preset"
1529 );
1530 }
1531
1532 #[test]
1533 fn the_spacing_layer_is_emitted_inside_the_family_layer() {
1534 // Unlayered declarations outrank layered ones, so an app that layers
1535 // its own :root overrides would lose to an unlayered geometry.css.
1536 let css = density_css(None);
1537 assert!(css.starts_with(&format!("@layer {CSS_LAYER} {{\n")));
1538 assert!(css.trim_end().ends_with('}'));
1539 // Everything still there, one level in.
1540 assert!(css.contains(" :root {"));
1541 assert!(css.contains("--gap-peer"));
1542 }
1543
1544 #[test]
1545 fn the_type_ramp_ascends_and_never_repeats_a_size() {
1546 // A tier that resolves to the same size as its neighbour is a name
1547 // with no distinction behind it, which is how a scale grows rungs
1548 // nobody can choose between.
1549 let sizes: Vec<u16> = Text::all().iter().map(|t| t.px()).collect();
1550 assert!(sizes.windows(2).all(|w| w[0] < w[1]), "{sizes:?}");
1551 assert_eq!(sizes, vec![12, 14, 16, 18, 20, 24, 32, 40, 48]);
1552 }
1553
1554 #[test]
1555 fn the_type_ramp_has_a_legibility_floor() {
1556 // Nothing under 12px at the default base. Text that should recede
1557 // recedes by colour or weight, not by shrinking out of legibility.
1558 assert_eq!(Text::Fine.px(), 12);
1559 assert!(Text::all().iter().all(|t| t.px() >= 12));
1560 }
1561
1562 #[test]
1563 fn the_corner_scale_is_short_and_ordered() {
1564 // A radius carries one bit of meaning, whether the thing is meant to
1565 // be pressed, so a long scale is a scale nobody can choose from.
1566 let px: Vec<Option<u16>> = Radius::all().iter().map(|r| r.px()).collect();
1567 assert_eq!(px, vec![Some(0), Some(2), Some(4), Some(8), None]);
1568 }
1569
1570 #[test]
1571 fn square_and_round_are_spelled_not_calculated() {
1572 // `calc(var(--geometry-base) * 0 / 1)` is a zero nobody can read, and
1573 // 50% is a proportion of the element rather than of the base.
1574 assert_eq!(Radius::Square.css(), "0");
1575 assert_eq!(Radius::Round.css(), "50%");
1576 assert_eq!(Radius::Round.ratio(), None);
1577 assert!(Radius::Control.css().contains(BASE_TOKEN));
1578 }
1579
1580 #[test]
1581 fn the_edge_scale_is_two_rungs_in_device_pixels() {
1582 // Separate or be noticed; a third rung has no third meaning. And the
1583 // mark is never the hairline's weight, or a focus ring reads as an
1584 // outline.
1585 let px: Vec<u16> = Stroke::all().iter().map(|s| s.px()).collect();
1586 assert_eq!(px, vec![1, 2]);
1587 let css = geometry_css_vars(Density::Pointer);
1588 assert!(css.contains("--stroke-hairline: 1px;"), "{css}");
1589 assert!(css.contains("--stroke-mark: 2px;"), "{css}");
1590 // Not scaled by the base, for the reason on Stroke.
1591 assert!(!stroke_css_declarations().contains(BASE_TOKEN));
1592 }
1593
1594 #[test]
1595 fn edges_do_not_move_with_density() {
1596 let css = density_css(Some(".ui-mode-mobile"));
1597 assert_eq!(css.matches("--stroke-hairline:").count(), 1, "{css}");
1598 }
1599
1600 #[test]
1601 fn type_does_not_move_with_density() {
1602 // Density is a claim about the contact patch, and text is not a
1603 // target. A --text-* inside the touch override means that argument
1604 // was lost somewhere.
1605 let css = density_css(Some(".ui-mode-mobile"));
1606 let root_end = css.find("@media").expect("a touch block");
1607 assert!(css[..root_end].contains("--text-body"));
1608 assert!(!css[root_end..].contains("--text-"), "{}", &css[root_end..]);
1609 }
1610
1611 #[test]
1612 fn every_type_token_scales_from_the_one_base() {
1613 // A literal rem here would be a size that stops tracking the reader's
1614 // root font size, which is the whole point of the base.
1615 for text in Text::all() {
1616 let css = text.ratio().css();
1617 assert!(css.contains(BASE_TOKEN), "{}: {css}", text.token());
1618 }
1619 }
1620
1621 #[test]
1622 fn wrapping_leaves_no_trailing_whitespace_on_blank_lines() {
1623 // A formatter strips these later and calls it a diff.
1624 let css = in_css_layer("a {\n\nb\n}\n");
1625 assert!(!css.lines().any(|l| l != l.trim_end()), "{css:?}");
1626 }
1627
1628 #[test]
1629 fn the_two_density_conditions_are_complements_and_not_negations() {
1630 let pointer = Density::Pointer.media_condition();
1631 let touch = Density::Touch.media_condition();
1632
1633 // Touch is the negation of the whole Pointer query, not a feature
1634 // list of its own: that is what makes every device land in one.
1635 assert_eq!(touch, format!("not all and {pointer}"));
1636 assert!(pointer.contains(" and "), "pointer must be an AND");
1637 assert!(
1638 !pointer.contains(','),
1639 "a comma is an OR and would match touchscreens"
1640 );
1641 }
1642
1643 #[test]
1644 fn the_emitted_touch_block_is_the_condition_and_not_a_second_copy_of_it() {
1645 // The literal used to be inline here. Nothing may re-spell it.
1646 let css = density_css(None);
1647 assert!(css.contains(&format!("@media {}", Density::Touch.media_condition())));
1648 }
1649
1650 #[test]
1651 fn an_explicit_choice_is_emitted_after_the_detection() {
1652 let css = density_css(Some(".ui-mode-mobile"));
1653 let media = css.find("@media").expect("media query");
1654 let explicit = css.find(".ui-mode-mobile").expect("explicit selector");
1655 // Equal specificity, so order is the whole mechanism: the user's
1656 // choice has to come last or detection quietly overrides it.
1657 assert!(explicit > media, "the explicit selector must come last");
1658 }
1659
1660 #[test]
1661 fn without_an_explicit_selector_there_are_the_default_the_query_and_two_choices() {
1662 assert_eq!(density_css(None).matches("--gap-peer").count(), 4);
1663 }
1664
1665 #[test]
1666 fn a_choice_wins_over_detection_in_both_directions() {
1667 let css = density_css(None);
1668 let media = css.find("@media").expect("media query");
1669 for density in [Density::Pointer, Density::Touch] {
1670 let selector = format!(
1671 ":root[{DENSITY_ATTRIBUTE}=\"{}\"]",
1672 density.attribute_value()
1673 );
1674 let at = css
1675 .find(&format!("{selector} {{"))
1676 .expect("a block per choice");
1677 assert!(at > media, "{selector} must follow the query");
1678 // The block carries this density's gaps and not the other's.
1679 let block = &css[at..at + css[at..].find('}').expect("closed")];
1680 let peer = Gap::Peer.step_at(density).token();
1681 assert!(
1682 block.contains(&format!("--gap-peer: var(--{peer});")),
1683 "{block}"
1684 );
1685 }
1686 }
1687
1688 #[test]
1689 fn a_stored_choice_reads_back_and_nothing_else_is_one() {
1690 for density in [Density::Pointer, Density::Touch] {
1691 assert_eq!(
1692 Density::from_attribute_value(density.attribute_value()),
1693 Some(density)
1694 );
1695 }
1696 for junk in ["", "auto", "Touch", " touch"] {
1697 assert_eq!(Density::from_attribute_value(junk), None, "{junk:?}");
1698 }
1699 }
1700
1701 #[test]
1702 fn the_hig_relationships_land_on_the_hig_values() {
1703 // Mac OS 8 HIG, Control Layout Guidelines. The ratios are ours, but at
1704 // the default base they must resolve to the numbers the HIG specifies,
1705 // or the departure has cost us the thing it was translating.
1706 assert_eq!(Gap::Bound.px(), 4);
1707 assert_eq!(Gap::Peer.px(), 6);
1708 assert_eq!(Gap::Group.px(), 10);
1709 assert_eq!(Gap::Section.px(), 12);
1710 }
1711
1712 #[test]
1713 fn every_ratio_divides_the_default_base_exactly() {
1714 for step in Step::all() {
1715 let r = step.ratio();
1716 assert_eq!(
1717 u32::from(DEFAULT_BASE_PX) * u32::from(r.numerator) % u32::from(r.denominator),
1718 0,
1719 "{step:?} is fractional at the default base"
1720 );
1721 }
1722 }
1723
1724 #[test]
1725 fn ratios_scale_linearly() {
1726 for step in Step::all() {
1727 assert_eq!(
1728 step.ratio().px_at(DEFAULT_BASE_PX * 2),
1729 step.px() * 2,
1730 "{step:?} does not double with the base"
1731 );
1732 }
1733 }
1734
1735 #[test]
1736 fn steps_ascend_and_never_repeat() {
1737 let px: Vec<u16> = Step::all().iter().map(|s| s.px()).collect();
1738 let mut sorted = px.clone();
1739 sorted.sort_unstable();
1740 sorted.dedup();
1741 assert_eq!(px, sorted, "steps must be strictly ascending");
1742 }
1743
1744 #[test]
1745 fn gaps_ascend_with_their_relationships_at_every_density() {
1746 for density in [Density::Pointer, Density::Touch] {
1747 let px: Vec<u16> = Gap::all().iter().map(|g| g.px_at(density)).collect();
1748 let mut sorted = px.clone();
1749 sorted.sort_unstable();
1750 assert_eq!(px, sorted, "{density:?}: a looser relationship is tighter");
1751 }
1752 }
1753
1754 #[test]
1755 fn touch_separates_targets_and_holds_the_shells() {
1756 // The derivation, asserted so that changing it has to come here and say
1757 // so. Touch is a claim about the contact patch: the gaps between
1758 // distinct tap targets open, and the gaps that are not tap targets do
1759 // not move.
1760 for gap in [Gap::Peer, Gap::Group, Gap::Section] {
1761 assert!(
1762 gap.px_at(Density::Touch) > gap.px_at(Density::Pointer),
1763 "{gap:?} separates tap targets and must open on touch"
1764 );
1765 }
1766 for gap in [Gap::Bound, Gap::Pane, Gap::Page] {
1767 assert_eq!(
1768 gap.px_at(Density::Touch),
1769 gap.px_at(Density::Pointer),
1770 "{gap:?} is not a tap target and must not move with the input device"
1771 );
1772 }
1773 }
1774
1775 #[test]
1776 fn touch_never_resolves_tighter_than_pointer() {
1777 // The one cross-density rule, and its direction is the point: a derived
1778 // preset must never set a floor under the one quoted from the HIG.
1779 //
1780 // Constraining Touch by Pointer instead cannot do that. A Pointer
1781 // retune downward moves freely; only a Pointer move upward pushes
1782 // Touch, which is the correct direction of authority.
1783 for gap in Gap::all() {
1784 assert!(
1785 gap.px_at(Density::Touch) >= gap.px_at(Density::Pointer),
1786 "{gap:?}: Touch resolved tighter than Pointer"
1787 );
1788 }
1789 }
1790
1791 #[test]
1792 fn the_pointer_retune_is_not_blocked_by_touch() {
1793 // Touch's own ordering must hold using Touch values only, so that a
1794 // Pointer Pane at or below Touch's Section is legal.
1795 assert!(
1796 Gap::Section.px_at(Density::Touch) <= Gap::Pane.px_at(Density::Touch),
1797 "Touch inverted internally, which is what set the old floor"
1798 );
1799 // Shells tighten by size class rather than by moving the quoted Pointer
1800 // values, so Pointer pane holds at 24. This holds the direction of
1801 // authority: a derived preset never sets a floor under a quoted one.
1802 assert!(Gap::Section.px_at(Density::Touch) >= 16);
1803 }
1804
1805 #[test]
1806 fn shells_tighten_on_a_compact_window_and_nothing_else_does() {
1807 // Shells come down
1808 // one step on a compact window; the four gaps that separate controls
1809 // do not move, because how much room a window has says nothing about
1810 // how far apart two tap targets belong.
1811 for density in [Density::Pointer, Density::Touch] {
1812 assert_eq!(Gap::Pane.px_at_size(density, SizeClass::Compact), 16);
1813 assert_eq!(Gap::Page.px_at_size(density, SizeClass::Compact), 24);
1814
1815 for class in [SizeClass::Medium, SizeClass::Expanded] {
1816 assert_eq!(Gap::Pane.px_at_size(density, class), 24);
1817 assert_eq!(Gap::Page.px_at_size(density, class), 32);
1818 }
1819
1820 for gap in [Gap::Bound, Gap::Peer, Gap::Group, Gap::Section] {
1821 for &class in SizeClass::all() {
1822 assert_eq!(
1823 gap.px_at_size(density, class),
1824 gap.px_at(density),
1825 "{gap:?} moved on {class:?}, and only shells may"
1826 );
1827 }
1828 }
1829 }
1830 }
1831
1832 #[test]
1833 fn the_widths_never_needed_a_step_at_seven_eighths() {
1834 // The retune wanted pane 14, which is 7/8 of the base and off an
1835 // eighths scale that runs 2/4/6/8/10/12/16/24/32/48. It would have
1836 // needed a new public Step variant, and naming one is a cost paid
1837 // forever. Putting the claim on the size-class axis lands both compact
1838 // values on steps that already exist.
1839 for gap in [Gap::Pane, Gap::Page] {
1840 for density in [Density::Pointer, Density::Touch] {
1841 let step = gap.step_at_size(density, SizeClass::Compact);
1842 assert!(
1843 Step::all().contains(&step),
1844 "{gap:?} compact resolved off the scale"
1845 );
1846 }
1847 }
1848 }
1849
1850 #[test]
1851 fn no_size_class_inverts_the_ordering() {
1852 // Collapse is allowed, inversion is not: the same rule the surface
1853 // quantum test applies, now across the third axis. Touch on a compact
1854 // window is the tight one: Section opens to 16 and Pane comes down to
1855 // 16, so they meet. Meeting is fine. Crossing is not.
1856 for density in [Density::Pointer, Density::Touch] {
1857 for &class in SizeClass::all() {
1858 let v: Vec<u16> = Gap::all()
1859 .iter()
1860 .map(|g| g.px_at_size(density, class))
1861 .collect();
1862 let mut sorted = v.clone();
1863 sorted.sort_unstable();
1864 assert_eq!(v, sorted, "{density:?} {class:?} inverted: {v:?}");
1865 }
1866 }
1867 }
1868
1869 #[test]
1870 fn step_at_is_the_wider_window_answer() {
1871 // Every caller that predates the size-class axis meant the wide
1872 // window, so the old entry point has to keep resolving to it or a
1873 // consumer tightens silently on a bump it did not read about.
1874 for gap in Gap::all() {
1875 for density in [Density::Pointer, Density::Touch] {
1876 assert_eq!(
1877 gap.step_at(density),
1878 gap.step_at_size(density, SizeClass::Medium)
1879 );
1880 assert_eq!(
1881 gap.step_at(density),
1882 gap.step_at_size(density, SizeClass::Expanded)
1883 );
1884 }
1885 }
1886 }
1887
1888 #[test]
1889 fn the_width_query_lives_outside_the_density_file() {
1890 // density_is_selected_by_capability_not_by_width_or_agent forbids a
1891 // breakpoint in density_css. This is the other half of that rule: the
1892 // width query has to exist somewhere, and somewhere is here.
1893 let css = size_class_css();
1894 assert!(css.contains(&SizeClass::Compact.media_condition()));
1895 assert!(css.contains("--gap-pane"));
1896 assert!(css.contains("--gap-page"));
1897 // Targets never appear in a width query.
1898 for token in ["--gap-bound", "--gap-peer", "--gap-group", "--gap-section"] {
1899 assert!(!css.contains(token), "{token} crept into a width query");
1900 }
1901 // And it stays out of the density file.
1902 assert!(!density_css(None).contains("width"));
1903 }
1904
1905 #[test]
1906 fn size_classes_partition_every_width_exactly_once() {
1907 // Mutually exclusive and exhaustive, or a rule lands in two classes and
1908 // whichever is emitted last silently wins. Checked at every width up to
1909 // well past the top boundary rather than at the boundaries alone.
1910 for px in 0..=4000u16 {
1911 let hits: Vec<SizeClass> = SizeClass::all()
1912 .iter()
1913 .copied()
1914 .filter(|c| {
1915 let lo = c.min_px();
1916 let hi = match c {
1917 SizeClass::Compact => SizeClass::Medium.min_px() - 1,
1918 SizeClass::Medium => SizeClass::Expanded.min_px() - 1,
1919 SizeClass::Expanded => u16::MAX,
1920 };
1921 px >= lo && px <= hi
1922 })
1923 .collect();
1924 assert_eq!(hits.len(), 1, "{px}px matched {hits:?}");
1925 assert_eq!(hits[0], SizeClass::at_width(px), "{px}px disagrees");
1926 }
1927 }
1928
1929 #[test]
1930 fn the_quoted_boundaries_are_the_ones_material_publishes() {
1931 // Quoted, not derived. Changing these means departing from the source,
1932 // which is a decision to record rather than a value to nudge.
1933 assert_eq!(SizeClass::Compact.min_px(), 0);
1934 assert_eq!(SizeClass::Medium.min_px(), 600);
1935 assert_eq!(SizeClass::Expanded.min_px(), 840);
1936 }
1937
1938 #[test]
1939 fn the_media_conditions_do_not_overlap_at_the_boundary() {
1940 // Each boundary is written once, exclusive below and inclusive above,
1941 // so 599.5px is Compact and 839.5px is Medium.
1942 assert_eq!(SizeClass::Compact.media_condition(), "(width < 600px)");
1943 assert_eq!(
1944 SizeClass::Medium.media_condition(),
1945 "(600px <= width < 840px)"
1946 );
1947 assert_eq!(SizeClass::Expanded.media_condition(), "(width >= 840px)");
1948 }
1949
1950 #[test]
1951 fn the_gap_scale_is_reachable_without_naming_a_size_class() {
1952 // The reasoning for size classes reaching the shells is in the docs on
1953 // Gap::step_at_size. This holds the other half: the whole spacing layer stays reachable without naming a size class. A
1954 // caller that has no idea how wide the window is still gets an answer,
1955 // and it is the wide-window one. Only step_at_size asks.
1956 let _ = geometry_css_vars(Density::Pointer);
1957 let _ = Gap::Page.px_at(Density::Touch);
1958 assert_eq!(SizeClass::all().len(), 3);
1959
1960 // And no size class may reach the four control gaps.
1961 for gap in [Gap::Bound, Gap::Peer, Gap::Group, Gap::Section] {
1962 for &class in SizeClass::all() {
1963 for density in [Density::Pointer, Density::Touch] {
1964 assert_eq!(
1965 gap.step_at_size(density, class),
1966 gap.step_at(density),
1967 "{gap:?} moved on {class:?}: screen budget reached a target gap"
1968 );
1969 }
1970 }
1971 }
1972 }
1973
1974 #[test]
1975 fn a_terminal_resolves_the_vocabulary_to_whole_cells() {
1976 let t = Surface::terminal();
1977 let cells: Vec<u32> = Gap::all()
1978 .iter()
1979 .map(|g| t.gap(*g, Density::Pointer))
1980 .collect();
1981 // bound, peer | group, section | pane, page
1982 assert_eq!(cells, vec![0, 0, 1, 1, 2, 2]);
1983 }
1984
1985 #[test]
1986 fn collapsing_is_allowed_but_inverting_is_not() {
1987 // A coarse surface has fewer distinctions, so neighbouring gaps may
1988 // land on the same quantum. What must never happen is a looser
1989 // relationship coming out tighter than a closer one.
1990 for quantum in [0.5_f32, 1.0, 2.0, 3.0, 7.0] {
1991 for density in [Density::Pointer, Density::Touch] {
1992 let s = Surface {
1993 base: 16.0,
1994 quantum,
1995 };
1996 let v: Vec<u32> = Gap::all().iter().map(|g| s.gap(*g, density)).collect();
1997 let mut sorted = v.clone();
1998 sorted.sort_unstable();
1999 assert_eq!(v, sorted, "quantum {quantum} {density:?} inverted: {v:?}");
2000 }
2001 }
2002 }
2003
2004 #[test]
2005 fn the_web_surface_agrees_with_the_pixel_helper() {
2006 let w = Surface::web();
2007 for step in Step::all() {
2008 assert_eq!(
2009 w.resolve(step.ratio()) as u16,
2010 step.px(),
2011 "{step:?} disagrees between surface and px_at"
2012 );
2013 }
2014 }
2015
2016 #[test]
2017 fn quantising_is_monotonic_in_the_ratio() {
2018 let (base, quantum) = (16.0, 1.0);
2019 let mut previous = 0;
2020 for step in Step::all() {
2021 let q = step.ratio().quanta(base, quantum);
2022 assert!(q >= previous, "{step:?} went backwards");
2023 previous = q;
2024 }
2025 }
2026
2027 #[test]
2028 fn a_degenerate_quantum_yields_nothing_rather_than_panicking() {
2029 let r = Step::Loose.ratio();
2030 for bad in [0.0_f32, -1.0, f32::NAN] {
2031 assert_eq!(r.quanta(16.0, bad), 0);
2032 assert!(r.quantize(16.0, bad).abs() < f32::EPSILON);
2033 }
2034 assert_eq!(r.quanta(f32::INFINITY, 1.0), 0);
2035 }
2036
2037 #[test]
2038 fn px_at_saturates_and_survives_a_zero_denominator() {
2039 assert_eq!(Step::Colossal.ratio().px_at(30_000), u16::MAX);
2040 assert_eq!(ROW_BLOCK.px_at(u16::MAX), u16::MAX);
2041 let big = Ratio {
2042 numerator: u16::MAX,
2043 denominator: 1,
2044 };
2045 assert_eq!(big.px_at(u16::MAX), u16::MAX);
2046 let broken = Ratio {
2047 numerator: 3,
2048 denominator: 0,
2049 };
2050 assert_eq!(broken.px_at(16), 0);
2051 }
2052
2053 #[test]
2054 fn a_zero_denominator_is_nothing_from_every_axis() {
2055 // 3/0 and 0/0 both mean nothing, and every resolver must say so rather
2056 // than one call saturating and another emitting the whole base.
2057 for r in [
2058 Ratio {
2059 numerator: 3,
2060 denominator: 0,
2061 },
2062 Ratio {
2063 numerator: 0,
2064 denominator: 0,
2065 },
2066 ] {
2067 assert_eq!(r.px_at(16), 0, "{r:?}");
2068 assert!(r.scale(16.0).abs() < f32::EPSILON, "{r:?}");
2069 assert_eq!(r.quanta(16.0, 1.0), 0, "{r:?}");
2070 assert!(r.quantize(16.0, 1.0).abs() < f32::EPSILON, "{r:?}");
2071 assert_eq!(r.css(), "calc(var(--geometry-base) * 0)", "{r:?}");
2072 }
2073 }
2074
2075 #[test]
2076 fn px_at_rounds_rather_than_truncating() {
2077 // Eighths divide 16 exactly, so the rounding only shows on a base
2078 // that does not: 3/8 of 15 is 5.625, which is 6px, not 5.
2079 assert_eq!(Step::Snug.ratio().px_at(15), 6);
2080 assert_eq!(Step::Snug.ratio().px_at(DEFAULT_BASE_PX), 6);
2081 }
2082
2083 #[test]
2084 fn tokens_are_unique() {
2085 let mut names: Vec<&str> = Step::all().iter().map(|s| s.token()).collect();
2086 names.extend(Gap::all().iter().map(|g| g.token()));
2087 names.extend(Text::all().iter().map(|t| t.token()));
2088 names.extend(Radius::all().iter().map(|r| r.token()));
2089 names.extend(Stroke::all().iter().map(|s| s.token()));
2090 let count = names.len();
2091 names.sort_unstable();
2092 names.dedup();
2093 assert_eq!(names.len(), count, "token names collide");
2094 }
2095
2096 #[test]
2097 fn css_is_expressed_over_the_base_never_in_pixels() {
2098 let css = geometry_css_vars(Density::Pointer);
2099 assert!(css.starts_with(":root {\n"));
2100 assert!(css.trim_end().ends_with('}'));
2101 assert!(css.contains("--geometry-base: 1rem;"));
2102 for step in Step::all() {
2103 let line = format!("--{}: {}", step.token(), step.ratio().css());
2104 assert!(css.contains(&line), "missing or wrong: {line}");
2105 }
2106 // A hard pixel count anywhere in the scale defeats the point.
2107 let scale = scale_css_declarations();
2108 assert!(
2109 !scale.contains("px;"),
2110 "the scale must not emit pixel literals:\n{scale}"
2111 );
2112 }
2113
2114 #[test]
2115 fn ratio_css_drops_redundant_arithmetic() {
2116 assert_eq!(Step::Loose.ratio().css(), "var(--geometry-base)");
2117 assert_eq!(Step::Vast.ratio().css(), "calc(var(--geometry-base) * 2)");
2118 assert_eq!(
2119 Step::Snug.ratio().css(),
2120 "calc(var(--geometry-base) * 3 / 8)"
2121 );
2122 }
2123
2124 #[test]
2125 fn gaps_reference_steps_rather_than_repeating_values() {
2126 let css = geometry_css_vars(Density::Pointer);
2127 assert!(css.contains("--gap-peer: var(--step-snug);"));
2128 assert!(!css.contains("--gap-peer: calc"));
2129 }
2130
2131 #[test]
2132 fn a_density_override_emits_only_the_relational_layer() {
2133 let css = gap_css_overrides(".ui-mode-mobile", Density::Touch);
2134 // Which step Peer lands on is the preset's business, asserted in
2135 // touch_separates_targets_and_holds_the_shells. This says only that the
2136 // gap is emitted and references a step.
2137 assert!(css.contains("--gap-peer: var(--step-"));
2138 // Referencing a step is the point; re-declaring one would fork the
2139 // scale, so the check is on declarations, not on mentions.
2140 let declared: Vec<&str> = css
2141 .lines()
2142 .filter_map(|l| l.trim().strip_prefix("--"))
2143 .filter_map(|l| l.split(':').next())
2144 .collect();
2145 assert!(
2146 declared.iter().all(|t| t.starts_with("gap-")),
2147 "only the relational layer may be overridden, got {declared:?}"
2148 );
2149 }
2150
2151 #[test]
2152 fn a_density_override_leaves_the_shells_to_the_size_class() {
2153 // The shells answer to window width, so a density block that
2154 // re-declared them would outrank the compact block: its attribute
2155 // selector on :root is more specific than the plain :root the width
2156 // query uses, and an explicit touch choice on a phone would then lose
2157 // the compact shells. Only the base :root may name them.
2158 let css = density_css(Some(".ui-mode-mobile"));
2159 assert_eq!(css.matches("--gap-pane").count(), 1, "{css}");
2160 assert_eq!(css.matches("--gap-page").count(), 1, "{css}");
2161 assert_eq!(css.matches("--gap-bound").count(), 1, "{css}");
2162 let explicit = css
2163 .rsplit(".ui-mode-mobile {")
2164 .next()
2165 .expect("an explicit block");
2166 assert!(explicit.contains("--gap-peer:"), "{explicit}");
2167 for shell in ["--gap-pane", "--gap-page", "--gap-bound"] {
2168 assert!(!explicit.contains(shell), "{shell} in {explicit}");
2169 }
2170 }
2171
2172 #[test]
2173 fn a_table_row_is_45px_at_the_default_base_and_emitted_once() {
2174 assert_eq!(ROW_BLOCK.px_at(DEFAULT_BASE_PX), 45);
2175 let css = geometry_css_vars(Density::Pointer);
2176 assert_eq!(css.matches("--row-block:").count(), 1, "{css}");
2177 assert!(
2178 css.contains("--row-block: calc(var(--geometry-base) * 45 / 16);"),
2179 "{css}"
2180 );
2181 }
2182}