makeover_timing/lib.rs
1//! The time axis of the make-family design system.
2//!
3//! <!-- wiki: makeover-timing -->
4//!
5//! [`makeover`] resolves colour, `makeover-geometry` resolves distance, and
6//! `makeover-layout` names what a thing is without resolving anything. This
7//! crate answers the remaining question of the same shape: **how long**.
8//!
9//! The move is the one the family makes everywhere. A duration is named by
10//! what it is waiting for, and the number follows:
11//!
12//! | Moment | What it waits for | Resolves to |
13//! |---|---|---|
14//! | [`Moment::Revert`] | a control returning to its resting label after confirming | 1500ms |
15//! | [`Moment::Clear`] | a status line emptying itself | 2000ms |
16//! | [`Moment::Dismiss`] | a transient notice's lifetime | 3000ms |
17//! | [`Moment::Debounce`] | typing settling before the work starts | 150ms |
18//!
19//! Whether a toast should live 3000ms or 3500ms is unanswerable on its own.
20//! Whether a message is a toast or a banner is not. That is the whole argument
21//! for the layer, and it is the same one [`Gap`](makeover_geometry::Gap) makes
22//! about six pixels.
23//!
24//! # One duration per moment, on every renderer
25//!
26//! A moment resolves to exactly one duration everywhere, whatever the renderer
27//! and whatever the theme.
28//!
29//! A per-renderer table, resolving the way
30//! [`Density`](makeover_geometry::Density) resolves gaps, is the wrong shape.
31//! Distance has a renderer axis because a fingertip is coarser than a cursor
32//! and a terminal cell is coarser than a pixel: the *surface* differs. Time
33//! does not differ that way. A second is a second in a browser, in egui and in
34//! a terminal, and the reader waiting it out is the same reader.
35//!
36//! So a divergence here is a bug report.
37//!
38//! # What is deliberately not a moment
39//!
40//! Three classes are out of scope, and leaving them out is most of what makes
41//! the four above coherent.
42//!
43//! **A race is not a moment.** Waiting 300ms before navigating because the
44//! write "should" have landed, or 150ms before closing a dropdown so a
45//! mousedown can beat the blur, is a synchronisation bug wearing a duration's
46//! clothes. Naming those would launder them into design decisions and give
47//! every future one a token to hide behind. They get fixed per screen.
48//!
49//! **Severity is not a moment either, and it is not a fifth number.** A longer
50//! lifetime for an error toast is one statement in disguise: *a message the
51//! user must not miss does not go away on its own*. `makeover-layout` already
52//! has the word for it: such a message is not `Notice::transient`. It is a
53//! banner, and a banner has no lifetime. See [`notice_lifetime`].
54//!
55//! **A poll interval is not a moment.** A retry backoff, a health check, an
56//! update check: those are answerable from what they talk to, not from what a
57//! reader can follow, and nothing here has an opinion about them.
58//!
59//! # Motion is a separate axis
60//!
61//! [`Moment`] says how long a state lasts. [`Motion`] says how long a change
62//! takes. CSS itself draws that line, a `setTimeout` against a
63//! `transition-duration`, and folding the two together makes a "timing scale"
64//! unusable: 300ms of fade and 3000ms of toast answer different questions.
65//!
66//! [`Motion`] is an enum rather than a constant so a second measured
67//! transition has somewhere to go. It grows when something is measured.
68//!
69//! # Cadence is a third question
70//!
71//! [`Moment`] is how long a state lasts and [`Motion`] is how long a change
72//! takes. Both are one-shot: something starts, it ends. [`Cadence`] is how
73//! often a repeating mark repeats, which neither of the other two can answer
74//! without lying about its own shape.
75//!
76//! The crate header's exclusion of poll intervals does not cover it, and the
77//! difference is the same one that exclusion rests on. A backoff or a health
78//! check is answerable from what it talks to. How fast a mark may blink before
79//! it reads as an alarm is answerable from the reader, which is what every rung
80//! in this crate is answerable from.
81//!
82//! # Reduced motion
83//!
84//! Anything whose whole existence is movement has a motion-off path, and
85//! [`Cadence`] is that. A duration that is not animating anything is
86//! unaffected: [`Moment::Debounce`] is a wait, and reducing motion does not
87//! make input settle faster.
88//!
89//! Two halves, because a browser and an egui window learn about the preference
90//! differently. A web surface gets a `prefers-reduced-motion` block in the
91//! generated stylesheet and needs no code. Every other renderer asks
92//! [`activity_blink`] with the [`MotionPreference`] its platform reported, as
93//! it asks [`notice_lifetime`] with the [`Persistence`] the description gave.
94//!
95//! # The numbers
96//!
97//! Each value is pinned by a test. Changing one is a design decision about
98//! every consumer at once, so the test failing is that argument happening out
99//! loud. What each is answerable to is stated on the member.
100//!
101//! # Consumers
102//!
103//! Web surfaces bake [`timing_css`] in at build time. Nothing here changes at
104//! runtime, so there is no load-time JS step, exactly as with geometry. egui
105//! and ratatui surfaces read [`Moment::duration`] instead, which is why this
106//! is a crate rather than a stylesheet.
107//!
108//! [`makeover`]: https://makenot.work/git/max/makeover
109
110#![forbid(unsafe_code)]
111
112use std::fmt::Write as _;
113use std::time::Duration;
114
115use makeover_geometry::in_css_layer;
116
117/// A duration named by what it is waiting for.
118///
119/// Each member is a thing a reader is waiting through, and the crate header
120/// says what is deliberately left out. Adding one means naming a wait a
121/// renderer is already having.
122///
123/// Named `Moment` rather than `Intent` so it cannot be confused with
124/// `makeover_layout::Intent`, which names what a thing is rather than how long
125/// a state lasts.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
127pub enum Moment {
128 /// How long a control shows that it did something before returning to its
129 /// resting label.
130 ///
131 /// "Copied!" on a button that said "Copy link". Long enough to be read
132 /// after the eye has moved back to it, short enough that the control is
133 /// honest about its own label again before the next click.
134 Revert,
135 /// How long a status line holds a message before emptying itself.
136 ///
137 /// The message is a receipt for something the user just did, so it is read
138 /// or not read immediately. Holding it longer means the next glance at that
139 /// line reports stale news.
140 Clear,
141 /// How long a transient notice lives before it starts to leave.
142 ///
143 /// Excludes the leaving itself, which is [`Motion::Fade`]. A notice the
144 /// user must not miss is not transient and gets no lifetime at all; see
145 /// [`notice_lifetime`].
146 Dismiss,
147 /// How long input waits to settle before the work behind it starts.
148 ///
149 /// A search field that queries on every keystroke, filtered through this.
150 /// The number is a claim about typing rather than about the query: below
151 /// roughly 100ms an ordinary typist trips it mid-word, and above roughly
152 /// 250ms the field feels like it stopped listening.
153 Debounce,
154}
155
156impl Moment {
157 /// The duration in whole milliseconds.
158 ///
159 /// The primary resolution. [`Self::duration`] and [`Self::css`] are both
160 /// spellings of this number, so there is exactly one place it lives.
161 #[must_use]
162 pub const fn ms(self) -> u32 {
163 match self {
164 Self::Revert => 1500,
165 Self::Clear => 2000,
166 Self::Dismiss => 3000,
167 Self::Debounce => 150,
168 }
169 }
170
171 /// The duration as a [`Duration`], for the renderers that are not a
172 /// browser.
173 #[must_use]
174 pub const fn duration(self) -> Duration {
175 Duration::from_millis(self.ms() as u64)
176 }
177
178 /// The CSS custom property name, without the leading dashes.
179 #[must_use]
180 pub const fn token(self) -> &'static str {
181 match self {
182 Self::Revert => "timing-revert",
183 Self::Clear => "timing-clear",
184 Self::Dismiss => "timing-dismiss",
185 Self::Debounce => "timing-debounce",
186 }
187 }
188
189 /// The CSS value, as a `ms` time.
190 ///
191 /// Milliseconds rather than seconds at every rung, including the ones that
192 /// divide evenly: a stylesheet where some durations read `1.5s` and others
193 /// `150ms` cannot be scanned for the odd one out.
194 #[must_use]
195 pub fn css(self) -> String {
196 format!("{}ms", self.ms())
197 }
198
199 /// Every moment, in the order they are emitted.
200 ///
201 /// A slice rather than an array, so adding a member changes a length and
202 /// not a type.
203 #[must_use]
204 pub const fn all() -> &'static [Self] {
205 &[Self::Revert, Self::Clear, Self::Dismiss, Self::Debounce]
206 }
207}
208
209/// How long a change takes, as opposed to how long a state lasts.
210///
211/// See the crate header for why this is not a [`Moment`]. It grows from a
212/// measurement rather than from the scale looking short.
213#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
214pub enum Motion {
215 /// A thing leaving: opacity to zero, then gone.
216 ///
217 /// The whole of the departure. A renderer that removes the node itself has
218 /// to wait this out first, or it drops the animation mid-stroke.
219 Fade,
220}
221
222impl Motion {
223 /// The duration in whole milliseconds.
224 #[must_use]
225 pub const fn ms(self) -> u32 {
226 match self {
227 Self::Fade => 300,
228 }
229 }
230
231 /// The duration as a [`Duration`].
232 #[must_use]
233 pub const fn duration(self) -> Duration {
234 Duration::from_millis(self.ms() as u64)
235 }
236
237 /// The CSS custom property name, without the leading dashes.
238 #[must_use]
239 pub const fn token(self) -> &'static str {
240 match self {
241 Self::Fade => "motion-fade",
242 }
243 }
244
245 /// The CSS value, as a `ms` time.
246 #[must_use]
247 pub fn css(self) -> String {
248 format!("{}ms", self.ms())
249 }
250
251 /// Every motion, in the order they are emitted.
252 #[must_use]
253 pub const fn all() -> &'static [Self] {
254 &[Self::Fade]
255 }
256}
257
258/// How often a repeating mark repeats.
259///
260/// The third question, and see the crate header for why it is neither a
261/// [`Moment`] nor a [`Motion`]. It grows the same way the others do.
262#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
263pub enum Cadence {
264 /// How long the activity mark holds each of its two states.
265 ///
266 /// The hard-disk light: a small mark saying that something is happening,
267 /// on a wait with no countable size. `makeover-layout`'s `Awaiting` is what
268 /// says the wait has no size; this is how fast the answer to that blinks.
269 ///
270 /// **A half-period, not a cycle.** The mark is lit for this long, dark for
271 /// this long, and a full cycle is twice it. One number rather than a period
272 /// plus a duty cycle, because two numbers are two things three renderers
273 /// can disagree about, and a mark that is lit a fifth of the time in a
274 /// browser and half the time in a terminal is not one mark.
275 ///
276 /// 500ms, so a cycle is a second. What it is answerable to is the eye: fast
277 /// enough that a glance catches it working, slow enough that it
278 /// reads as steady work rather than as an alarm. A blink much under half a
279 /// second is a strobe and starts to claim urgency the wait has not earned.
280 ///
281 /// This is the *fallback*, and on most surfaces it should be the rarer
282 /// case. Where the activity is observable the mark follows it, per rule 3
283 /// of wiki `loading-and-progress-standard`: an upload blinks per chunk
284 /// delivered, and this is for the waits with nothing to watch.
285 Activity,
286}
287
288impl Cadence {
289 /// The duration in whole milliseconds.
290 #[must_use]
291 pub const fn ms(self) -> u32 {
292 match self {
293 Self::Activity => 500,
294 }
295 }
296
297 /// The duration as a [`Duration`].
298 #[must_use]
299 pub const fn duration(self) -> Duration {
300 Duration::from_millis(self.ms() as u64)
301 }
302
303 /// One full on-and-off cycle, which is twice the half-period.
304 ///
305 /// Spelled here rather than doubled at each call site: a renderer driving a
306 /// two-state toggle wants [`duration`](Self::duration), and one scheduling
307 /// a whole cycle wants this, and neither should be doing the arithmetic.
308 #[must_use]
309 pub const fn cycle(self) -> Duration {
310 Duration::from_millis(self.ms() as u64 * 2)
311 }
312
313 /// The CSS custom property name, without the leading dashes.
314 #[must_use]
315 pub const fn token(self) -> &'static str {
316 match self {
317 Self::Activity => "cadence-activity",
318 }
319 }
320
321 /// The CSS value, as a `ms` time.
322 #[must_use]
323 pub fn css(self) -> String {
324 format!("{}ms", self.ms())
325 }
326
327 /// Every cadence, in the order they are emitted.
328 #[must_use]
329 pub const fn all() -> &'static [Self] {
330 &[Self::Activity]
331 }
332}
333
334/// Whether the reader has asked for less motion, as their platform reported it.
335///
336/// Exhaustive on purpose: it is a two-state answer the caller supplies, and a
337/// third state would be a question this crate has not been asked. An enum
338/// rather than a bool so a call site reads as what it means.
339#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
340pub enum MotionPreference {
341 /// No preference stated, so things move.
342 #[default]
343 Full,
344 /// The reader asked for less movement.
345 Reduced,
346}
347
348/// Whether a notice goes away on its own.
349///
350/// What `makeover_layout::Notice::transient` answers, taken as its answer
351/// rather than as the `Notice`, which keeps this crate off `makeover-layout`'s
352/// dependency graph. Exhaustive for [`MotionPreference`]'s reason.
353#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
354pub enum Persistence {
355 /// It dismisses itself, after [`Moment::Dismiss`].
356 Transient,
357 /// It stays until its cause is fixed, and has no lifetime.
358 Standing,
359}
360
361/// How fast the activity mark blinks, given whether the reader has asked for
362/// less motion.
363///
364/// The same seam as [`notice_lifetime`]: the preference is the platform's to
365/// report, and taking the answer rather than the platform keeps this crate off
366/// everyone's dependency graph.
367///
368/// ```
369/// # use makeover_timing::{Cadence, MotionPreference, activity_blink};
370/// assert_eq!(
371/// activity_blink(MotionPreference::Full),
372/// Some(Cadence::Activity.duration())
373/// );
374/// assert_eq!(activity_blink(MotionPreference::Reduced), None);
375/// ```
376///
377/// `None` is not "the caller decides" and it is not "draw nothing". It means
378/// the mark does not blink: it is drawn, lit, and still, for as long as the
379/// wait lasts. The reader still learns that something is happening, which is
380/// the whole content of the mark; what they are spared is the movement. A
381/// renderer that hides the mark instead has removed the information rather than
382/// the animation, and reduced motion asks for the second.
383///
384/// A web surface does not call this. The generated stylesheet carries a
385/// `prefers-reduced-motion` block that does the same thing in the cascade,
386/// which is why [`reduced_motion_css`] exists.
387#[must_use]
388pub const fn activity_blink(preference: MotionPreference) -> Option<Duration> {
389 match preference {
390 MotionPreference::Full => Some(Cadence::Activity.duration()),
391 MotionPreference::Reduced => None,
392 }
393}
394
395/// How long a notice lives, given whether it goes away on its own.
396///
397/// `makeover-layout` documents `Notice::Toast` as "transient, stacked,
398/// dismisses itself", and the description deliberately says nothing about
399/// when. This is when, on the renderer's side of the line:
400///
401/// ```
402/// # use makeover_timing::{Moment, Persistence, notice_lifetime};
403/// assert_eq!(
404/// notice_lifetime(Persistence::Transient),
405/// Some(Moment::Dismiss.duration())
406/// );
407/// assert_eq!(notice_lifetime(Persistence::Standing), None);
408/// ```
409///
410/// `None` is not "the caller decides". It means the notice has no lifetime:
411/// a banner is dismissed by fixing the cause, and an error is a banner. See
412/// the crate header on why severity is not a fifth duration.
413#[must_use]
414pub const fn notice_lifetime(persistence: Persistence) -> Option<Duration> {
415 match persistence {
416 Persistence::Transient => Some(Moment::Dismiss.duration()),
417 Persistence::Standing => None,
418 }
419}
420
421/// Emit the time axis as CSS declarations, no selector.
422///
423/// [`Moment::Debounce`] is emitted with the rest even though no stylesheet can
424/// use it. One document holds every duration in the system, so a token cannot
425/// live here for some moments and in a JS constant for another, and a script
426/// can read the value back off the computed style.
427#[must_use]
428pub fn timing_css_declarations() -> String {
429 let mut out = String::new();
430 out.push_str(" /* Time. Named for what is being waited on; the number\n");
431 out.push_str(" follows. One duration per moment on every renderer. */\n");
432 for moment in Moment::all() {
433 let _ = writeln!(out, " --{}: {};", moment.token(), moment.css());
434 }
435 out.push_str("\n /* Motion: how long a change takes, not how long a state\n");
436 out.push_str(" lasts. A separate question, so a separate axis. */\n");
437 for motion in Motion::all() {
438 let _ = writeln!(out, " --{}: {};", motion.token(), motion.css());
439 }
440
441 out.push_str("\n /* Cadence: how often a repeating mark repeats. A\n");
442 out.push_str(" half-period, so a full cycle is twice it. */\n");
443 for cadence in Cadence::all() {
444 let _ = writeln!(out, " --{}: {};", cadence.token(), cadence.css());
445 }
446 out
447}
448
449/// The motion-off block, for a reader who has asked for less of it.
450///
451/// Everything here that animates resolves to `0ms`. A zero-length transition
452/// is a jump to its end state, so a notice stops fading and simply goes when
453/// its lifetime is up, with no rule written twice.
454///
455/// **The blink needs one thing from the rule that consumes it**, and it does
456/// not fall out of the zero on its own. A zero-length animation with no
457/// `animation-fill-mode` leaves the element in its *base* style, not at its
458/// last keyframe. So write the rule with the mark lit in the base style and the
459/// keyframes doing the dimming, never the other way round. Then reduced motion
460/// stills a lit mark, and the inverted spelling would blank it. See
461/// [`activity_blink`] on why removing the mark answers a different request from
462/// the one that was made.
463///
464/// [`Moment`] is untouched. Those are waits rather than strokes, and a reader
465/// asking for less motion has not asked for their input to settle sooner or for
466/// a notice they are reading to leave early.
467#[must_use]
468pub fn reduced_motion_css() -> String {
469 let mut out = String::new();
470 out.push_str("@media (prefers-reduced-motion: reduce) {\n");
471 out.push_str(" :root {\n");
472 out.push_str(" /* Motion off. The state a stroke was heading for,\n");
473 out.push_str(" reached at once; nothing is removed. */\n");
474 for motion in Motion::all() {
475 let _ = writeln!(out, " --{}: 0ms;", motion.token());
476 }
477 for cadence in Cadence::all() {
478 let _ = writeln!(out, " --{}: 0ms;", cadence.token());
479 }
480 out.push_str(" }\n}\n");
481 out
482}
483
484/// Emit the whole time axis: a `:root { ... }` block, then the motion-off block.
485///
486/// Mirrors `makeover_geometry::geometry_css_vars`. Like geometry and unlike
487/// colour, none of this varies at runtime, so a web consumer bakes it in at
488/// build time rather than applying it from JS on load.
489///
490/// The `prefers-reduced-motion` block rides with the values it overrides rather
491/// than being a second thing to remember to include. A consumer that took the
492/// vars and not the block would animate at every rung for a reader who asked it
493/// not to, and would do it silently.
494#[must_use]
495pub fn timing_css_vars() -> String {
496 format!(
497 ":root {{\n{}}}\n\n{}",
498 timing_css_declarations(),
499 reduced_motion_css()
500 )
501}
502
503/// The time axis as a stylesheet, inside the family's cascade layer.
504///
505/// The whole-file entry point, and the one a build script should call.
506/// Unlayered declarations outrank every named layer, so generated CSS that
507/// stays outside the layer beats the app's own overrides regardless of
508/// specificity, which is invisible until the app adopts layers. `makeover_geometry::CSS_LAYER` is the one spelling of the name.
509#[must_use]
510pub fn timing_css() -> String {
511 in_css_layer(&timing_css_vars())
512}
513
514#[cfg(test)]
515mod tests {
516 use super::*;
517
518 #[test]
519 fn every_intent_resolves_to_one_number_in_three_spellings() {
520 // ms, Duration and CSS are three renderings of one value, so a rung
521 // cannot drift between the browser and egui.
522 for moment in Moment::all() {
523 assert_eq!(moment.duration().as_millis() as u32, moment.ms());
524 assert_eq!(moment.css(), format!("{}ms", moment.ms()));
525 }
526 for motion in Motion::all() {
527 assert_eq!(motion.duration().as_millis() as u32, motion.ms());
528 }
529 for cadence in Cadence::all() {
530 assert_eq!(cadence.duration().as_millis() as u32, cadence.ms());
531 assert_eq!(cadence.css(), format!("{}ms", cadence.ms()));
532 }
533 }
534
535 #[test]
536 fn the_measured_values_are_the_ones_the_tree_had() {
537 // Changing one of these is a design decision about every consumer at
538 // once, which is the point of the crate; a test failure is the argument
539 // happening out loud.
540 assert_eq!(Moment::Revert.ms(), 1500);
541 assert_eq!(Moment::Clear.ms(), 2000);
542 assert_eq!(Moment::Dismiss.ms(), 3000);
543 assert_eq!(Moment::Debounce.ms(), 150);
544 assert_eq!(Motion::Fade.ms(), 300);
545 // The one value that is not a count. Pinned all the same: it is the
546 // number three renderers agree on, which is the whole reason it is
547 // here rather than in each of them.
548 assert_eq!(Cadence::Activity.ms(), 500);
549 }
550
551 #[test]
552 fn a_notice_leaves_after_its_lifetime_and_its_fade() {
553 // The two numbers the toast class needs, and the reason they are on
554 // different axes: a renderer that removes the node at Dismiss drops
555 // the animation, and one that waits Dismiss + Fade is correct.
556 assert_eq!(
557 notice_lifetime(Persistence::Transient),
558 Some(Duration::from_secs(3))
559 );
560 assert!(Motion::Fade.duration() < Moment::Dismiss.duration());
561 }
562
563 #[test]
564 fn a_notice_that_is_not_transient_has_no_lifetime() {
565 // Not "the caller decides": a banner is dismissed by fixing the cause.
566 assert_eq!(notice_lifetime(Persistence::Standing), None);
567 }
568
569 #[test]
570 fn debounce_is_the_shortest_wait_and_a_notice_the_longest() {
571 // The ordering is the sanity check on the set: input settling is the
572 // one wait a user is inside rather than watching, so it is the only
573 // sub-second rung, and nothing may quietly grow past a notice.
574 assert!(
575 Moment::all()
576 .iter()
577 .all(|i| i.ms() >= Moment::Debounce.ms())
578 );
579 assert!(Moment::all().iter().all(|i| i.ms() <= Moment::Dismiss.ms()));
580 }
581
582 #[test]
583 fn no_intent_is_long_enough_to_be_a_poll_interval() {
584 // A ceiling with an argument behind it: every rung here is a wait a
585 // reader sits through, and past a few seconds that stops being true.
586 // A backoff or a health check answers to what it talks to, not here.
587 assert!(Moment::all().iter().all(|i| i.ms() <= 5_000));
588 }
589
590 #[test]
591 fn the_layer_is_emitted_inside_the_family_layer() {
592 let css = timing_css();
593 assert!(css.starts_with("@layer makeover {\n"));
594 assert!(css.contains(" :root {"));
595 assert!(css.trim_end().ends_with('}'));
596 }
597
598 #[test]
599 fn every_token_reaches_the_stylesheet_exactly_once() {
600 let css = timing_css();
601 for moment in Moment::all() {
602 let decl = format!("--{}: {}", moment.token(), moment.css());
603 assert_eq!(css.matches(&decl).count(), 1, "{}", moment.token());
604 }
605 for motion in Motion::all() {
606 let decl = format!("--{}: {}", motion.token(), motion.css());
607 assert_eq!(css.matches(&decl).count(), 1, "{}", motion.token());
608 }
609 for cadence in Cadence::all() {
610 let decl = format!("--{}: {}", cadence.token(), cadence.css());
611 assert_eq!(css.matches(&decl).count(), 1, "{}", cadence.token());
612 }
613 }
614
615 #[test]
616 fn tokens_are_prefixed_by_their_axis() {
617 // `--timing-*` for a state's length, `--motion-*` for a change's. A
618 // reader scanning the sheet can tell which question a var answers.
619 assert!(
620 Moment::all()
621 .iter()
622 .all(|i| i.token().starts_with("timing-"))
623 );
624 assert!(
625 Motion::all()
626 .iter()
627 .all(|m| m.token().starts_with("motion-"))
628 );
629 assert!(
630 Cadence::all()
631 .iter()
632 .all(|c| c.token().starts_with("cadence-"))
633 );
634 }
635
636 #[test]
637 fn the_blink_is_a_half_period_and_the_cycle_is_twice_it() {
638 // The one arithmetic a renderer must not be doing itself. A mark lit
639 // for 500ms and dark for 500ms is a one-second cycle, and a renderer
640 // scheduling the cycle where it meant the half draws at half speed.
641 assert_eq!(Cadence::Activity.cycle(), Cadence::Activity.duration() * 2);
642 assert_eq!(Cadence::Activity.cycle(), Duration::from_secs(1));
643 }
644
645 #[test]
646 fn the_blink_is_slower_than_a_stroke_and_faster_than_a_notice() {
647 // Where it sits between the existing axes is the sanity check on the
648 // number. Faster than Fade and it is a strobe; slower than the shortest
649 // thing a reader sits through and it reads as stalled rather than busy.
650 assert!(Cadence::Activity.duration() > Motion::Fade.duration());
651 assert!(Cadence::Activity.duration() < Moment::Revert.duration());
652 }
653
654 #[test]
655 fn reduced_motion_stills_the_mark_rather_than_removing_it() {
656 // None means lit and static, not absent. The distinction is the whole
657 // of what reduced motion asks for: less movement, not less information.
658 assert_eq!(
659 activity_blink(MotionPreference::Full),
660 Some(Cadence::Activity.duration())
661 );
662 assert_eq!(activity_blink(MotionPreference::Reduced), None);
663 }
664
665 #[test]
666 fn reduced_motion_leaves_the_waits_alone() {
667 // Only what animates is zeroed. A debounce is a wait, and a reader
668 // asking for less motion has not asked their input to settle sooner.
669 let css = reduced_motion_css();
670 for moment in Moment::all() {
671 assert!(!css.contains(moment.token()), "{}", moment.token());
672 }
673 for motion in Motion::all() {
674 assert!(css.contains(&format!("--{}: 0ms;", motion.token())));
675 }
676 for cadence in Cadence::all() {
677 assert!(css.contains(&format!("--{}: 0ms;", cadence.token())));
678 }
679 }
680
681 #[test]
682 fn the_motion_off_block_ships_with_the_values_it_overrides() {
683 // A consumer taking the vars and not the block animates at every rung
684 // for a reader who asked it not to, and does it silently. So the
685 // whole-file entry point carries both, inside the family layer.
686 let css = timing_css();
687 assert!(css.contains("@media (prefers-reduced-motion: reduce)"));
688 let vars = css
689 .find(&format!(
690 "--{}: {}",
691 Cadence::Activity.token(),
692 Cadence::Activity.css()
693 ))
694 .expect("the value");
695 let off = css.find("prefers-reduced-motion").expect("the block");
696 assert!(
697 vars < off,
698 "the override has to come after what it overrides"
699 );
700 }
701
702 #[test]
703 fn no_two_rungs_share_a_name_or_a_value() {
704 // A duplicate name silently overwrites in the cascade; a duplicate
705 // value is two names for one thing, which is a distinction nobody can
706 // choose between.
707 let mut tokens: Vec<&str> = Moment::all().iter().map(|i| i.token()).collect();
708 tokens.extend(Motion::all().iter().map(|m| m.token()));
709 tokens.extend(Cadence::all().iter().map(|c| c.token()));
710 let mut sorted = tokens.clone();
711 sorted.sort_unstable();
712 sorted.dedup();
713 assert_eq!(sorted.len(), tokens.len(), "{tokens:?}");
714
715 let mut values: Vec<u32> = Moment::all().iter().map(|i| i.ms()).collect();
716 values.sort_unstable();
717 values.dedup();
718 assert_eq!(values.len(), Moment::all().len(), "two intents, one number");
719 }
720}