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