Skip to main content

makeover_touch/
lib.rs

1//! The adaptation layer of the make-family design system.
2//!
3//! <!-- wiki: makeover-touch -->
4//!
5//! `makeover` answers *what colour*. `makeover-geometry` answers *how much
6//! space*, and owns the two axes an adaptation is stated against:
7//! [`Density`] (pointer or touch) and [`SizeClass`] (compact, medium,
8//! expanded). `makeover-layout` answers *what the thing is*. This crate
9//! answers one question and no other:
10//!
11//! > Does this affordance exist here?
12//!
13//! Like `makeover-layout` it emits nothing. It is a description, rendered to
14//! CSS by `makeover-webview` and to whatever the other renderers can express.
15//!
16//! # Why this is a crate and not a density preset
17//!
18//! What an adaptive stylesheet changes falls into buckets, and each has an
19//! owner:
20//!
21//! | bucket | retired by |
22//! |---|---|
23//! | density | a `makeover-geometry` preset |
24//! | type | the type scale |
25//! | columns | `makeover_layout::Column` |
26//! | reflow | `makeover_layout::Arrangement` |
27//! | **show/hide** | **this crate** |
28//! | **reposition** | **this crate** |
29//! | **appearance** | **this crate** |
30//!
31//! The bottom three are what no spacing scale can retire. `display: none` on a
32//! keyboard hint says *the affordance does not exist on touch*. No amount of
33//! gap retuning expresses that, and a scale that tried would be putting a
34//! product claim on a measurement axis.
35//!
36//! [`Affordance::Gesture`] and [`Affordance::Haptic`] adapt *behaviour*, which
37//! no stylesheet contains. Without them the density question gets answered in
38//! script by sniffing (`'ontouchstart' in window`), where no stylesheet can see
39//! it.
40//!
41//! # The two axes are borrowed, never redefined
42//!
43//! Boundaries are not this crate's job. `makeover-geometry` quotes Material 3's
44//! window size classes at 600 and 840 and carries [`Density`]; this crate names
45//! affordances *against* those two and adds no third axis, no fourth class and
46//! no breakpoint of its own. If a rule here wants a boundary that does not
47//! exist, that is a conversation with `makeover-geometry`, not a constant.
48//!
49//! # What density is allowed to gate
50//!
51//! Density is a claim about **the contact patch and nothing else**. So it gates
52//! affordances that depend on an interaction a fingertip cannot perform:
53//! hovering, and the keyboard chrome that documents shortcuts a touch surface
54//! has no way to send. It does not gate anything that is really about how much
55//! screen there is. A phone is small *and* touch; a tablet is big *and* touch.
56//!
57//! `density_gates_only_what_the_contact_patch_touches` asserts that separation. Putting a screen-budget
58//! claim on the input device is the failure this crate exists to prevent, and
59//! re-introducing it has to come to the test and say so.
60//!
61//! # Both densities gain something
62//!
63//! Touch is not pointer minus what a fingertip cannot do.
64//! [`Affordance::Hover`]'s own doc says a fingertip has no hover state *and that
65//! something else has to carry the same actions*, so something here has to be
66//! that something. [`Affordance::Anchored`] and [`Affordance::Overflow`]
67//! compensate on the size axis; [`Affordance::Gesture`] and
68//! [`Affordance::Haptic`] compensate on the density axis, and both are gained
69//! by touch rather than lost to it.
70//!
71//! [`Affordance::gained_by`] makes each member declare which density it belongs
72//! to, and
73//! `a_density_member_is_available_on_exactly_the_density_it_declares` checks the
74//! declaration against the rule. So a new member still cannot quietly invert:
75//! it has to say which way it goes, in code, and the test is where a wrong
76//! answer surfaces.
77//!
78//! # Collapsing is allowed, inverting is not
79//!
80//! Borrowed verbatim from `makeover-geometry`, where two gap relationships both
81//! resolve to zero cells on a terminal and stay two members regardless. Two
82//! affordances here may have identical availability ([`Affordance::Hover`] and
83//! [`Affordance::Hint`] do) and are still two members, because the call
84//! site names *what is being gated*, not the rule. What must never happen is
85//! one of them becoming available where the other is not for a reason that is
86//! really the same reason.
87//!
88//! # Deliberately absent
89//!
90//! **A navigation shell fork.** Two navigation shells behind one breakpoint are
91//! two shells rather than one shell adapting, and choosing to build two is a
92//! product decision. This crate will not describe it. Named here the way
93//! `makeover-layout` names validation absent, so nobody has to discover it.
94//!
95//! **Which columns a narrow window keeps.** A column is ranked rather than
96//! gated, so the cutoff for a size class lives with the ranking, in
97//! `makeover-layout`'s `column` module.
98//!
99//! **Which class applies.** The app decides, from a measured width via
100//! [`SizeClass::at_width`] and from whatever it already knows about the input.
101//! This crate takes both as arguments and never sniffs.
102//!
103//! **What a renderer does when an affordance is unavailable.** Hiding it,
104//! substituting it, or showing it unconditionally anyway is renderer policy.
105//! `makeover-layout` already deleted `Fill::fallback` for being exactly that.
106
107#![forbid(unsafe_code)]
108
109pub use makeover_geometry::{Density, SizeClass};
110
111/// An affordance whose existence depends on the surface it is offered on.
112///
113/// Drawn from what apps already gate by hand rather than from a taxonomy. `makeover-layout`'s warning applies and is the
114/// reason each addition has to point at call sites rather than at a category:
115/// guessing is how a description becomes a framework.
116///
117/// Each answers [`Self::available`] against the two axes and nothing else. An
118/// affordance that is always available is not an affordance this crate has
119/// anything to say about, and `every_member_is_an_adaptation` asserts none has
120/// snuck in.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
122#[non_exhaustive]
123pub enum Affordance {
124    /// Anything a consumer reveals on hover: a row's action cluster, a
125    /// hover toolbar, a preview popover.
126    ///
127    /// `makeover-layout` records hover-revealed row actions as behaviour of
128    /// `RowPart::Actions` rather than as app policy. A fingertip has no hover
129    /// state at all, so the affordance does not exist on touch, and something
130    /// else has to carry the same actions: [`Self::Gesture`].
131    Hover,
132    /// Chrome documenting a keyboard interaction: shortcut badges, key hints,
133    /// a "press / to search" line.
134    ///
135    /// Strictly this is a claim about
136    /// having a keyboard rather than about the contact patch, and [`Density`]
137    /// is the closest honest proxy the family carries. Stated rather than
138    /// hidden, because a detachable-keyboard tablet is where the proxy breaks
139    /// and a third axis is what fixing it would cost.
140    Hint,
141    /// A secondary panel standing beside the primary content: a saved-views
142    /// rail, a filter sidebar, an inspector.
143    ///
144    /// Purely a screen-budget claim (a touchscreen laptop should keep it), so
145    /// this reads [`SizeClass`] alone.
146    Ancillary,
147    /// The detail half of a list-detail split, shown *alongside* the list
148    /// rather than navigated to.
149    ///
150    /// Unavailable is not the same as absent: the detail still exists, it is
151    /// reached by navigation instead of by adjacency, and which of the two a
152    /// screen gets is what `makeover-layout`'s `Arrangement` is describing.
153    Detail,
154    /// Navigation or a primary action cluster pinned to a fixed screen edge
155    /// instead of sitting in the flow of the page.
156    ///
157    /// The reposition bucket. It exists to compensate for what a compact window cannot hold in flow,
158    /// so unlike the two above it is available at the *narrow* end and not the
159    /// wide one. That inversion is the point: an adaptation that only ever
160    /// removes things describes a degraded layout rather than a different one.
161    Anchored,
162    /// An action cluster collapsed behind one control rather than laid out
163    /// inline.
164    ///
165    /// The other compensating member. `makeover-layout`'s `Column::kept_at`
166    /// already handles a *table* narrowing by dropping columns; this is the
167    /// same pressure on a cluster of controls, which cannot drop any of them
168    /// and folds instead.
169    Overflow,
170    /// A direct-manipulation gesture on content: swipe-to-action, long-press to
171    /// select, pull to refresh, swipe to navigate, drag to dismiss.
172    ///
173    /// The density axis's compensating member, and the answer to the question
174    /// [`Self::Hover`] asks and cannot answer. A fingertip has no hover state,
175    /// so the row actions a pointer reveals by hovering have to arrive some
176    /// other way; on both webview apps that way is a swipe.
177    ///
178    /// **One member for five gestures, on purpose.** Apps gate all five behind
179    /// one fact about the surface, so five members would be minted from one.
180    /// If a surface ever offers swipe without long-press, splitting this is
181    /// additive and the call sites that named `Gesture` keep meaning what they
182    /// meant.
183    Gesture,
184    /// Confirmation delivered through the contact patch rather than the eye: the
185    /// tick as a drag crosses a threshold, the thump as a gesture fires.
186    ///
187    /// A contact-patch claim, which is what makes it this crate's business
188    /// despite being the one member nothing on screen shows.
189    ///
190    /// The proxy breaks where the hardware has haptics and the user or the OS
191    /// has switched them off. That is neither [`Density`] nor [`SizeClass`], and
192    /// it is stated here rather than fixed for the same reason [`Self::Hint`]
193    /// states the detachable-keyboard case: a third axis is what fixing it would
194    /// cost. **This member says the surface can, never that the user wants.**
195    /// Asking the platform whether haptics are enabled is the renderer's job.
196    Haptic,
197}
198
199impl Affordance {
200    /// Whether this affordance exists on a surface with the given input class
201    /// and screen budget.
202    ///
203    /// The whole crate in one call. A renderer asks per affordance and never
204    /// branches on a width.
205    #[must_use]
206    pub const fn available(self, density: Density, size: SizeClass) -> bool {
207        match self {
208            // Contact patch, lost to a fingertip.
209            Self::Hover | Self::Hint => matches!(density, Density::Pointer),
210            // Contact patch, gained by one. A mouse can neither swipe a row nor
211            // feel a confirmation, and a phone-sized window has nothing to do
212            // with either.
213            Self::Gesture | Self::Haptic => matches!(density, Density::Touch),
214            // Screen budget. The input device has no opinion about any of them.
215            Self::Ancillary => matches!(size, SizeClass::Expanded),
216            Self::Detail => matches!(size, SizeClass::Medium | SizeClass::Expanded),
217            Self::Anchored | Self::Overflow => matches!(size, SizeClass::Compact),
218        }
219    }
220
221    /// Which [`Density`] this affordance belongs to, or `None` when it reads the
222    /// screen budget instead.
223    ///
224    /// Each member declares its own direction, and
225    /// `a_density_member_is_available_on_exactly_the_density_it_declares` holds
226    /// the declaration to the rule. There is no crate-wide one-directional
227    /// rule: see the crate doc.
228    ///
229    /// Exposed rather than kept private for the same reason [`Self::reads_density`]
230    /// is: it is the crate's claim about itself, and a renderer that has one
231    /// density can read it directly instead of probing [`Self::available`] twice.
232    #[must_use]
233    pub const fn gained_by(self) -> Option<Density> {
234        match self {
235            Self::Hover | Self::Hint => Some(Density::Pointer),
236            Self::Gesture | Self::Haptic => Some(Density::Touch),
237            Self::Ancillary | Self::Detail | Self::Anchored | Self::Overflow => None,
238        }
239    }
240
241    /// Which of the two axes this affordance's availability reads.
242    ///
243    /// Declared per member rather than derived, so the tests can hold each
244    /// declaration against what [`Self::available`] actually does.
245    #[must_use]
246    pub const fn axis(self) -> Axis {
247        match self {
248            Self::Hover | Self::Hint | Self::Gesture | Self::Haptic => Axis::Density,
249            Self::Ancillary | Self::Detail | Self::Anchored | Self::Overflow => Axis::Size,
250        }
251    }
252
253    /// Whether this affordance's availability reads [`Density`] at all.
254    ///
255    /// Exposed rather than kept private because it is the crate's own claim
256    /// about itself: exactly the members gating a contact-patch interaction say
257    /// yes. A renderer with one density can skip the rest entirely.
258    #[must_use]
259    pub const fn reads_density(self) -> bool {
260        matches!(self.axis(), Axis::Density)
261    }
262
263    /// Whether this affordance's availability reads [`SizeClass`] at all.
264    #[must_use]
265    pub const fn reads_size(self) -> bool {
266        matches!(self.axis(), Axis::Size)
267    }
268
269    /// Every member, in declaration order.
270    ///
271    /// A slice rather than an array, so a new member changes a length and not
272    /// a type: `Affordance` is `#[non_exhaustive]` for exactly that reason.
273    #[must_use]
274    pub const fn all() -> &'static [Self] {
275        &[
276            Self::Hover,
277            Self::Hint,
278            Self::Ancillary,
279            Self::Detail,
280            Self::Anchored,
281            Self::Overflow,
282            Self::Gesture,
283            Self::Haptic,
284        ]
285    }
286
287    /// The CSS class name an app may hang off this, without the leading dot.
288    ///
289    /// Present for the same reason [`SizeClass::token`] is: a webview renderer
290    /// needs a stable name, and minting it per app is how two apps end up with
291    /// `has-hover` and `hover-capable`.
292    #[must_use]
293    pub const fn token(self) -> &'static str {
294        match self {
295            Self::Hover => "offers-hover",
296            Self::Hint => "offers-hint",
297            Self::Ancillary => "offers-ancillary",
298            Self::Detail => "offers-detail",
299            Self::Anchored => "offers-anchored",
300            Self::Overflow => "offers-overflow",
301            Self::Gesture => "offers-gesture",
302            Self::Haptic => "offers-haptic",
303        }
304    }
305}
306
307/// The axis an [`Affordance`] reads: the input class or the screen budget.
308///
309/// Every member reads exactly one. `#[non_exhaustive]` because a member that
310/// genuinely read both would be added here as a third answer, and
311/// `no_member_reads_both_axes` is where that claim would be withdrawn.
312#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
313#[non_exhaustive]
314pub enum Axis {
315    /// [`Density`]: pointer or touch.
316    Density,
317    /// [`SizeClass`]: compact, medium or expanded.
318    Size,
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324
325    /// Whether `a`'s availability changes with density at any size.
326    fn varies_by_density(a: Affordance) -> bool {
327        SizeClass::all()
328            .iter()
329            .any(|&s| a.available(Density::Pointer, s) != a.available(Density::Touch, s))
330    }
331
332    /// Whether `a`'s availability changes with size at either density.
333    fn varies_by_size(a: Affordance) -> bool {
334        [Density::Pointer, Density::Touch].iter().any(|&d| {
335            SizeClass::all()
336                .iter()
337                .any(|&s| a.available(d, s) != a.available(d, SizeClass::Compact))
338        })
339    }
340
341    /// Every combination of the two axes, narrowest and coarsest first.
342    fn surfaces() -> Vec<(Density, SizeClass)> {
343        let mut out = Vec::new();
344        for d in [Density::Pointer, Density::Touch] {
345            for &s in SizeClass::all() {
346                out.push((d, s));
347            }
348        }
349        out
350    }
351
352    #[test]
353    fn density_gates_only_what_the_contact_patch_touches() {
354        // The failure this crate exists to avoid: a screen-budget claim
355        // smuggled onto the input axis, which is what let the old Touch gap
356        // preset set a floor under a preset quoted from the HIG. Adding a
357        // density dependency to a screen-budget affordance has to come here
358        // and say so.
359        for &a in Affordance::all() {
360            assert_eq!(
361                varies_by_density(a),
362                a.reads_density(),
363                "{a:?} disagrees with its own reads_density()"
364            );
365        }
366    }
367
368    #[test]
369    fn size_gates_only_what_screen_budget_touches() {
370        for &a in Affordance::all() {
371            assert_eq!(
372                varies_by_size(a),
373                a.reads_size(),
374                "{a:?} disagrees with its own reads_size()"
375            );
376        }
377    }
378
379    #[test]
380    fn no_member_reads_both_axes() {
381        // Not a law of adaptation, a statement about the members that exist.
382        // Measured off `available`, so a member whose rule starts reading the
383        // second axis fails here whatever its `axis` declares. A member that
384        // genuinely reads both is allowed, and this test is where the claim
385        // gets withdrawn rather than quietly falsified.
386        for &a in Affordance::all() {
387            assert!(
388                !(varies_by_density(a) && varies_by_size(a)),
389                "{a:?} reads both axes; update this test and say why"
390            );
391        }
392    }
393
394    #[test]
395    fn every_member_is_an_adaptation() {
396        // A member available everywhere, or nowhere, is not describing an
397        // adaptation and does not belong in this crate.
398        for &a in Affordance::all() {
399            let yes = surfaces()
400                .iter()
401                .filter(|&&(d, s)| a.available(d, s))
402                .count();
403            assert!(yes > 0, "{a:?} exists on no surface");
404            assert!(yes < surfaces().len(), "{a:?} exists on every surface");
405        }
406    }
407
408    #[test]
409    fn availability_is_contiguous_across_the_size_ladder() {
410        // No member may exist at compact and expanded but not medium. A hole
411        // in the middle is always an off-by-one, never a design.
412        for &a in Affordance::all() {
413            for d in [Density::Pointer, Density::Touch] {
414                let run: Vec<bool> = SizeClass::all()
415                    .iter()
416                    .map(|&s| a.available(d, s))
417                    .collect();
418                let transitions = run.windows(2).filter(|w| w[0] != w[1]).count();
419                assert!(
420                    transitions <= 1,
421                    "{a:?} at {d:?} is available in a broken run: {run:?}"
422                );
423            }
424        }
425    }
426
427    #[test]
428    fn compact_compensates_rather_than_only_losing() {
429        // The reposition bucket is the reason this crate is not just a
430        // hide-list. Whatever compact takes
431        // away, something has to give back.
432        for d in [Density::Pointer, Density::Touch] {
433            assert!(!Affordance::Detail.available(d, SizeClass::Compact));
434            assert!(Affordance::Anchored.available(d, SizeClass::Compact));
435        }
436    }
437
438    #[test]
439    fn hover_and_hint_collapse_and_that_is_allowed() {
440        // Borrowed from makeover-geometry, where bound and peer both resolve to
441        // zero cells on a terminal and stay two members. Identical rules are
442        // not a duplicate; the call site names what is gated.
443        for (d, s) in surfaces() {
444            assert_eq!(
445                Affordance::Hover.available(d, s),
446                Affordance::Hint.available(d, s)
447            );
448        }
449        assert_ne!(Affordance::Hover.token(), Affordance::Hint.token());
450    }
451
452    /// The other density. Two members, so this is total, and writing it here
453    /// rather than in `makeover-geometry` keeps the axis definition borrowed
454    /// rather than extended.
455    fn opposite(d: Density) -> Density {
456        match d {
457            Density::Pointer => Density::Touch,
458            Density::Touch => Density::Pointer,
459        }
460    }
461
462    #[test]
463    fn a_density_member_is_available_on_exactly_the_density_it_declares() {
464        // Direction is a property of each member rather than of the crate:
465        // Gesture and Haptic are gained by touch. A member still cannot invert
466        // quietly. It declares its density in `gained_by`, and this is where a
467        // declaration that disagrees with the rule shows up.
468        for &a in Affordance::all() {
469            match a.gained_by() {
470                Some(gained) => {
471                    assert!(
472                        a.reads_density(),
473                        "{a:?} declares a density but denies reading one"
474                    );
475                    for &s in SizeClass::all() {
476                        assert!(
477                            a.available(gained, s),
478                            "{a:?} declares {gained:?} but is unavailable there at {s:?}"
479                        );
480                        assert!(
481                            !a.available(opposite(gained), s),
482                            "{a:?} declares {gained:?} but is also available on the other density at {s:?}"
483                        );
484                    }
485                }
486                None => assert!(
487                    !a.reads_density(),
488                    "{a:?} reads density but declares no side"
489                ),
490            }
491        }
492    }
493
494    #[test]
495    fn both_densities_gain_something() {
496        // A crate where only pointer gains members describes touch as a lesser
497        // pointer. If the touch-gained members ever go, this fails rather than
498        // passing quietly on an empty set.
499        for d in [Density::Pointer, Density::Touch] {
500            assert!(
501                Affordance::all().iter().any(|a| a.gained_by() == Some(d)),
502                "no member is gained by {d:?}"
503            );
504        }
505    }
506
507    #[test]
508    fn the_density_axis_compensates_rather_than_only_losing() {
509        // The density-axis twin of `compact_compensates_rather_than_only_losing`:
510        // Hover's own doc says something else has to carry the actions a
511        // fingertip cannot hover to reveal, and Gesture is that something.
512        for &s in SizeClass::all() {
513            assert!(!Affordance::Hover.available(Density::Touch, s));
514            assert!(Affordance::Gesture.available(Density::Touch, s));
515        }
516    }
517
518    #[test]
519    fn tokens_are_distinct() {
520        let mut seen: Vec<&str> = Affordance::all().iter().map(|a| a.token()).collect();
521        seen.sort_unstable();
522        let before = seen.len();
523        seen.dedup();
524        assert_eq!(seen.len(), before);
525    }
526
527    #[test]
528    fn the_axes_are_borrowed_not_redefined() {
529        // Re-exported rather than mirrored, so there is exactly one definition
530        // of each in the family. A local copy is how two crates start
531        // disagreeing about where 600px is.
532        assert_eq!(SizeClass::Medium.min_px(), 600);
533        assert_eq!(SizeClass::Expanded.min_px(), 840);
534        assert_eq!(SizeClass::at_width(599), SizeClass::Compact);
535    }
536}