Skip to main content

Router

Struct Router 

Source
pub struct Router;
Expand description

Router functionality for managing browser history, overlays, and navigation.

Provides methods for scroll-to-top behavior, hash change handling, overlay history management, and drawer scroll positioning.

Implementations§

Source§

impl Router

Implementation of router functionality.

Provides methods for managing browser history, overlays, navigation, and scroll behavior.

Source

pub fn use_scroll_to_top(route_signal: Signal<String>)

Watches the route signal and scrolls the <main> content container back to the top whenever the route changes.

On each route change, queries the document for the first <main> element and resets its scrollTop to zero. The sidebar scroll position is preserved natively since the <nav> element is never destroyed during route transitions.

§Arguments
  • Signal<String> - The reactive signal holding the current route path.
Source

pub fn use_hash_change(route_signal: Signal<String>)

Subscribes to browser hashchange events and updates the given signal.

Registers a global event listener on window that reads the current route on every hash change and writes it into the provided signal. The listener is automatically removed when the hook context is cleared.

Increments WINDOW_EVENT_DEPTH before dispatching and decrements it after, so that any code that checks re-entrancy can detect that it is running within a window event handler context.

Note: navigate() always defers set_hash() to a microtask, so by the time the hashchange fires, all caller frames have already unwound and there is no risk of recursive Closure invocation. The handler only needs to update the route signal with the current URL hash value.

§Arguments
  • Signal<String> - The reactive signal that holds the current route and will be updated on each hash change.
Source

pub fn use_overlay_history( drawer_open: Signal<bool>, mobile_signal: Signal<bool>, )

Manages browser history for all overlays (modals, panels, drawers) so that the back button closes the most recently opened overlay instead of navigating away.

Uses a unified OVERLAY_STACK that records every overlay in the order it was opened. A popstate listener pops the topmost entry and invokes its close callback, so overlays close in reverse opening order regardless of type.

Before consulting the overlay stack, the listener iterates over all registered popstate guards (see [register_popstate_guard]). The first guard that returns true consumes the event, preventing the overlay stack and normal navigation from processing it.

§Arguments
  • Signal<bool> - The reactive signal controlling the nav drawer visibility.
  • Signal<bool> - The reactive signal tracking whether the viewport is mobile-sized.
Source

pub fn use_scroll_drawer_to_active(drawer_open: Signal<bool>)

Watches the drawer open signal and scrolls the mobile navigation drawer to make the currently active navigation item visible when the drawer opens.

Uses nested requestAnimationFrame to defer the scroll until after the framework has completed its DOM update cycle. The first requestAnimationFrame fires after the framework’s own requestAnimationFrame-based render pass, and the second one fires after the browser has laid out the new DOM. Locates the scrollable c-nav-items-scroll container and the active nav item within the drawer, then sets scrollTop so the active item appears near the vertical center of the container.

§Arguments
  • Signal<bool> - The reactive signal controlling the mobile nav drawer visibility.
Source

pub fn register_popstate_guard(guard: Rc<dyn Fn() -> bool>) -> usize

Registers a popstate guard callback that is invoked on every popstate event before the overlay stack is consulted.

Guards are called in registration order. The first guard that returns true consumes the popstate event, preventing the overlay stack and normal navigation from processing it. This allows external modules (e.g. native fullscreen, canvas fullscreen) to intercept the system back gesture without registering their own independent popstate listener.

Returns a guard ID that can be passed to Router::unregister_popstate_guard to remove the guard when it is no longer needed.

§Arguments
  • Rc<dyn Fn() -> bool> - The guard callback. Return true to consume the popstate event, false to let subsequent guards or the overlay stack handle it.
§Returns
  • usize - A unique guard ID for later unregistration.
Source

pub fn overlay_push_state()

Pushes a browser history entry for an overlay that is about to open.

Call this when an overlay (vconsole panel) opens so that the browser back button will close the overlay instead of navigating away.

Source

pub fn overlay_back(navigate_target: Option<String>)

Performs a programmatic history.back() to consume the overlay’s history entry, optionally scheduling a navigation to run after the popstate event fires.

§Arguments
  • Option<String> - An optional route to navigate to after the back completes.
Source

pub fn overlay_stack_close()

Closes the most recently opened overlay via the UI and consumes one browser history entry.

Pops the top entry from OVERLAY_STACK and calls overlay_back so that the history count stays in sync. Use this when the user dismisses an overlay through a close button, overlay click, or confirm/cancel action.

Source

pub fn modal_push(visible: Signal<bool>, closer: Rc<dyn Fn()>)

Registers an open modal by pushing it onto the global modal stack and adding a browser history entry, enabling nested modals.

The stack is ordered with the most recently opened modal on top. When the user triggers a system back gesture (or presses the browser back button), the popstate handler pops the topmost entry from OVERLAY_STACK and invokes its close callback, so the most recently opened overlay is dismissed first instead of navigating to the previous page.

If the given visibility signal is already on the stack, this is a no-op so that re-opening an already-open modal does not create duplicate stack or history entries.

§Arguments
  • Signal<bool> - The modal’s visibility signal, used as a stable identity for later removal.
  • Rc<dyn Fn()> - The callback that closes the modal (e.g., sets the visibility signal to false).
Source

pub fn modal_close_via_ui(visible: Signal<bool>)

Closes a modal that was opened via Router::modal_push when the user dismisses it through the UI (close button, overlay click, confirm/cancel action) rather than the system back gesture.

Removes the entry matching the given visibility signal from the global stack (by identity, not necessarily the top, so nested modals stay consistent) and consumes one matching browser history entry via overlay_stack_close, keeping the history count in sync so a subsequent back gesture behaves correctly.

§Arguments
  • Signal<bool> - The visibility signal identifying the modal to remove.
Source

pub fn open_system_browser<U>(url: U)
where U: AsRef<str>,

Opens the given URL in the system default browser using window.open with the _system target name.

In a bridge WebView environment, the _system target instructs the shell opener plugin to delegate the URL to the operating system’s default browser. In a regular browser, window.open falls back to opening a new tab or window as usual.

§Arguments
  • U: AsRef<str> - The URL to open.

Creates a click event handler for external <a> links that opens the URL in the system default browser.

Calls event.prevent_default() to suppress the <a> element’s default navigation (which would open inside the WebView), then delegates to open_system_browser so the URL is handled by the operating system’s default browser.

§Arguments
  • U: AsRef<str> - The external URL to open on click.
§Returns
  • NativeEventHandler - An event handler for click events.
Source

pub fn close_drawer_and_navigate<T>(_drawer_open: Signal<bool>, target: T)
where T: AsRef<str>,

Helper to close the drawer and navigate.

Used internally by mobile nav items. Closes the drawer via overlay back and schedules navigation to the target route after the popstate event is processed.

§Arguments
  • Signal<bool> - The drawer open signal.
  • T: AsRef<str> - The target route.
Source§

impl Router

Implementation of router navigation and viewport utilities.

Source

pub fn current_route() -> String

Reads the current hash-based route from the browser URL.

§Returns
  • String - The hash fragment without the leading #, or DEFAULT_ROUTE_PATH if empty.
Source

pub fn navigate<R>(route: R)
where R: AsRef<str>,

Navigates to a new hash-based route.

Always defers the actual location.set_hash() call to queueMicrotask to prevent synchronous hashchange dispatch while any caller frame is still on the stack. This avoids wasm_bindgen’s "closure invoked recursively or after being dropped" error which occurs when set_hash() fires hashchange synchronously and the handler (or the reactive update chain it triggers) calls navigate() again before the original dispatch finishes.

Multiple rapid navigate() calls before the microtask fires are coalesced: only the last target route wins, as earlier routes were superseded by

§Arguments
  • R: AsRef<str> - The target route path.

Creates a link click handler that navigates to the given route.

Calls event.prevent_default() to prevent the <a> element’s default hash navigation, then programmatically navigates via navigate(). Without preventDefault, both the <a href> default behavior and navigate() would fire, potentially creating duplicate history entries and causing incorrect browser back/forward behavior.

§Arguments
  • R: AsRef<str> - The target route path.
§Returns
  • NativeEventHandler - An event handler for click events.
Source

pub fn is_mobile() -> bool

Checks whether the current viewport width qualifies as a mobile device.

Uses MOBILE_BREAKPOINT (768px) as the threshold.

§Returns
  • bool - true if the viewport width is less than the mobile breakpoint.

Trait Implementations§

Source§

impl Clone for Router

Source§

fn clone(&self) -> Router

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Router

Source§

impl Debug for Router

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Router

Source§

fn default() -> Router

Returns the “default value” for a type. Read more
Source§

impl Eq for Router

Source§

impl Hash for Router

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for Router

Source§

fn cmp(&self, other: &Router) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for Router

Source§

fn eq(&self, other: &Router) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for Router

Source§

fn partial_cmp(&self, other: &Router) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl StructuralPartialEq for Router

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more