diff --git a/README.md b/README.md index 04a5f4c..36c3474 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ unit = { git = "https://github.com/diaryx-org/unit", branch = "main" } | Overlays | `Unit::open_dialog` (alerts, confirmations, a prompt), `Unit::open_actions` (an action sheet), `Modal` and its `Sheet` placement (a sheet along the bottom on a phone held upright, with Cancel and Done and dragged down to close, and a card in the middle of a wider window; `BottomSheet` for a sheet everywhere), `Unit::toast` (until dismissed, or for as long as it `lasts`) | | Gestures | `LongPress` and `use_hold`: a finger held still, timed by the host's sleep (`Unit::set_timer`) | | Layout | `Stack`, `Spacer`, `Card`, `Divider`, `Field` (a form's row), `Heading`, `Text`, `Badge`, `Progress`, `Callout` | -| Theme | `Theme`: a light and a dark `Palette`, a pointer's and a finger's `Metrics` (corners among them), a `Shape` (edges, pills, shadows, how a menu's rows sit), and a text and a heading font, written as CSS custom properties; `Appearance`, `Density` and `Accent` on the root. Three ship: `Theme::default()` (Unit), `Theme::soft()` (Diaryx's: warm, round, faces by fill) and `Theme::sharp()` (square and ruled); the gallery switches between them, and `?theme=soft` opens it in one | +| Theme | `Theme`: a light and a dark `Palette`, a pointer's and a finger's `Metrics` (corners among them), a `Shape` (edges, pills, shadows, how a menu's rows sit), and a text and a heading font, written as CSS custom properties; `Appearance`, `Density` and `Accent` on the root. Three ship: `Theme::default()` (Unit), `Theme::soft()` (Diaryx's: warm, round, faces by fill, on a spring) and `Theme::sharp()` (square and ruled); the gallery switches between them, and `?theme=soft` opens it in one. A theme's `Motion` times its changes: a switch's knob sliding, a hover easing, a menu, dialog, sheet or toast growing in and fading out; `MotionSetting` on the root keeps a page still where the system or the host asks, and a terminal's cells never move | Its component list and its theme of tokens take after [Libero](https://github.com/tdymel/libero)'s; how it is built does not. diff --git a/gallery/src/lib.rs b/gallery/src/lib.rs index 4c8ac6d..f37e2f3 100644 --- a/gallery/src/lib.rs +++ b/gallery/src/lib.rs @@ -27,8 +27,23 @@ pub fn Gallery() -> Element { let appearance = use_signal(|| appearance); let density = use_signal(|| density); let theme = use_signal(chosen_theme); + let motion = use_signal(chosen_motion); rsx! { - Shown { appearance, density, theme, accent: Accent::System } + Shown { appearance, density, theme, motion, accent: Accent::System } + } +} + +/// How the page moves: the environment's UNIT_MOTION (full, reduced), or a +/// web page's `?motion=reduced`; the system's otherwise. +fn chosen_motion() -> MotionSetting { + #[cfg(not(target_arch = "wasm32"))] + let asked = std::env::var("UNIT_MOTION").unwrap_or_default(); + #[cfg(target_arch = "wasm32")] + let asked = web_query("motion"); + match asked.as_str() { + "full" => MotionSetting::Full, + "reduced" => MotionSetting::Reduced, + _ => MotionSetting::System, } } @@ -84,15 +99,24 @@ fn chosen() -> (Appearance, Density) { /// The page as [`Gallery`] draws it, told its window is `width` × `height` /// CSS pixels: what a window's host tells unit ([`Unit::set_viewport`]), -/// for the tests, which lay it out with no window. +/// for the tests, which lay it out with no window. Still unless `moving`: +/// a test's clock stands at 0 unless it moves it, so whatever moved would +/// stand where its motion began. #[component] -pub fn GallerySized(width: f64, height: f64) -> Element { +pub fn GallerySized(width: f64, height: f64, #[props(default)] moving: bool) -> Element { let (appearance, density) = chosen(); let appearance = use_signal(|| appearance); let density = use_signal(|| density); let theme = use_signal(chosen_theme); + let motion = use_signal(move || { + if moving { + MotionSetting::Full + } else { + MotionSetting::Reduced + } + }); rsx! { - Shown { appearance, density, theme, accent: Accent::Theme, size: (width, height) } + Shown { appearance, density, theme, motion, accent: Accent::Theme, size: (width, height) } } } @@ -112,8 +136,10 @@ pub fn GalleryAt( let appearance = use_signal(|| appearance); let density = use_signal(|| density); let theme = use_signal(|| theme); + // Still: the audit reads every look as it is at rest. + let motion = use_signal(|| MotionSetting::Reduced); rsx! { - Shown { appearance, density, theme, accent: Accent::Theme, size } + Shown { appearance, density, theme, motion, accent: Accent::Theme, size } } } @@ -123,15 +149,16 @@ fn Shown( density: Signal, /// Which of [`Theme::all`]. theme: Signal, + motion: Signal, accent: Accent, size: Option<(f64, f64)>, ) -> Element { let shown = Theme::all().swap_remove(theme().min(Theme::all().len() - 1)); rsx! { - UnitRoot { appearance: appearance(), density: density(), accent, theme: shown, class: "gallery", + UnitRoot { appearance: appearance(), density: density(), accent, theme: shown, motion: motion(), class: "gallery", style { {GALLERY_CSS} } Sized { size } - Page { appearance, density, theme } + Page { appearance, density, theme, motion } // The page's own element, outside any component, as a host's // editor is: unit's styles leave its box as the page drew it. div { class: "gallery-own" } @@ -237,7 +264,12 @@ html, body { margin: 0; } "#; #[component] -fn Page(appearance: Signal, density: Signal, theme: Signal) -> Element { +fn Page( + appearance: Signal, + density: Signal, + theme: Signal, + motion: Signal, +) -> Element { let unit = use_unit(); #[cfg(not(target_arch = "wasm32"))] use_hook(move || { @@ -432,6 +464,12 @@ fn Page(appearance: Signal, density: Signal, theme: Signal< unit.set_keyboard(if i == 2 { 336.0 } else { 0.0 }); }, } + Segmented { + label: "Motion", + options: vec!["System".into(), "Full".into(), "Reduced".into()], + selected: Some(match motion() { MotionSetting::System => 0, MotionSetting::Full => 1, MotionSetting::Reduced => 2 }), + onchange: move |i| motion.clone().set([MotionSetting::System, MotionSetting::Full, MotionSetting::Reduced][i]), + } Segmented { label: "Density", options: vec!["Pointer".into(), "Touch".into()], diff --git a/gallery/tests/audit.rs b/gallery/tests/audit.rs index 3260b7a..561f28a 100644 --- a/gallery/tests/audit.rs +++ b/gallery/tests/audit.rs @@ -200,7 +200,7 @@ fn LongText(at: At) -> Element { let options: Vec = vec![LONG.into(), WORD.into()]; rsx! { UnitRoot { appearance: at.appearance, density: at.density, - theme: unit::Theme::all().swap_remove(at.theme), + theme: unit::Theme::all().swap_remove(at.theme), motion: unit::MotionSetting::Reduced, Stack { gap: 12.0, Heading { level: 1, "{LONG}" } Heading { level: 1, "{WORD}" } diff --git a/gallery/tests/blitz.rs b/gallery/tests/blitz.rs index 6dec797..188f59a 100644 --- a/gallery/tests/blitz.rs +++ b/gallery/tests/blitz.rs @@ -3291,3 +3291,135 @@ fn a_nav_bar_centres_its_title_and_gives_way_to_its_buttons() { } } } + +/// The gallery with motion on, as [`page`] is without it. +#[allow(non_snake_case)] +fn Moving(window: Window) -> Element { + rsx! { + unit_gallery::GallerySized { width: window.width, height: window.height, moving: true } + } +} + +fn page_moving(width: u32, height: u32) -> DioxusDocument { + let vdom = VirtualDom::new_with_props( + Moving, + Window { + width: width as f64, + height: height as f64, + }, + ); + let mut doc = DioxusDocument::new(vdom, DocumentConfig::default()); + doc.inner + .borrow_mut() + .set_viewport(Viewport::new(width, height, 1.0, ColorScheme::Light)); + doc.initial_build(); + settle(&mut doc); + doc +} + +/// Poll the page and lay it out with the clock at `seconds`. +fn at_time(doc: &mut DioxusDocument, seconds: f64) { + for _ in 0..3 { + Document::poll(doc, Some(Context::from_waker(Waker::noop()))); + doc.inner.borrow_mut().resolve(seconds); + } +} + +fn opacity(doc: &DioxusDocument, node: NodeId) -> f64 { + doc.inner + .borrow() + .resolved_style_value(node, "opacity") + .parse() + .unwrap_or(f64::NAN) +} + +/// With motion on, a menu grows into place as Blitz's clock runs, and +/// once closed is drawn going, then taken away when its motion is over. +#[test] +fn a_menu_comes_and_goes_in_the_themes_motion() { + let mut doc = page_moving(1200, 800); + let edit = find(&doc, "button", "Edit ▾"); + click(&mut doc, edit); + let menu = doc + .inner + .borrow() + .query_selector(".unit-menu") + .unwrap() + .unwrap(); + at_time(&mut doc, 0.0); + let start = opacity(&doc, menu); + at_time(&mut doc, 0.06); + let during = opacity(&doc, menu); + at_time(&mut doc, 1.0); + let end = opacity(&doc, menu); + assert!( + start < during && during < end && end == 1.0, + "{start} → {during} → {end}" + ); + + // Closed, the menu is gone at once to whatever reads it, and a drawing + // of it goes. + let primary = find(&doc, "button", "Primary"); + click(&mut doc, primary); + at_time(&mut doc, 1.0); + assert!(!displayed(&doc, menu), "the menu itself is closed"); + let going = doc + .inner + .borrow() + .query_selector(".unit-menu.unit-leaving") + .unwrap() + .unwrap(); + assert!(displayed(&doc, going), "drawn going"); + at_time(&mut doc, 1.06); + let fading = opacity(&doc, going); + at_time(&mut doc, 2.0); + let gone = opacity(&doc, going); + assert!(fading < 1.0 && gone == 0.0, "{fading} → {gone}"); + // The host's sleep ends its time, and the drawing is taken away. + std::thread::sleep(std::time::Duration::from_millis(300)); + at_time(&mut doc, 2.0); + assert!(!displayed(&doc, going), "taken away"); +} + +/// With motion on, a dismissed toast sinks away and is then taken out; the +/// toasts that read it are told at once that it is gone. +#[test] +fn a_dismissed_toast_sinks_away_then_goes() { + let mut doc = page_moving(1200, 800); + let toast = find(&doc, "button", "Toast"); + click(&mut doc, toast); + at_time(&mut doc, 1.0); + let dismiss = { + let inner = doc.inner.borrow(); + let all = inner + .query_selector_all(".unit-toast [aria-label=\"Dismiss\"]") + .unwrap(); + *all.first().expect("a toast to dismiss") + }; + click(&mut doc, dismiss); + at_time(&mut doc, 1.0); + let going = doc + .inner + .borrow() + .query_selector(".unit-toast.unit-leaving") + .unwrap() + .expect("drawn going"); + assert_eq!( + doc.inner + .borrow() + .resolved_style_value(going, "pointer-events"), + "none" + ); + at_time(&mut doc, 2.0); + assert_eq!(opacity(&doc, going), 0.0, "sunk away"); + std::thread::sleep(std::time::Duration::from_millis(300)); + at_time(&mut doc, 2.0); + assert!( + doc.inner + .borrow() + .query_selector(".unit-toast") + .unwrap() + .is_none(), + "taken out" + ); +} diff --git a/src/layer.rs b/src/layer.rs index 369bbf1..eb51d89 100644 --- a/src/layer.rs +++ b/src/layer.rs @@ -115,6 +115,13 @@ pub(crate) struct LayerState { actions: Option<(ActionSheet, Choose)>, /// Each toast, its id and its action's handler, oldest first. toasts: Vec<(u64, Toast, Option)>, + /// A menu just closed, drawn going (`unit-leaving`) until its motion + /// ends, and which closing it was: a drawing only, which nothing reads + /// and no pointer reaches. + leaving: Option<(Vec, u64)>, + /// The toasts going, by id: drawn going until their motion ends, and + /// then taken away. + leaving_toasts: Vec, /// The page's size, which a menu is kept inside. pub viewport: (f64, f64), } @@ -171,6 +178,8 @@ impl Unit { let clear = (safe.top, safe.bottom.max(keyboard)); let menu = Menu::open_clear(entries, at, above, viewport, clear, sizes); let mut w = l.write(); + // A new menu is drawn alone, not over the last one going. + w.leaving = None; w.menu = Some((menu, Rc::new(move |i| (pick.borrow_mut())(i)))); w.owner = (owner != 0).then_some(owner); } @@ -189,7 +198,7 @@ impl Unit { let done = RefCell::new(done); let mut l = self.layer; let mut w = l.write(); - w.menu = None; + self.let_menu_go(&mut w); w.dialog = Some((dialog, Rc::new(move |a| (done.borrow_mut())(a)))); } @@ -199,7 +208,7 @@ impl Unit { let choose = RefCell::new(choose); let mut l = self.layer; let mut w = l.write(); - w.menu = None; + self.let_menu_go(&mut w); w.actions = Some((sheet, Rc::new(move |a| (choose.borrow_mut())(a)))); } @@ -231,11 +240,31 @@ impl Unit { } } + /// Close the open menu, choosing nothing from it, and give back what it + /// would have chosen with: it goes in its own motion where the page + /// moves, as a drawing that nothing reads, and is gone at once where it + /// does not. + fn let_menu_go(&self, w: &mut LayerState) -> Option { + let (menu, pick) = w.menu.take()?; + if let Some(time) = self.exit_time() { + let token = next_id(); + w.leaving = Some((menu.levels, token)); + let unit = *self; + self.after(time, move || { + let mut l = unit.layer; + if l.peek().leaving.as_ref().is_some_and(|(_, t)| *t == token) { + l.write().leaving = None; + } + }); + } + Some(pick) + } + /// Close whatever is open, choosing nothing. pub fn close(&self) { let mut l = self.layer; if l.peek().menu.is_some() { - l.write().menu = None; + self.let_menu_go(&mut l.write()); } else if l.peek().actions.is_some() { self.choose(None); } else if l.peek().dialog.is_some() { @@ -273,11 +302,27 @@ impl Unit { id } - /// Take the toast `id` away. + /// Take the toast `id` away: in its own motion where the page moves, + /// and at once where it does not. pub fn dismiss(&self, id: u64) { let mut l = self.layer; - if l.peek().toasts.iter().any(|(t, ..)| *t == id) { - l.write().toasts.retain(|(t, ..)| *t != id); + let there = l.peek().toasts.iter().any(|(t, ..)| *t == id); + if !there || l.peek().leaving_toasts.contains(&id) { + return; + } + let gone = move |unit: Unit| { + let mut l = unit.layer; + let mut w = l.write(); + w.toasts.retain(|(t, ..)| *t != id); + w.leaving_toasts.retain(|t| *t != id); + }; + match self.exit_time() { + Some(time) => { + l.write().leaving_toasts.push(id); + let unit = *self; + self.after(time, move || gone(unit)); + } + None => gone(*self), } } @@ -374,11 +419,11 @@ impl Unit { Outcome::Ignored => false, Outcome::Handled => true, Outcome::Close => { - l.write().menu = None; + self.let_menu_go(&mut l.write()); true } Outcome::Pick(id) => { - let pick = l.write().menu.take().map(|(_, p)| p); + let pick = self.let_menu_go(&mut l.write()); if let Some(p) = pick { p(id); } @@ -410,11 +455,18 @@ fn LayerView(unit: Unit) -> Element { .collect(); let dialog = l.dialog.as_ref().map(|(d, _)| d.clone()); let actions = l.actions.as_ref().map(|(a, _)| a.clone()); - let toasts: Vec<(u64, Toast)> = l + let leaving: Vec> = (0..LEVELS) + .map(|i| { + l.leaving + .as_ref() + .and_then(|(levels, _)| levels.get(i).cloned()) + }) + .collect(); + let toasts: Vec<(u64, Toast, bool)> = l .toasts .iter() .take(TOASTS) - .map(|(id, t, _)| (*id, t.clone())) + .map(|(id, t, _)| (*id, t.clone(), l.leaving_toasts.contains(id))) .collect(); drop(l); let (safe, keyboard) = unit.edges(); @@ -458,7 +510,7 @@ fn LayerView(unit: Unit) -> Element { e.stop_propagation(); let mut l = unit.layer; if l.peek().menu.is_some() { - l.write().menu = None; + unit.let_menu_go(&mut l.write()); } else if l.peek().actions.is_some() { unit.choose(None); } else if l.peek().dialog.is_some() { @@ -469,20 +521,33 @@ fn LayerView(unit: Unit) -> Element { for (depth, level) in levels.into_iter().enumerate() { MenuLevel { key: "{depth}", unit, depth, level } } + // The menu just closed, going: after the live levels, so that + // whatever looks for a menu finds the one open first. + for (depth, level) in leaving.into_iter().enumerate() { + MenuLevel { key: "leaving-{depth}", unit, depth, level, leaving: true } + } DialogView { unit, dialog, top: safe.top, bottom: safe.bottom.max(keyboard) } ActionsView { unit, sheet: actions, bottom: safe.bottom } div { class: "unit-toasts", role: "status", "aria-live": "polite", style: "bottom: {toasts_bottom}px", - for (id, t) in toasts { - ToastView { key: "{id}", unit, id, toast: t } + for (id, t, going) in toasts { + ToastView { key: "{id}", unit, id, toast: t, leaving: going } } } } } } +/// One level of the open menu, or, `leaving`, of the menu just closed: a +/// drawing going in its own motion that nothing reads and no pointer +/// reaches. #[component] -fn MenuLevel(unit: Unit, depth: usize, level: Option) -> Element { +fn MenuLevel( + unit: Unit, + depth: usize, + level: Option, + #[props(default)] leaving: bool, +) -> Element { // One template whether the level is open or not: Blitz does not lay out // an absolutely positioned element a later frame inserts, so this one is // only ever restyled. Its rows are in a box of their own, which scrolls @@ -514,9 +579,14 @@ fn MenuLevel(unit: Unit, depth: usize, level: Option) -> Element { ), None => ("display: none".to_string(), None), }; + let (class, role) = if leaving { + ("unit-menu unit-leaving", "presentation") + } else { + ("unit-menu", "menu") + }; rsx! { - div { class: "unit-menu", role: "menu", style, - "aria-hidden": if level.is_none() { "true" } else { "false" }, + div { class, role, style, + "aria-hidden": if level.is_none() || leaving { "true" } else { "false" }, onpointerdown: move |e: PointerEvent| { e.prevent_default(); e.stop_propagation(); @@ -891,7 +961,7 @@ fn field_view(f: &Field, label: &str) -> Element { } #[component] -fn ToastView(unit: Unit, id: u64, toast: Toast) -> Element { +fn ToastView(unit: Unit, id: u64, toast: Toast, #[props(default)] leaving: bool) -> Element { let act = move |e: MouseEvent| { e.stop_propagation(); let action = unit @@ -907,7 +977,8 @@ fn ToastView(unit: Unit, id: u64, toast: Toast) -> Element { } }; rsx! { - div { class: "unit-toast{toast.tone.class()}", + div { class: if leaving { "unit-toast unit-leaving{toast.tone.class()}" } else { "unit-toast{toast.tone.class()}" }, + "aria-hidden": leaving.then_some("true"), onpointerdown: move |e: PointerEvent| { e.stop_propagation(); }, diff --git a/src/lib.rs b/src/lib.rs index ea60c0b..a6a97e5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -100,7 +100,9 @@ pub use layer::{Toast, Tone}; pub use menu::{Entry, Item}; pub use selection::{Pick, Selection}; pub use style::CSS; -pub use theme::{Accent, Appearance, Density, Metrics, Palette, Theme}; +pub use theme::{ + Accent, Appearance, Density, Metrics, Motion, MotionSetting, Palette, Shape, Theme, +}; pub use unit::{ Clipboard, Focus, Insets, Keys, Kind, Unit, UnitRoot, next_id, use_focus, use_unit, use_unit_provider, @@ -112,12 +114,12 @@ pub mod prelude { Accent, Accessory, ActionSheet, Align, Answer, Appearance, Axis, Badge, BarItem, Breadcrumbs, Button, Callout, Card, Checkbox, Chips, Choice, CodeField, Column, ContextMenu, Density, Dialog, Disclosure, Divider, EmptyState, Entry, Field, Heading, Icon, - Ink, InputKind, Item, Keys, ListBox, LongPress, MenuButton, Modal, NavBar, Orientation, - Photo, PhotoViewer, Pick, Placement, Pressable, Progress, RadioGroup, Row, ScrollBar, - SearchField, Section, Segmented, Select, Selection, SheetAction, Slider, Sort, Spacer, - Stack, Stepper, Swatch, SwatchAction, Swatches, Switch, TabBar, Table, TableRow, Tabs, - Text, TextArea, TextField, Theme, Tile, TileGrid, Toast, ToggleButton, Tone, Tree, TreeRow, - Unit, UnitRoot, Variant, use_unit, + Ink, InputKind, Item, Keys, ListBox, LongPress, MenuButton, Modal, MotionSetting, NavBar, + Orientation, Photo, PhotoViewer, Pick, Placement, Pressable, Progress, RadioGroup, Row, + ScrollBar, SearchField, Section, Segmented, Select, Selection, SheetAction, Slider, Sort, + Spacer, Stack, Stepper, Swatch, SwatchAction, Swatches, Switch, TabBar, Table, TableRow, + Tabs, Text, TextArea, TextField, Theme, Tile, TileGrid, Toast, ToggleButton, Tone, Tree, + TreeRow, Unit, UnitRoot, Variant, use_unit, }; } diff --git a/src/style.rs b/src/style.rs index 192ea3b..e767a6a 100644 --- a/src/style.rs +++ b/src/style.rs @@ -5,7 +5,9 @@ //! //! Written for what Blitz lays out as a browser does: flexbox, absolute //! positions by `left`/`top`/`right`/`bottom`, attribute selectors, `:hover` -//! — not `inset`, `calc()`, transitions or animations. A menu's rows and +//! — not `inset` or `calc()`. Transitions and keyframes Blitz runs as a +//! browser does, on its own clock; every keyframe names both its ends, +//! which Blitz's Stylo needs to draw the frames between. A menu's rows and //! separators have fixed heights, the ones `menu::Sizes` computes its //! geometry by, for each density. @@ -208,7 +210,11 @@ pub const CSS: &str = r#" .unit-switch-label { flex: 1; min-width: 0; overflow-wrap: anywhere; } .unit-switch-track { display: flex; flex: none; width: 32px; height: 18px; padding: 2px; background: var(--unit-border); border-radius: var(--unit-pill); } -.unit-switch.on .unit-switch-track { justify-content: flex-end; background: var(--unit-accent); } +.unit-switch.on .unit-switch-track { background: var(--unit-accent); } +/* The knob slides across rather than jumping: the track's width less its + padding and the knob's, at each density. */ +.unit-switch.on .unit-switch-knob { transform: translateX(14px); } +.unit-root[data-density="touch"] .unit-switch.on .unit-switch-knob { transform: translateX(20px); } .unit-switch-knob { width: 14px; height: 14px; border-radius: var(--unit-pill); background: #ffffff; box-shadow: var(--unit-raised-shadow); } .unit-radios { display: flex; flex-direction: column; gap: 4px; } @@ -595,6 +601,39 @@ pub const CSS: &str = r#" .unit-viewer-caption { position: absolute; left: 0; right: 0; bottom: 0; padding: 22px 16px 14px; text-align: center; color: var(--unit-text); background: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.6)); } + +/* Motion: every duration and curve is the theme's (`Motion`), and 0 where + the page asks for less motion or is drawn in a terminal's cells, so + nothing here moves there. Blitz runs these as a browser does. + + A small change in place eases between its two looks. A menu's row lights + at once, as a system's does. */ +.unit-button, .unit-chip, .unit-tab, .unit-option, .unit-tree-row, .unit-row, .unit-segment-face, +.unit-step, .unit-check-box, .unit-radio-ring, .unit-radio-dot, .unit-switch-track, .unit-input, +.unit-code-cell, .unit-tile-face, .unit-tr, .unit-swatch, .unit-swatch-action, .unit-toggle { + transition: background-color var(--unit-motion-quick) var(--unit-ease), + color var(--unit-motion-quick) var(--unit-ease), + border-color var(--unit-motion-quick) var(--unit-ease), + box-shadow var(--unit-motion-quick) var(--unit-ease), + opacity var(--unit-motion-quick) var(--unit-ease); } +.unit-switch-knob { transition: transform var(--unit-motion-quick) var(--unit-ease); } +.unit-progress-fill { transition: width var(--unit-motion-enter) var(--unit-ease); } + +/* What appears grows into place from where it opened; a sheet and a toast + rise. Each is always in the page and shown by its display, which starts + its keyframes again each time it is shown. */ +.unit-menu { animation: unit-enter var(--unit-motion-enter) var(--unit-ease); transform-origin: top left; } +.unit-dialog { animation: unit-enter var(--unit-motion-enter) var(--unit-ease); } +.unit-backdrop.unit-scrim, .unit-modal-place { animation: unit-fade var(--unit-motion-enter) var(--unit-ease); } +.unit-actions, .unit-toast, .unit-modal.unit-sheet { animation: unit-rise var(--unit-motion-enter) var(--unit-ease); } +.unit-modal { animation: unit-enter var(--unit-motion-enter) var(--unit-ease); } + +/* What goes: a menu just closed and a toast dismissed, drawn going until + their motion ends, where no pointer reaches them. */ +.unit-menu.unit-leaving { animation: unit-leave var(--unit-motion-exit) var(--unit-ease-exit) forwards; + pointer-events: none; } +.unit-toast.unit-leaving { animation: unit-sink var(--unit-motion-exit) var(--unit-ease-exit) forwards; + pointer-events: none; } "#; #[cfg(test)] diff --git a/src/theme.rs b/src/theme.rs index 64bbc73..19c6d17 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -462,6 +462,121 @@ impl Default for Shape { } } +/// How a theme's pieces move: how long a change takes, and along what +/// curve. Durations are in milliseconds. A page that asks for less motion +/// ([`MotionSetting::Reduced`], or the system's `prefers-reduced-motion`), +/// and a terminal's cells, take none of it: every duration is 0. +#[derive(Clone, Debug, PartialEq)] +pub struct Motion { + /// A small change in place: a hover, a press, a switch's knob, a + /// checkbox filling. + pub quick: f64, + /// What appears: a menu, a dialog, a sheet, a toast. + pub enter: f64, + /// What goes: quicker than what comes, as a system's menus are. + pub exit: f64, + /// The curve of a change and of what appears, as CSS: a + /// `cubic-bezier()`, or a spring drawn as `linear()`. + pub ease: &'static str, + /// The curve of what goes. + pub ease_exit: &'static str, + /// How large what appears starts, and what goes ends: 1 fades alone. + pub grow: f64, + /// How far, in pixels, what rises from the bottom (a sheet, a toast) + /// starts below where it ends. + pub rise: f64, +} + +impl Motion { + /// unit's own: quick, and settling without a bounce. + pub const DEFAULT: Motion = Motion { + quick: 120.0, + enter: 160.0, + exit: 120.0, + ease: "cubic-bezier(0.2, 0, 0, 1)", + ease_exit: "cubic-bezier(0.4, 0, 1, 1)", + grow: 0.97, + rise: 12.0, + }; + + /// [`Theme::soft`]'s: a little longer, on a spring that passes its mark + /// and comes back, as a phone's sheets do. + pub const SOFT: Motion = Motion { + quick: 160.0, + enter: 320.0, + exit: 160.0, + ease: "linear(0, 0.13 3.6%, 0.44 9.2%, 0.73 15.4%, 0.92 22%, 1.02 29.3%, 1.045 35.8%, 1.04 42.7%, 1.016 53.5%, 0.999 67%, 1)", + ease_exit: "cubic-bezier(0.4, 0, 1, 1)", + grow: 0.94, + rise: 24.0, + }; + + /// [`Theme::sharp`]'s: short, straight, and a fade with no growing. + pub const SHARP: Motion = Motion { + quick: 80.0, + enter: 100.0, + exit: 80.0, + ease: "linear", + ease_exit: "linear", + grow: 1.0, + rise: 0.0, + }; + + fn entries(&self) -> [(&'static str, String); 5] { + let ms = |v: f64| format!("{v}ms"); + [ + ("motion-quick", ms(self.quick)), + ("motion-enter", ms(self.enter)), + ("motion-exit", ms(self.exit)), + ("ease", self.ease.to_string()), + ("ease-exit", self.ease_exit.to_string()), + ] + } + + /// The keyframes what appears and what goes are drawn by, with this + /// motion's growing and rising written into them. + fn keyframes(&self) -> String { + let (g, r) = (self.grow, self.rise); + format!( + "@keyframes unit-enter {{ from {{ opacity: 0; transform: scale({g}); }} to {{ opacity: 1; transform: scale(1); }} }}\n\ + @keyframes unit-rise {{ from {{ opacity: 0; transform: translateY({r}px); }} to {{ opacity: 1; transform: translateY(0px); }} }}\n\ + @keyframes unit-fade {{ from {{ opacity: 0; }} to {{ opacity: 1; }} }}\n\ + @keyframes unit-leave {{ from {{ opacity: 1; transform: scale(1); }} to {{ opacity: 0; transform: scale({g}); }} }}\n\ + @keyframes unit-sink {{ from {{ opacity: 1; transform: translateY(0px); }} to {{ opacity: 0; transform: translateY({r}px); }} }}\n" + ) + } +} + +impl Default for Motion { + fn default() -> Self { + Motion::DEFAULT + } +} + +/// Whether a page moves: as the system asks (`prefers-reduced-motion`, +/// where the renderer reads it), always, or as little as it can. A host +/// that knows the system's setting where a renderer does not (Blitz, on a +/// phone) says it with [`MotionSetting::Full`] or +/// [`MotionSetting::Reduced`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum MotionSetting { + #[default] + System, + Full, + Reduced, +} + +impl MotionSetting { + /// The root's `data-motion`. + pub fn attr(self) -> &'static str { + match self { + MotionSetting::System => "system", + MotionSetting::Full => "full", + MotionSetting::Reduced => "reduced", + } + } +} + /// Which appearance a page shows. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Appearance { @@ -528,6 +643,8 @@ pub struct Theme { pub heading_font: &'static str, /// The edges, pills and shadows. pub shape: Shape, + /// How long things take to change, and along what curve. + pub motion: Motion, } /// The system's text face, on each platform. @@ -545,6 +662,7 @@ impl Default for Theme { font: SYSTEM_FONT, heading_font: SYSTEM_FONT, shape: Shape::DEFAULT, + motion: Motion::DEFAULT, } } } @@ -563,6 +681,7 @@ impl Theme { regular: Metrics::REGULAR.rounded(8.0, 12.0, 6.0), touch: Metrics::TOUCH.rounded(12.0, 18.0, 10.0), shape: Shape::SOFT, + motion: Motion::SOFT, ..Theme::default() } } @@ -577,10 +696,22 @@ impl Theme { regular: Metrics::REGULAR.rounded(0.0, 0.0, 0.0), touch: Metrics::TOUCH.rounded(0.0, 0.0, 0.0), shape: Shape::SHARP, + motion: Motion::SHARP, ..Theme::default() } } + /// How long `density` and `setting` let a change take, in milliseconds, + /// for what Rust times rather than CSS: 0 where nothing moves. The + /// system's own setting is not known here, and is taken as motion. + pub fn exit_ms(&self, density: Density, setting: MotionSetting) -> f64 { + if setting == MotionSetting::Reduced || density == Density::Cell { + 0.0 + } else { + self.motion.exit + } + } + /// Every theme unit ships, its own first: for a page that offers them. pub fn all() -> Vec { vec![Theme::default(), Theme::soft(), Theme::sharp()] @@ -616,6 +747,9 @@ impl Theme { for (name, value) in self.shape.entries() { let _ = writeln!(s, " --unit-{name}: {value};"); } + for (name, value) in self.motion.entries() { + let _ = writeln!(s, " --unit-{name}: {value};"); + } palette(&mut s, &self.light); metrics(&mut s, &self.regular); s.push_str("}\n"); @@ -638,6 +772,14 @@ impl Theme { let _ = writeln!(s, " --unit-{shadow}-shadow: none;"); } s.push_str("}\n"); + // Less motion, and a terminal's cells: nothing takes any time. + let still = " --unit-motion-quick: 0ms;\n --unit-motion-enter: 0ms;\n --unit-motion-exit: 0ms;\n"; + let _ = write!( + s, + ".unit-root[data-motion=\"reduced\"], .unit-root[data-density=\"cell\"] {{\n{still}}}\n\ + @media (prefers-reduced-motion: reduce) {{\n.unit-root[data-motion=\"system\"] {{\n{still}}}\n}}\n" + ); + s.push_str(&self.motion.keyframes()); s } } @@ -715,6 +857,28 @@ mod tests { assert!(cell.contains("--unit-pill: 0px;") && cell.contains("--unit-float-shadow: none;")); } + /// Each theme moves in its own way, and none moves where less motion is + /// asked for or in a terminal's cells. + #[test] + fn a_theme_says_how_it_moves_and_stillness_wins() { + let soft = Theme::soft().css(); + assert!(soft.contains("--unit-motion-enter: 320ms;"), "{soft}"); + assert!(soft.contains("--unit-ease: linear(0,"), "{soft}"); + assert!(soft.contains("transform: scale(0.94)"), "{soft}"); + let sharp = Theme::sharp().css(); + assert!(sharp.contains("--unit-ease: linear;"), "{sharp}"); + let still = &soft[soft.find("[data-motion=\"reduced\"]").unwrap()..]; + assert!( + still.starts_with("[data-motion=\"reduced\"], .unit-root[data-density=\"cell\"] {") + ); + assert!(still.contains("--unit-motion-enter: 0ms;")); + assert!(soft.contains("@media (prefers-reduced-motion: reduce)")); + let t = Theme::soft(); + assert_eq!(t.exit_ms(Density::Regular, MotionSetting::System), 160.0); + assert_eq!(t.exit_ms(Density::Touch, MotionSetting::Reduced), 0.0); + assert_eq!(t.exit_ms(Density::Cell, MotionSetting::Full), 0.0); + } + #[test] fn headings_take_their_own_font() { let theme = Theme { diff --git a/src/unit.rs b/src/unit.rs index 3785c3a..4ca67ff 100644 --- a/src/unit.rs +++ b/src/unit.rs @@ -18,12 +18,13 @@ use std::cell::Cell; use std::rc::Rc; +use std::time::Duration; use dioxus::html::{Key, Modifiers, NamedKey}; use dioxus::prelude::*; use crate::layer::LayerState; -use crate::theme::{Accent, Appearance, Density, SystemColours, Theme}; +use crate::theme::{Accent, Appearance, Density, MotionSetting, SystemColours, Theme}; /// What the host answers for the page: the clipboard, for a dialog's field. pub trait Clipboard { @@ -110,6 +111,8 @@ pub struct Unit { pub(crate) edges: Signal<(Insets, f64)>, /// The host's sleep, which times a long press (`hold.rs`). pub(crate) timer: CopyValue>, + /// Whether the page moves, as its root says. + pub(crate) motion: CopyValue, } impl PartialEq for Unit { @@ -155,6 +158,7 @@ pub fn use_unit_provider(keys: Keys, activates: bool) -> Unit { appearance: Signal::new(Appearance::System), edges: Signal::new((Insets::default(), 0.0)), timer: CopyValue::new(None), + motion: CopyValue::new(MotionSetting::System), }); unit.keys.clone().set(keys); unit.activates.clone().set(activates); @@ -365,6 +369,32 @@ impl Unit { } } + /// How long what goes takes to go, for what Rust holds on to while it + /// does (a menu, a toast): `None` where nothing moves, or where there is + /// no way to wait (no host's sleep, and not a browser), so it goes at + /// once. + pub(crate) fn exit_time(&self) -> Option { + let can_wait = self.timer.peek().is_some() || cfg!(target_arch = "wasm32"); + let ms = self + .theme + .peek() + .exit_ms(*self.density.peek(), *self.motion.peek()); + (can_wait && ms > 0.0).then(|| Duration::from_millis(ms as u64)) + } + + /// Do `then` once `time` has passed: by the host's sleep, or in a + /// browser by its own timer. + pub(crate) fn after(&self, time: Duration, then: impl FnOnce() + 'static) { + let sleep = self.timer.peek().clone(); + dioxus::core::spawn_forever(async move { + match sleep { + Some(sleep) => sleep(time).await, + None => browser_sleep(time).await, + } + then(); + }); + } + /// The page's stylesheet: `theme`'s properties and every component's /// styles. [`UnitRoot`] puts it in the page, unless told not to. pub fn stylesheet(theme: &Theme) -> String { @@ -503,6 +533,10 @@ pub fn UnitRoot( activates: bool, /// The theme; [`Theme::default`] unless given. theme: Option, + /// Whether the page moves: as the system asks, unless the host knows + /// better ([`MotionSetting`]). + #[props(default)] + motion: MotionSetting, /// Whether the theme's stylesheet goes in the page, in a `