2024-02-14 21:48:58 +00:00
|
|
|
//! Read the size of elements using the MountedData struct.
|
|
|
|
//!
|
2024-04-19 13:29:22 +00:00
|
|
|
//! Whenever an Element is finally mounted to the Dom, its data is available to be read.
|
2024-02-14 21:48:58 +00:00
|
|
|
//! These fields can typically only be read asynchronously, since various renderers need to release the main thread to
|
|
|
|
//! perform layout and painting.
|
|
|
|
|
2023-03-24 16:32:42 +00:00
|
|
|
use std::rc::Rc;
|
|
|
|
|
|
|
|
use dioxus::{html::geometry::euclid::Rect, prelude::*};
|
|
|
|
|
|
|
|
fn main() {
|
2024-07-25 21:58:00 +00:00
|
|
|
launch(app);
|
2023-03-24 16:32:42 +00:00
|
|
|
}
|
|
|
|
|
2024-01-14 04:51:37 +00:00
|
|
|
fn app() -> Element {
|
2024-01-16 07:24:59 +00:00
|
|
|
let mut div_element = use_signal(|| None as Option<Rc<MountedData>>);
|
|
|
|
let mut dimensions = use_signal(Rect::zero);
|
2023-03-24 16:32:42 +00:00
|
|
|
|
2024-01-31 01:59:57 +00:00
|
|
|
let read_dims = move |_| async move {
|
2024-01-15 21:06:05 +00:00
|
|
|
let read = div_element.read();
|
|
|
|
let client_rect = read.as_ref().map(|el| el.get_client_rect());
|
2024-02-14 21:48:58 +00:00
|
|
|
|
2024-01-15 21:06:05 +00:00
|
|
|
if let Some(client_rect) = client_rect {
|
|
|
|
if let Ok(rect) = client_rect.await {
|
|
|
|
dimensions.set(rect);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
2023-03-24 16:32:42 +00:00
|
|
|
|
2024-01-16 19:18:46 +00:00
|
|
|
rsx!(
|
2024-07-25 21:58:00 +00:00
|
|
|
head::Link { rel: "stylesheet", href: asset!("./examples/assets/read_size.css") }
|
2023-03-24 16:32:42 +00:00
|
|
|
div {
|
|
|
|
width: "50%",
|
|
|
|
height: "50%",
|
|
|
|
background_color: "red",
|
2024-01-31 22:07:00 +00:00
|
|
|
onmounted: move |cx| div_element.set(Some(cx.data())),
|
2024-01-16 05:12:44 +00:00
|
|
|
"This element is {dimensions():?}"
|
2023-03-24 16:32:42 +00:00
|
|
|
}
|
|
|
|
|
2024-01-16 14:42:16 +00:00
|
|
|
button { onclick: read_dims, "Read dimensions" }
|
2024-01-14 05:12:21 +00:00
|
|
|
)
|
2023-03-24 16:32:42 +00:00
|
|
|
}
|