diff --git a/gallery/src/lib.rs b/gallery/src/lib.rs index 2e29165..439c447 100644 --- a/gallery/src/lib.rs +++ b/gallery/src/lib.rs @@ -328,6 +328,10 @@ fn Page( let mut picked_photos = use_signal(Selection::new); let mut tray_chosen = use_signal(Selection::new); let mut viewing = use_signal(|| None::); + // Where a finger or the pointer last pressed among the photos, and the + // photo opened by it and that spot, which it flies out of and back into. + let mut pressed = use_hook(|| CopyValue::new(None::<(f64, f64)>)); + let mut opened_from = use_signal(|| None::<(usize, Spot)>); let edit = vec![ Item::new(CUT, "Cut").shortcut("⌘X").into(), @@ -410,7 +414,14 @@ fn Page( said.set(format!("Opened {key}.")); } }; - let photos = photos(); + let photos: Vec = photos() + .into_iter() + .enumerate() + .map(|(i, p)| match opened_from() { + Some((at, spot)) if at == i => p.from(spot), + _ => p, + }) + .collect(); let photo_tiles: Vec = photos .iter() .enumerate() @@ -781,16 +792,27 @@ fn Page( Text { dim: true, "{chosen().len()} of {shown.len()} chosen." } } Card { title: "Photos", class: "gallery-wide", - TileGrid { label: "Photos", tiles: photo_tiles, size: 88.0, fill: true, labels: false, - selection: picked_photos(), opens: true, - onselect: move |s| picked_photos.set(s), - onactivate: move |k: String| { - viewing.set(k.trim_start_matches("photo-").parse().ok()); - } } + div { class: "gallery-photos", + onpointerdown: move |e: PointerEvent| { + let p = e.client_coordinates(); + pressed.set(Some((p.x, p.y))); + }, + TileGrid { label: "Photos", tiles: photo_tiles, size: 88.0, fill: true, labels: false, + selection: picked_photos(), opens: true, + onselect: move |s| picked_photos.set(s), + onactivate: move |k: String| { + let i = k.trim_start_matches("photo-").parse().ok(); + // Opened by a press, it flies out of where it was pressed; + // by a key, it fades in. + let at = pressed.take(); + opened_from.set(i.zip(at.map(|(x, y)| Spot::point(x, y)))); + viewing.set(i); + } } + } Stack { axis: Axis::Horizontal, align: Align::Center, Text { dim: true, "Tap one to see it whole." } Spacer {} - Button { onpress: move |_| viewing.set(Some(0)), "View Photos…" } + Button { onpress: move |_| { opened_from.set(None); viewing.set(Some(0)); }, "View Photos…" } } } Card { title: "Tray", diff --git a/gallery/tests/blitz.rs b/gallery/tests/blitz.rs index 188f59a..fc8da06 100644 --- a/gallery/tests/blitz.rs +++ b/gallery/tests/blitz.rs @@ -3423,3 +3423,73 @@ fn a_dismissed_toast_sinks_away_then_goes() { "taken out" ); } + +/// Frames by the gallery's own timer until the viewer has closed: the last +/// place its photo was drawn, if it was drawn going. +fn until_closed(doc: &mut DioxusDocument) -> Option<(f64, f64, f64, f64)> { + let mut last = None; + for _ in 0..100 { + if viewer(doc).is_none() { + return last; + } + last = Some(photo_frame(doc)); + std::thread::sleep(std::time::Duration::from_millis(20)); + settle(doc); + } + panic!("the viewer never closed") +} + +/// With motion on, a photo opened by a tap flies out of where it was +/// tapped to fill the window, and closed, by its button or a drag down, +/// flies back into it before the viewer is gone. Opened by a button, with +/// no spot, it grows a little where it rests as it fades in. +#[test] +fn a_photo_flies_out_of_where_it_was_tapped_and_back_into_it() { + let mut doc = page_moving(1200, 800); + let photo = option_named(&doc, "Noon on the hill"); + let (x, y, w, h) = rect(&doc, photo); + let spot = (x + w / 2.0, y + h / 2.0); + let middle = |(x, y, w, h): (f64, f64, f64, f64)| (x + w / 2.0, y + h / 2.0); + let close_to = |a: (f64, f64), b: (f64, f64), by: f64| (a.0 - b.0).hypot(a.1 - b.1) < by; + click(&mut doc, photo); + assert!(viewer(&doc).is_some(), "open"); + let first = photo_frame(&doc); + assert!(first.2 < FITS.2 / 2.0, "small, as it begins: {first:?}"); + assert!( + close_to(middle(first), spot, 300.0), + "near where it was tapped: {first:?}, {spot:?}" + ); + rest(&mut doc); + assert!(near(photo_frame(&doc), FITS), "{:?}", photo_frame(&doc)); + let style = attr(&doc, viewer(&doc).unwrap(), "style").unwrap(); + assert!(style.contains("rgba(0, 0, 0, 1)"), "{style}"); + + // Closed by its button, it goes back into the spot, then is gone. + let close = labelled(&doc, ".unit-viewer button", "Close"); + click(&mut doc, close); + assert!(viewer(&doc).is_some(), "drawn going first"); + let last = until_closed(&mut doc).expect("drawn going"); + assert!(last.2 < FITS.2 / 2.0, "shrunk: {last:?}"); + assert!(close_to(middle(last), spot, 150.0), "{last:?}, {spot:?}"); + + // Dragged down far and let go, it flies back into the spot rather + // than on down. + let photo = option_named(&doc, "Noon on the hill"); + click(&mut doc, photo); + rest(&mut doc); + drag_down(&mut doc, (600.0, 300.0), 200.0, 4, 16, 0); + let last = until_closed(&mut doc).expect("drawn going"); + assert!(close_to(middle(last), spot, 150.0), "{last:?}, {spot:?}"); + + // Opened by a button, it has no spot: it grows where it rests. + open_photos(&mut doc); + let first = photo_frame(&doc); + assert!( + close_to(middle(first), middle(FITS), 2.0) && first.2 > FITS.2 * 0.9, + "{first:?}" + ); + rest(&mut doc); + assert!(near(photo_frame(&doc), FITS), "{:?}", photo_frame(&doc)); + key(&mut doc, Key::Named(NamedKey::Escape)); + assert!(until_closed(&mut doc).is_some(), "fading where it is"); +} diff --git a/src/components/viewer.rs b/src/components/viewer.rs index f9a8672..217edd8 100644 --- a/src/components/viewer.rs +++ b/src/components/viewer.rs @@ -11,6 +11,12 @@ //! //! It is drawn on black whatever the page's appearance, and sets the //! theme's text, dim and hover colours for what is in it to match. +//! +//! It comes and goes in the theme's motion: a photo given the [`Spot`] it +//! was shown in (its thumbnail, or where a finger pressed) flies out of it +//! as the viewer opens, and back into it as the viewer closes, by its +//! button, Escape or a drag down, as a phone's Photos app's does. One with +//! none fades in growing a little, and fades out shrinking, where it is. use std::rc::Rc; use std::time::Duration; @@ -22,7 +28,7 @@ use crate::components::button::{Button, Variant}; use crate::icon::paths; use crate::scroll::{Tracker, wheel_delta, zoom_factor}; use crate::unit::{Kind, Unit, next_id, use_focus, use_unit}; -use crate::zoom::{Dismiss, MOST, PAGE_GAP, Pages, Zoom}; +use crate::zoom::{Dismiss, Flight, MOST, PAGE_GAP, Pages, Spot, Zoom, shrunk}; /// How far a pointer may move and its lifting still be a tap, in CSS /// pixels; how soon a second tap follows the first to make a double tap, @@ -66,13 +72,16 @@ const DOUBLE_TAP_NEAR: f64 = 30.0; /// is in it, read by assistive tech, and a caption drawn under it. `size` /// is its own width and height, in any unit: its shape, which the viewer /// needs to know where its edges are when it is zoomed. With none it is -/// taken to be the window's shape. +/// taken to be the window's shape. `from` is where it was shown on the +/// screen before the viewer opened it, which it flies out of and back into +/// ([`Spot`]). #[derive(Clone, Debug, PartialEq)] pub struct Photo { pub src: String, pub alt: String, pub caption: Option, pub size: Option<(f64, f64)>, + pub from: Option, } impl Photo { @@ -82,6 +91,7 @@ impl Photo { alt: alt.into(), caption: None, size: None, + from: None, } } @@ -94,6 +104,13 @@ impl Photo { self.size = Some((width, height)); self } + + /// Where it was shown on the screen: the viewer opens out of it, and + /// closes back into it while it is the photo shown. + pub fn from(mut self, spot: Spot) -> Self { + self.from = Some(spot); + self + } } /// Milliseconds from a start of its own, for a finger's speed, a double tap @@ -255,6 +272,13 @@ type Key3 = (usize, u64, u64); /// window's size, which the host gives ([`Unit::set_viewport`]); a /// browser's root sets it itself. Without it, the photo fits and does not /// zoom or slide, and the arrows go from photo to photo. +/// +/// It opens and closes in the theme's motion ([`Flight`]), out of and back +/// into the [`Photo::from`] of the photo shown where it has one. Asked to +/// close, by its button, Escape or a drag down, it goes first and then +/// calls `onclose`; a page that sets `open` false of its own accord closes +/// it at once. Where nothing moves ([`crate::MotionSetting::Reduced`], or +/// without the window's size) it comes and goes at once. #[component] pub fn PhotoViewer( open: bool, @@ -275,9 +299,6 @@ pub fn PhotoViewer( let id = use_hook(next_id); let n = photos.len(); let index = index.min(n.saturating_sub(1)); - // Escape closes it, as it does a modal. - let close: Rc = Rc::new(move || onclose.call(())); - unit.modal(id, open.then_some(close)); use_drop(move || unit.modal(id, None)); // The stage: the window inside its safe area, if the host said how @@ -297,6 +318,23 @@ pub fn PhotoViewer( let fitted = move |i: usize| Zoom::new(stage, sizes.get(i).copied().flatten(), most); let key: Key3 = (index, stage.0.to_bits(), stage.1.to_bits()); let fresh = staged.then(|| fitted(index)); + // How long the photo takes to fly out of its spot and back, or to fade + // in and out where it is without one: 0 where nothing moves. + let (travel, enter, exit, grow) = { + let theme = unit.theme.peek(); + let (density, setting) = (*unit.density.peek(), *unit.motion.peek()); + ( + theme.travel_ms(density, setting), + theme.enter_ms(density, setting), + theme.exit_ms(density, setting), + theme.motion.grow, + ) + }; + // Where the photo shown was on the screen, on the stage. + let spot = photos + .get(index) + .and_then(|p| p.from) + .map(|s| s.on_stage((safe.left, safe.top))); // The photo's zoom, for the photo and the stage it was made for: a new // photo, or a window of a new size, starts again from fitting. let zoom = use_signal(|| None::<(Key3, Zoom)>); @@ -304,6 +342,9 @@ pub fn PhotoViewer( let pages = use_signal(|| (index, Pages::default())); // The photo dragged down to close the viewer. let dismiss = use_signal(Dismiss::default); + // The photo flying out of its spot as the viewer opens, or back into + // it as it closes. + let flight = use_signal(|| None::); let running = use_signal(|| false); let touches = use_hook(|| CopyValue::new(Touches::default())); let swipe = use_hook(|| CopyValue::new(None::)); @@ -370,7 +411,19 @@ pub fn PhotoViewer( onclose.call(()); return false; } - swiping || zooming || sliding || dismissing + let mut flight = flight; + let flying = flight.write().as_mut().is_some_and(|f| f.step(dt)); + let landed = *flight.peek(); + if let Some(f) = landed.filter(|f| f.is_there()) { + // Back in its spot, or faded where it was: the viewer closes, + // drawn where it went until the page has closed it. + if f.closes() { + onclose.call(()); + return false; + } + flight.set(None); + } + swiping || zooming || sliding || dismissing || flying }); }; let change = move |f: &mut dyn FnMut(&mut Zoom) -> bool| { @@ -384,6 +437,48 @@ pub fn PhotoViewer( kick(); } }; + // Where the photo shown is drawn now: flying, dragged down, or where it + // rests as it is zoomed. + let drawn = move || -> Option<(f64, f64, f64, f64)> { + if let Some(f) = *flight.peek() { + return Some(f.frame()); + } + let z = current()?; + let d = *dismiss.peek(); + Some(if d.is_active() { + d.carried(z.frame(), stage) + } else { + z.frame() + }) + }; + // Close: the photo flies back into its spot, or fades where it is, and + // then the viewer closes; at once where nothing moves. + let leave = move || { + if let Some(f) = (*flight.peek()).filter(|f| f.closes()) { + // Going already; gone, and the page has yet to close it. + if f.is_there() { + onclose.call(()); + } + return; + } + let length = if spot.is_some() { travel } else { exit }; + let Some(from) = drawn().filter(|_| length > 0.0) else { + onclose.call(()); + return; + }; + let fade = match *flight.peek() { + Some(f) => f.fade(), + None => dismiss.peek().fade(stage.1), + }; + let to = spot.unwrap_or_else(|| shrunk(from, grow)); + let (mut flight, mut dismiss, mut pages) = (flight, dismiss, pages); + dismiss.set(Dismiss::default()); + if pages.peek().1.is_dragging() { + pages.write().1.release(0.0, stride, false, false); + } + flight.set(Some(Flight::closing(from, to, fade, length))); + kick(); + }; // Go to photo `to`, sliding it in from its side where there is a stage. let slide_to = move |to: usize| { if to == index || to >= n { @@ -406,6 +501,10 @@ pub fn PhotoViewer( let zoomed = shown.is_some_and(|z| z.is_zoomed()); let middle = (stage.0 / 2.0, stage.1 / 2.0); + // Escape closes it, as it does a modal. + let close: Rc = Rc::new(leave); + unit.modal(id, open.then_some(close)); + let focus = use_focus(Kind::Widget, move |key, _| { let to = match key { Key::Named(NamedKey::ArrowLeft) => index.saturating_sub(1), @@ -437,13 +536,42 @@ pub fn PhotoViewer( }); // The keys while it is open, and back where they were after. let before = use_hook(|| CopyValue::new(None)); + // How the photo flies as the viewer opens, worked out in the draw that + // opens it, which draws it where its flight begins, and set flying + // after. + let opening = use_hook(|| CopyValue::new(None::)); + let opened = use_hook(|| CopyValue::new(false)); + if open && !*opened.peek() && opening.peek().is_none() { + let length = if spot.is_some() { travel } else { enter }; + let start = fresh.filter(|_| length > 0.0).map(|z| { + Flight::opening( + spot.unwrap_or_else(|| shrunk(z.frame(), grow)), + z.frame(), + length, + ) + }); + opening.clone().set(start); + } use_effect(use_reactive!(|open| { + let mut flight = flight; if open { dismiss.clone().set(Dismiss::default()); before.clone().set(unit.current()); focus.take(); - } else if unit.focused() == Some(focus.id) { - unit.restore(*before.peek()); + opened.clone().set(true); + if let Some(f) = opening.clone().take() { + flight.set(Some(f)); + kick(); + } + } else { + opened.clone().set(false); + opening.clone().set(None); + if flight.peek().is_some() { + flight.set(None); + } + if unit.focused() == Some(focus.id) { + unit.restore(*before.peek()); + } } })); @@ -454,8 +582,11 @@ pub fn PhotoViewer( // Dragged down: the photo smaller, and the viewer's black and its bar // fading, the page under it showing through. let d = *dismiss.read(); - let fade = d.fade(stage.1); - let lifted = d.is_active().then(|| { + // Flying out of its spot or back, or about to: where the photo shown is + // drawn, and how much of the viewer shows. + let flown = (*flight.read()).or(*opening.peek()); + let fade = flown.map_or(d.fade(stage.1), |f| f.fade()); + let lifted = (d.is_active() && flown.is_none()).then(|| { format!( "; transform: translate({}px, {}px) scale({})", d.at.0, @@ -475,8 +606,9 @@ pub fn PhotoViewer( (index.saturating_sub(1)..=(index + 1).min(n - 1)) .map(|i| { let x = offset + (i as f64 - index as f64) * stride; - let frame = match (i == index, shown) { - (true, Some(z)) => z.frame(), + let frame = match (i == index, flown, shown) { + (true, Some(f), _) => f.frame(), + (true, None, Some(z)) => z.frame(), _ => fitted(i).frame(), }; (i, x, frame) @@ -564,6 +696,10 @@ pub fn PhotoViewer( div { class: "unit-viewer-stage", style: "left: {safe.left}px; top: {safe.top}px; right: {safe.right}px; bottom: {safe.bottom}px", onpointerdown: move |e: PointerEvent| { + // Flying, it is not to be caught. + if flight.peek().is_some() { + return; + } let p = local(&e); let mut t = touches; let mut t = t.write(); @@ -688,10 +824,15 @@ pub fn PhotoViewer( }); kick(); } else if dismiss.peek().is_dragging() { - // Down far or fast enough: on down, and closed; - // else back where it rests. + // Down far or fast enough: on down, and closed, + // or back into its spot where it has one; else + // back where it rests. let mut dismiss = dismiss; - dismiss.write().release(speed); + let goes = dismiss.write().release(speed); + if goes && spot.is_some() && travel > 0.0 { + leave(); + return; + } kick(); } else if pages.peek().1.is_dragging() { // On to the next photo, or back to this one, @@ -735,7 +876,11 @@ pub fn PhotoViewer( div { key: "{i}", class: "unit-viewer-page", style: "left: {x}px; width: {stage.0}px{lifted.as_deref().filter(|_| i == index).unwrap_or_default()}", "aria-hidden": (i != index).then_some("true"), - div { class: if i == index { "unit-viewer-photo current" } else { "unit-viewer-photo" }, + div { class: match (i == index, flown.is_some() && photos[i].size.is_some()) { + (true, true) => "unit-viewer-photo current unit-flying", + (true, false) => "unit-viewer-photo current", + _ => "unit-viewer-photo", + }, style: "left: {fx}px; top: {fy}px; width: {fw}px; height: {fh}px", // `alt` for a browser; Blitz names an image by // its label. Not the browser's to drag away as @@ -749,11 +894,11 @@ pub fn PhotoViewer( img { class: "unit-viewer-image unit-viewer-whole", src: "{photo.src}", alt: "{photo.alt}", "aria-label": "{photo.alt}", draggable: "false" } } - if prev && !zoomed && !d.is_active() { + if prev && !zoomed && !d.is_active() && flown.is_none() { Button { variant: Variant::Ghost, class: "unit-icon unit-viewer-prev", label: "Previous photo", icon: paths::CHEVRON_LEFT, refuses_keys: true, onpress: move |_| slide_to(index - 1) } } - if next && !zoomed && !d.is_active() { + if next && !zoomed && !d.is_active() && flown.is_none() { Button { variant: Variant::Ghost, class: "unit-icon unit-viewer-next", label: "Next photo", icon: paths::CHEVRON_RIGHT, refuses_keys: true, onpress: move |_| slide_to(index + 1) } } @@ -763,7 +908,7 @@ pub fn PhotoViewer( div { class: "unit-viewer-actions", {actions} Button { variant: Variant::Ghost, class: "unit-icon", label: "Close", icon: paths::CLOSE, - refuses_keys: true, onpress: move |_| onclose.call(()) } + refuses_keys: true, onpress: move |_| leave() } } } if let Some(c) = &photo.caption { diff --git a/src/lib.rs b/src/lib.rs index a6a97e5..145ca41 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -107,6 +107,7 @@ pub use unit::{ Clipboard, Focus, Insets, Keys, Kind, Unit, UnitRoot, next_id, use_focus, use_unit, use_unit_provider, }; +pub use zoom::Spot; /// Everything a page uses, at once. pub mod prelude { @@ -117,9 +118,9 @@ pub mod prelude { 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, + Spacer, Spot, 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 7c708fe..bae7bfb 100644 --- a/src/style.rs +++ b/src/style.rs @@ -587,6 +587,10 @@ pub const CSS: &str = r#" .unit-viewer-page { position: absolute; top: 0; bottom: 0; } .unit-viewer-photo { position: absolute; } .unit-viewer-photo .unit-viewer-image { display: block; width: 100%; height: 100%; } +/* Flying out of its thumbnail or back into it, the photo fills the box it + is in, cropped as a thumbnail is, until its box is its own shape. */ +.unit-viewer-photo.unit-flying { overflow: hidden; } +.unit-viewer-photo.unit-flying .unit-viewer-image { object-fit: cover; } .unit-viewer-image.unit-viewer-whole { position: absolute; left: 0; top: 0; width: 100%; height: 100%; object-fit: contain; } .unit-viewer-bar { position: absolute; left: 0; top: 0; right: 0; display: flex; align-items: center; diff --git a/src/theme.rs b/src/theme.rs index 19c6d17..56c5dec 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -485,6 +485,10 @@ pub struct Motion { /// How far, in pixels, what rises from the bottom (a sheet, a toast) /// starts below where it ends. pub rise: f64, + /// What travels across the screen: a photo flying out of the spot it + /// was shown in to fill the window, and back into it as it closes. + /// Longer than what appears in place, as it goes further. + pub travel: f64, } impl Motion { @@ -497,6 +501,7 @@ impl Motion { ease_exit: "cubic-bezier(0.4, 0, 1, 1)", grow: 0.97, rise: 12.0, + travel: 300.0, }; /// [`Theme::soft`]'s: a little longer, on a spring that passes its mark @@ -509,6 +514,7 @@ impl Motion { ease_exit: "cubic-bezier(0.4, 0, 1, 1)", grow: 0.94, rise: 24.0, + travel: 400.0, }; /// [`Theme::sharp`]'s: short, straight, and a fade with no growing. @@ -520,6 +526,7 @@ impl Motion { ease_exit: "linear", grow: 1.0, rise: 0.0, + travel: 160.0, }; fn entries(&self) -> [(&'static str, String); 5] { @@ -705,10 +712,25 @@ impl Theme { /// 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 { + self.timed(self.motion.exit, density, setting) + } + + /// What appears takes, as [`Theme::exit_ms`] says what goes does. + pub fn enter_ms(&self, density: Density, setting: MotionSetting) -> f64 { + self.timed(self.motion.enter, density, setting) + } + + /// What travels across the screen takes ([`Motion::travel`]), as + /// [`Theme::exit_ms`] says what goes does. + pub fn travel_ms(&self, density: Density, setting: MotionSetting) -> f64 { + self.timed(self.motion.travel, density, setting) + } + + fn timed(&self, ms: f64, density: Density, setting: MotionSetting) -> f64 { if setting == MotionSetting::Reduced || density == Density::Cell { 0.0 } else { - self.motion.exit + ms } } @@ -877,6 +899,9 @@ mod tests { 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); + assert_eq!(t.travel_ms(Density::Touch, MotionSetting::Full), 400.0); + assert_eq!(t.travel_ms(Density::Touch, MotionSetting::Reduced), 0.0); + assert_eq!(t.enter_ms(Density::Cell, MotionSetting::Full), 0.0); } #[test] diff --git a/src/zoom.rs b/src/zoom.rs index ea2d532..d3dd2b3 100644 --- a/src/zoom.rs +++ b/src/zoom.rs @@ -592,6 +592,22 @@ impl Dismiss { 1.0 - 0.3 * self.progress(height) } + /// Where `frame`, the photo where it rests on a `stage` it is the width + /// and height of, is drawn now: moved by [`Dismiss::at`] and drawn + /// [`Dismiss::scale`] times its size about the stage's middle, as the + /// viewer's transform draws it. + pub fn carried(&self, frame: (f64, f64, f64, f64), stage: (f64, f64)) -> (f64, f64, f64, f64) { + let s = self.scale(stage.1); + let (cx, cy) = (stage.0 / 2.0, stage.1 / 2.0); + let (x, y, w, h) = frame; + ( + cx + (x - cx) * s + self.at.0, + cy + (y - cy) * s + self.at.1, + w * s, + h * s, + ) + } + /// How much of the viewer's black, and its bar and caption, still /// shows: gone by the time the photo is 40% of a stage down. pub fn fade(&self, height: f64) -> f64 { @@ -649,6 +665,180 @@ impl Dismiss { } } +// ── Flying between a spot on the screen and the stage ──────────────────── + +/// A place on the screen a photo was shown before the viewer opened it, in +/// the window's CSS pixels: the thumbnail it was tapped in, or the point +/// where a finger pressed. The viewer flies the photo out of it as it opens +/// and back into it as it closes ([`Flight`]). +/// +/// A point is a spot of no size: the photo grows out of it, and shrinks +/// back into it. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Spot { + pub x: f64, + pub y: f64, + pub width: f64, + pub height: f64, +} + +impl Spot { + /// The box at `x`, `y`, `width` × `height`: a thumbnail's. + pub fn rect(x: f64, y: f64, width: f64, height: f64) -> Self { + Self { + x, + y, + width: width.max(0.0), + height: height.max(0.0), + } + } + + /// The point `x`, `y`: where a finger pressed. + pub fn point(x: f64, y: f64) -> Self { + Self::rect(x, y, 0.0, 0.0) + } + + /// Where it is on a stage whose top left is `origin` in the window, as + /// a [`Zoom::frame`] is: left, top, width, height. + pub fn on_stage(&self, origin: (f64, f64)) -> (f64, f64, f64, f64) { + ( + self.x - origin.0, + self.y - origin.1, + self.width, + self.height, + ) + } +} + +/// A photo flying from one frame on the stage to another, as the viewer's +/// black and its bar fade from one share to another: out of a [`Spot`] to +/// where it rests as the viewer opens, and from wherever it is back into +/// its spot, or shrinking a little where it is, as it closes. +/// +/// It follows a curve that starts quickly and settles, as the theme's own +/// does, over `length` milliseconds; a length of 0 is there at once. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Flight { + from: (f64, f64, f64, f64), + to: (f64, f64, f64, f64), + fade: (f64, f64), + elapsed: f64, + length: f64, + closes: bool, +} + +impl Flight { + /// The photo opening: out of `from` to `to`, where it rests, the + /// viewer's black coming in from nothing. + pub fn opening(from: (f64, f64, f64, f64), to: (f64, f64, f64, f64), length: f64) -> Self { + Self { + from, + to, + fade: (0.0, 1.0), + elapsed: 0.0, + length: length.max(0.0), + closes: false, + } + } + + /// The photo closing: from `from`, where it is now, to `to`, the + /// viewer's black going from `fade` to nothing. + pub fn closing( + from: (f64, f64, f64, f64), + to: (f64, f64, f64, f64), + fade: f64, + length: f64, + ) -> Self { + Self { + from, + to, + fade: (fade, 0.0), + elapsed: 0.0, + length: length.max(0.0), + closes: true, + } + } + + /// How far along it is, on its curve: 0 where it began, 1 there. + fn progress(&self) -> f64 { + if self.length <= 0.0 { + return 1.0; + } + settle((self.elapsed / self.length).clamp(0.0, 1.0)) + } + + /// Where the photo is drawn on the stage now: left, top, width, height. + pub fn frame(&self) -> (f64, f64, f64, f64) { + let p = self.progress(); + let at = |a: f64, b: f64| a + (b - a) * p; + ( + at(self.from.0, self.to.0), + at(self.from.1, self.to.1), + at(self.from.2, self.to.2), + at(self.from.3, self.to.3), + ) + } + + /// How much of the viewer's black, and its bar and caption, shows now. + pub fn fade(&self) -> f64 { + let p = self.progress(); + (self.fade.0 + (self.fade.1 - self.fade.0) * p).clamp(0.0, 1.0) + } + + /// Whether it closes the viewer when it is there. + pub fn closes(&self) -> bool { + self.closes + } + + /// Whether it has got where it was going. + pub fn is_there(&self) -> bool { + self.elapsed >= self.length + } + + /// Move on by `dt` milliseconds. Whether it is still flying. + pub fn step(&mut self, dt: f64) -> bool { + self.elapsed = (self.elapsed + dt.clamp(0.0, 100.0)).min(self.length); + !self.is_there() + } +} + +/// `frame` drawn `scale` times its size about its own middle: where a photo +/// that fades where it is without a spot starts or ends. +pub fn shrunk(frame: (f64, f64, f64, f64), scale: f64) -> (f64, f64, f64, f64) { + let (x, y, w, h) = frame; + let (cx, cy) = (x + w / 2.0, y + h / 2.0); + ( + cx - w * scale / 2.0, + cy - h * scale / 2.0, + w * scale, + h * scale, + ) +} + +/// The curve a flight follows: `cubic-bezier(0.2, 0, 0, 1)`, unit's own +/// ([`crate::Motion::DEFAULT`]), quick from the start and settling into +/// place. `t` is how much of the time has passed; what it gives, how much +/// of the way. +fn settle(t: f64) -> f64 { + if t <= 0.0 || t >= 1.0 { + return t.clamp(0.0, 1.0); + } + // A cubic Bézier from (0, 0) to (1, 1) through (0.2, 0) and (0, 1): + // find the `s` along it whose x is `t`, and give its y. + let x = |s: f64| 3.0 * (1.0 - s) * (1.0 - s) * s * 0.2 + s * s * s; + let y = |s: f64| 3.0 * (1.0 - s) * s * s + s * s * s; + let (mut lo, mut hi) = (0.0, 1.0); + for _ in 0..40 { + let mid = (lo + hi) / 2.0; + if x(mid) < t { + lo = mid; + } else { + hi = mid; + } + } + y((lo + hi) / 2.0) +} + #[cfg(test)] mod tests { use super::*; @@ -879,4 +1069,61 @@ mod tests { assert_eq!(up.fade(800.0), 1.0); assert!(!up.release((0.0, -1.0))); } + + #[test] + fn a_flight_settles_from_where_it_began_to_where_it_goes() { + // Out of an 80 × 80 thumbnail at (40, 600), to where the photo rests. + let to = phone().frame(); + let mut f = Flight::opening((40.0, 600.0, 80.0, 80.0), to, 300.0); + assert_eq!(f.frame(), (40.0, 600.0, 80.0, 80.0), "where it was shown"); + assert_eq!(f.fade(), 0.0); + // Frames of 50ms: a frame longer than 100ms counts as 100. + for _ in 0..3 { + assert!(f.step(50.0)); + } + let (x, y, w, _) = f.frame(); + assert!(w > 80.0 + 0.5 * (400.0 - 80.0), "quick at first: {w}"); + assert!(x < 40.0 && y < 600.0 && y > 250.0, "{x}, {y}"); + assert!(f.fade() > 0.5 && f.fade() < 1.0, "{}", f.fade()); + assert!(f.step(100.0) && f.step(25.0)); + assert!(!f.step(25.0), "there in its time"); + assert_eq!(f.frame(), to); + assert_eq!(f.fade(), 1.0); + assert!(!f.closes()); + } + + #[test] + fn a_flight_of_no_length_is_there_at_once() { + let f = Flight::closing((0.0, 0.0, 400.0, 300.0), (10.0, 10.0, 0.0, 0.0), 1.0, 0.0); + assert!(f.is_there() && f.closes()); + assert_eq!(f.frame(), (10.0, 10.0, 0.0, 0.0)); + assert_eq!(f.fade(), 0.0); + } + + #[test] + fn a_spot_is_placed_on_the_stage_and_a_point_has_no_size() { + let s = Spot::point(100.0, 200.0); + assert_eq!(s.on_stage((0.0, 47.0)), (100.0, 153.0, 0.0, 0.0)); + let r = Spot::rect(10.0, 20.0, -5.0, 30.0); + assert_eq!((r.width, r.height), (0.0, 30.0)); + assert_eq!( + shrunk((0.0, 250.0, 400.0, 300.0), 0.5), + (100.0, 325.0, 200.0, 150.0) + ); + } + + #[test] + fn a_photo_dragged_down_is_drawn_where_its_transform_puts_it() { + let mut d = Dismiss::default(); + d.drag_start((200.0, 300.0)); + d.drag_move((230.0, 500.0), 800.0); + let (x, y, w, h) = d.carried(phone().frame(), (400.0, 800.0)); + let s = d.scale(800.0); + assert!(near(w, 400.0 * s) && near(h, 300.0 * s)); + // Its middle is the stage's, moved as the finger moved. + assert!( + near(x + w / 2.0, 230.0) && near(y + h / 2.0, 600.0), + "{x}, {y}" + ); + } }