From 184f026fd3a2d1a1ed832ff3148dfac6f4413f20 Mon Sep 17 00:00:00 2001 From: Filipe Rodrigues Date: Sun, 4 Feb 2024 10:56:01 +0000 Subject: [PATCH] Added `dynatos_router::Location::{with, update}`. --- dynatos-router/src/location.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/dynatos-router/src/location.rs b/dynatos-router/src/location.rs index bc942db..fb28b7c 100644 --- a/dynatos-router/src/location.rs +++ b/dynatos-router/src/location.rs @@ -28,7 +28,15 @@ impl Location { /// Gets the location as a url pub fn get(&self) -> Url { - self.0.with(|inner| inner.location.clone()) + self.with(|location| location.clone()) + } + + /// Uses the location as a url + pub fn with(&self, f: F) -> O + where + F: FnOnce(&Url) -> O, + { + self.0.with(|inner| f(&inner.location)) } /// Sets the location. @@ -56,6 +64,26 @@ impl Location { Ok(()) } + /// Updates the location + pub fn update(&self, f: F) -> Result + where + F: FnOnce(&mut Url) -> O, + { + self.0.update(|inner| { + let output = f(&mut inner.location); + + let window = web_sys::window().context("Unable to get window")?; + let history = window.history().context("Unable to get history")?; + + // Push the new location into history + history + .push_state_with_url(&JsValue::UNDEFINED, "", Some(inner.location.as_ref())) + .expect("Unable to push history"); + + Ok(output) + }) + } + /// Parses the location as url fn parse_location_url(document: web_sys::Document) -> Result { let location = document.location().context("Document had no location")?;