Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,121 changes: 516 additions & 605 deletions Cargo.lock

Large diffs are not rendered by default.

73 changes: 73 additions & 0 deletions examples/router_restore_scroll.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
use std::rc::Rc;

use dioxus::html::geometry::PixelsVector2D;
use dioxus::prelude::*;

#[derive(Clone, Routable, Debug, PartialEq)]
enum Route {
#[route("/")]
Home {},
#[route("/blog/:id")]
Blog { id: i32 },
}

fn main() {
dioxus::launch(App);
}

#[component]
fn App() -> Element {
use_context_provider(|| Signal::new(Scroll::default()));

rsx! {
Router::<Route> {}
}
}

#[component]
fn Blog(id: i32) -> Element {
rsx! {
GoBackButton { "Go back" }
div { "Blog post {id}" }
}
}

type Scroll = Option<PixelsVector2D>;

#[component]
fn Home() -> Element {
let mut element: Signal<Option<Rc<MountedData>>> = use_signal(|| None);
let mut scroll = use_context::<Signal<Scroll>>();

_ = use_resource(move || async move {
if let (Some(element), Some(scroll)) = (element.read().as_ref(), *scroll.peek()) {
element
.scroll(scroll, ScrollBehavior::Instant)
.await
.unwrap();
}
});

rsx! {
div {
height: "300px",
overflow_y: "auto",
border: "1px solid black",

onmounted: move |event| element.set(Some(event.data())),

onscroll: move |_| async move {
if let Some(element) = element.cloned() {
scroll.set(Some(element.get_scroll_offset().await.unwrap()))
}
},

for i in 0..100 {
div { height: "20px",

Link { to: Route::Blog { id: i }, "Blog {i}" }
}
}
}
}
}
59 changes: 59 additions & 0 deletions examples/scroll_to_offset.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//! Scroll elements using their MountedData
//!
//! Dioxus exposes a few helpful APIs around elements (mimicking the DOM APIs) to allow you to interact with elements
//! across the renderers. This includes scrolling, reading dimensions, and more.
//!
//! In this example we demonstrate how to scroll to a given y offset of the scrollable parent using the `scroll` method on the `MountedData`

use dioxus::html::geometry::PixelsVector2D;
use dioxus::prelude::*;

fn main() {
dioxus::launch(app);
}

fn app() -> Element {
rsx! {
ScrollToCoordinates {}
ScrollToCoordinates {}
}
}

#[component]
fn ScrollToCoordinates() -> Element {
let mut element = use_signal(|| None);

rsx! {
div { border: "1px solid black", position: "relative",

div {
height: "300px",
overflow_y: "auto",

onmounted: move |event| element.set(Some(event.data())),

for i in 0..100 {
div { height: "20px", "Item {i}" }
}
}

div { position: "absolute", top: 0, right: 0,
input {
r#type: "number",
min: "0",
max: "99",
oninput: move |event| async move {
if let Some(ul) = element.cloned() {
let data = event.data();
if let Ok(value) = data.parsed::<f64>() {
ul.scroll(PixelsVector2D::new(0.0, 20.0 * value), ScrollBehavior::Smooth)
.await
.unwrap();
}
}
},
}
}
}
}
}
30 changes: 30 additions & 0 deletions packages/desktop/src/element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,36 @@ impl RenderedElementBacking for DesktopElement {
})
}

fn scroll(
&self,
coordinates: PixelsVector2D,
behavior: dioxus_html::ScrollBehavior,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = MountedResult<()>>>> {
let script = format!(
"return window.interpreter.scroll({}, {}, {}, {});",
self.id.0,
coordinates.x,
coordinates.y,
serde_json::to_string(&behavior).expect("Failed to serialize ScrollBehavior")
);
let webview = self
.webview
.upgrade()
.expect("Webview should be alive if the element is being queried");
let fut = self.query.new_query::<bool>(&script, webview).resolve();
Box::pin(async move {
match fut.await {
Ok(true) => Ok(()),
Ok(false) => MountedResult::Err(dioxus_html::MountedError::OperationFailed(
Box::new(DesktopQueryError::FailedToQuery),
)),
Err(err) => {
MountedResult::Err(dioxus_html::MountedError::OperationFailed(Box::new(err)))
}
}
})
}

fn set_focus(
&self,
focus: bool,
Expand Down
19 changes: 19 additions & 0 deletions packages/html/src/events/mounted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,15 @@ pub trait RenderedElementBacking: std::any::Any {
Box::pin(async { Err(MountedError::NotSupported) })
}

/// Scroll to the given element offsets
fn scroll(
&self,
_coordinates: PixelsVector2D,
_behavior: ScrollBehavior,
) -> Pin<Box<dyn Future<Output = MountedResult<()>>>> {
Box::pin(async { Err(MountedError::NotSupported) })
}

/// Set the focus on the element
fn set_focus(&self, _focus: bool) -> Pin<Box<dyn Future<Output = MountedResult<()>>>> {
Box::pin(async { Err(MountedError::NotSupported) })
Expand Down Expand Up @@ -119,6 +128,16 @@ impl MountedData {
self.inner.scroll_to(behavior)
}

/// Scroll to the given element offsets
#[doc(alias = "scrollTo")]
pub fn scroll(
&self,
coordinates: PixelsVector2D,
behavior: ScrollBehavior,
) -> Pin<Box<dyn Future<Output = MountedResult<()>>>> {
self.inner.scroll(coordinates, behavior)
}

/// Set the focus on the element
#[doc(alias = "focus")]
#[doc(alias = "blur")]
Expand Down
2 changes: 1 addition & 1 deletion packages/interpreter/src/js/hash.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
[6449103750905854967, 17669692872757955279, 13069001215487072322, 11420464406527728232, 3770103091118609057, 5444526391971481782, 7965007982501706197, 5052021921702764563, 10988859153374944111, 16153602427306015669]
[6449103750905854967, 17669692872757955279, 13069001215487072322, 11420464406527728232, 3770103091118609057, 5444526391971481782, 15257049569425934744, 5052021921702764563, 10988859153374944111, 16153602427306015669]
2 changes: 1 addition & 1 deletion packages/interpreter/src/js/native.js

Large diffs are not rendered by default.

9 changes: 9 additions & 0 deletions packages/interpreter/src/ts/native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,15 @@ export class NativeInterpreter extends JSChannel_ {
return false;
}

scroll(id: NodeId, x: number, y: number, behavior: ScrollBehavior): boolean {
const node = this.nodes[id];
if (node instanceof HTMLElement) {
node.scroll({ top: y, left: x, behavior });
return true;
}
return false;
}

getScrollHeight(id: NodeId): number | undefined {
const node = this.nodes[id];
if (node instanceof HTMLElement) {
Expand Down
27 changes: 27 additions & 0 deletions packages/liveview/src/element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,33 @@ impl RenderedElementBacking for LiveviewElement {
})
}

fn scroll(
&self,
coordinates: PixelsVector2D,
behavior: dioxus_html::ScrollBehavior,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = MountedResult<()>>>> {
let script = format!(
"return window.interpreter.scroll({}, {}, {}, {});",
self.id.0,
coordinates.x,
coordinates.y,
serde_json::to_string(&behavior).expect("Failed to serialize ScrollBehavior")
);

let fut = self.query.new_query::<bool>(&script).resolve();
Box::pin(async move {
match fut.await {
Ok(true) => Ok(()),
Ok(false) => MountedResult::Err(dioxus_html::MountedError::OperationFailed(
Box::new(DesktopQueryError::FailedToQuery),
)),
Err(err) => {
MountedResult::Err(dioxus_html::MountedError::OperationFailed(Box::new(err)))
}
}
})
}

fn set_focus(
&self,
focus: bool,
Expand Down
1 change: 1 addition & 0 deletions packages/web/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ features = [
"ResizeObserverEntry",
"ResizeObserverSize",
"ScrollRestoration",
"ScrollToOptions",
"Text",
"Touch",
"TouchEvent",
Expand Down
21 changes: 21 additions & 0 deletions packages/web/src/events/mounted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,27 @@ impl dioxus_html::RenderedElementBacking for Synthetic<web_sys::Element> {
Box::pin(async { Ok(()) })
}

fn scroll(
&self,
coordinates: dioxus_html::geometry::PixelsVector2D,
behavior: dioxus_html::ScrollBehavior,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = dioxus_html::MountedResult<()>>>> {
let options = web_sys::ScrollToOptions::new();
options.set_top(coordinates.y);
options.set_left(coordinates.x);
match behavior {
dioxus_html::ScrollBehavior::Instant => {
options.set_behavior(web_sys::ScrollBehavior::Instant);
}
dioxus_html::ScrollBehavior::Smooth => {
options.set_behavior(web_sys::ScrollBehavior::Smooth);
}
}
self.event.scroll_with_scroll_to_options(&options);

Box::pin(async { Ok(()) })
}

fn set_focus(
&self,
focus: bool,
Expand Down
Loading