use std::borrow::Cow;
use wasm_bindgen::JsCast;
use web_sys::{Element, HtmlElement};
use super::waapi::{animate, AnimateOptions, Keyframe};
#[derive(Clone, Debug)]
pub struct CollapseOptions {
pub duration_ms: f64,
pub easing: Cow<'static, str>,
}
impl Default for CollapseOptions {
fn default() -> Self {
Self {
duration_ms: 200.0,
easing: Cow::Borrowed("cubic-bezier(0.2, 0, 0, 1)"),
}
}
}
pub fn collapse_to(el: &Element, open: bool, opts: CollapseOptions) {
let Ok(html) = el.clone().dyn_into::<HtmlElement>() else {
return;
};
if open {
let style = html.style();
let _ = style.set_property("overflow", "hidden");
let target = el.scroll_height() as f64;
animate(
el,
&[
Keyframe::from_iter([("height", "0px")]),
Keyframe::from_iter([("height", format!("{}px", target))]),
],
AnimateOptions {
duration_ms: opts.duration_ms,
easing: opts.easing,
delay_ms: 0.0,
fill: "none",
respect_motion_preference: true,
},
)
.on_finish(move || {
let style = html.style();
let _ = style.remove_property("overflow");
let _ = style.remove_property("height");
});
} else {
let current = el.get_bounding_client_rect().height();
let style = html.style();
let _ = style.set_property("overflow", "hidden");
animate(
el,
&[
Keyframe::from_iter([("height", format!("{}px", current))]),
Keyframe::from_iter([("height", "0px")]),
],
AnimateOptions {
duration_ms: opts.duration_ms,
easing: opts.easing,
delay_ms: 0.0,
fill: "forwards",
respect_motion_preference: true,
},
);
}
}