//! Animated DOM updates: tiles carrying a `view-transition-name` glide from //! their old place to their new one, even across lists. /// Runs `update` inside a view transition, or right away when the browser /// does not support them. pub fn animate(update: impl FnOnce() + 'static) { #[cfg(feature = "hydrate")] browser::animate(update); #[cfg(not(feature = "hydrate"))] update(); } /// `view-transition-name` of an item tile, the same in both lists. pub fn item_name(id: i64) -> String { format!("item-{id}") } /// `view-transition-name` of a suggestion tile. Product names may contain /// spaces or accents, which are not allowed in an identifier: hex-encode them. pub fn suggestion_name(name: &str) -> String { let hex: String = name.bytes().map(|b| format!("{b:02x}")).collect(); format!("suggestion-{hex}") } #[cfg(feature = "hydrate")] mod browser { use js_sys::{Function, Promise, Reflect}; use leptos::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen::closure::Closure; pub fn animate(update: impl FnOnce() + 'static) { let document = document(); let start = Reflect::get(&document, &"startViewTransition".into()) .ok() .and_then(|start| start.dyn_into::().ok()); let Some(start) = start else { return update(); }; let callback = Closure::once_into_js(move || { update(); // Leptos patches the DOM in a microtask: the new state is // ready by the next timeout. Promise::new(&mut |resolve, _| { let _ = window().set_timeout_with_callback(&resolve); }) }); let _ = start.call1(&document, &callback); } }