fix: router should still scroll to hash even if path didn't change (closes #1907) (#1917)

This commit is contained in:
Greg Johnston 2023-10-20 14:57:35 -04:00 committed by GitHub
parent c87328f5cf
commit bf14999eb2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 17 deletions

View file

@ -1,6 +1,6 @@
use crate::{
create_location, matching::resolve_path, Branch, History, Location,
LocationChange, RouteContext, RouterIntegrationContext, State,
create_location, matching::resolve_path, scroll_to_el, Branch, History,
Location, LocationChange, RouteContext, RouterIntegrationContext, State,
};
#[cfg(not(feature = "ssr"))]
use crate::{unescape, Url};
@ -302,6 +302,8 @@ impl RouterContextInner {
});
}
});
} else {
scroll_to_el(false);
}
Ok(())

View file

@ -118,24 +118,28 @@ impl History for BrowserIntegration {
.unwrap_throw();
}
// scroll to el
if let Ok(hash) = leptos_dom::helpers::location().hash() {
if !hash.is_empty() {
let hash = js_sys::decode_uri(&hash[1..])
.ok()
.and_then(|decoded| decoded.as_string())
.unwrap_or(hash);
let el = leptos_dom::document().get_element_by_id(&hash);
if let Some(el) = el {
el.scroll_into_view();
return;
}
scroll_to_el(loc.scroll);
}
}
pub(crate) fn scroll_to_el(loc_scroll: bool) {
if let Ok(hash) = leptos_dom::helpers::location().hash() {
if !hash.is_empty() {
let hash = js_sys::decode_uri(&hash[1..])
.ok()
.and_then(|decoded| decoded.as_string())
.unwrap_or(hash);
let el = leptos_dom::document().get_element_by_id(&hash);
if let Some(el) = el {
el.scroll_into_view();
return;
}
}
}
// scroll to top
if loc.scroll {
leptos_dom::window().scroll_to_with_x_and_y(0.0, 0.0);
}
// scroll to top
if loc_scroll {
leptos_dom::window().scroll_to_with_x_and_y(0.0, 0.0);
}
}