dioxus/examples/read_size.rs

61 lines
1.5 KiB
Rust
Raw Normal View History

//! Read the size of elements using the MountedData struct.
//!
//! Whenever an Element is finally mounted to the Dom, its data is avaiable to be read.
//! 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-01-31 01:59:57 +00:00
LaunchBuilder::desktop()
.with_cfg(
dioxus::desktop::Config::default().with_custom_head(
r#"
2023-03-24 16:32:42 +00:00
<style type="text/css">
html, body {
height: 100%;
width: 100%;
margin: 0;
}
#main {
height: 100%;
width: 100%;
}
</style>
"#
2024-01-31 01:59:57 +00:00
.to_owned(),
),
)
.launch(app);
2023-03-24 16:32:42 +00:00
}
fn app() -> Element {
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-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!(
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())),
"This element is {dimensions():?}"
2023-03-24 16:32:42 +00:00
}
button { onclick: read_dims, "Read dimensions" }
2024-01-14 05:12:21 +00:00
)
2023-03-24 16:32:42 +00:00
}