fix: check whether we're on the server before adding window event listener (closes #2891) (#2910)

This commit is contained in:
Greg Johnston 2024-09-02 09:11:07 -04:00 committed by GitHub
parent 998165148b
commit 2b8e987cb8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 26 additions and 14 deletions

View file

@ -56,6 +56,7 @@ hydration = [
"reactive_graph/hydration",
"leptos_server/hydration",
"hydration_context/browser",
"leptos_dom/hydration"
]
csr = ["leptos_macro/csr", "reactive_graph/effects"]
hydrate = [

View file

@ -30,6 +30,7 @@ features = ["Location"]
default = []
tracing = ["dep:tracing"]
trace-component-props = ["dep:serde", "dep:serde_json"]
hydration = ["reactive_graph/hydration"]
[package.metadata.docs.rs]
rustdoc-args = ["--generate-link-to-definition"]

View file

@ -64,18 +64,17 @@ pub fn location() -> web_sys::Location {
/// Current [`window.location.hash`](https://developer.mozilla.org/en-US/docs/Web/API/Window/location)
/// without the beginning #.
pub fn location_hash() -> Option<String> {
// TODO use shared context for is_server
/*if is_server() {
if is_server() {
None
} else {*/
location()
.hash()
.ok()
.map(|hash| match hash.chars().next() {
Some('#') => hash[1..].to_string(),
_ => hash,
})
//}
} else {
location()
.hash()
.ok()
.map(|hash| match hash.chars().next() {
Some('#') => hash[1..].to_string(),
_ => hash,
})
}
}
/// Current [`window.location.pathname`](https://developer.mozilla.org/en-US/docs/Web/API/Window/location).
@ -475,9 +474,7 @@ pub fn window_event_listener_untyped(
cb(e);
};
// TODO use shared context for is_server
if true {
// !is_server() {
if !is_server() {
#[inline(never)]
fn wel(
cb: Box<dyn FnMut(web_sys::Event)>,
@ -550,3 +547,16 @@ impl WindowListenerHandle {
(self.0)()
}
}
fn is_server() -> bool {
#[cfg(feature = "hydration")]
{
Owner::current_shared_context()
.map(|sc| !sc.is_browser())
.unwrap_or(false)
}
#[cfg(not(feature = "hydration"))]
{
false
}
}