euv_ui/component/router/hook/impl.rs
1use super::*;
2
3/// Implementation of router functionality.
4///
5/// Provides methods for managing browser history, overlays, navigation,
6/// and scroll behavior.
7impl Router {
8 /// Watches the route signal and scrolls the `<main>` content container
9 /// back to the top whenever the route changes.
10 ///
11 /// On each route change, queries the document for the first `<main>`
12 /// element and resets its `scrollTop` to zero. The sidebar scroll
13 /// position is preserved natively since the `<nav>` element is never
14 /// destroyed during route transitions.
15 ///
16 /// # Arguments
17 ///
18 /// - `Signal<String>` - The reactive signal holding the current route path.
19 pub fn use_scroll_to_top(route_signal: Signal<String>) {
20 watch!(route_signal, |_: String| {
21 let Some(window_value) = window() else {
22 return;
23 };
24 let Some(document_value) = window_value.document() else {
25 return;
26 };
27 if let Some(main_element) = document_value
28 .query_selector(ROUTER_MAIN_ELEMENT_SELECTOR)
29 .ok()
30 .flatten()
31 {
32 let html_element: HtmlElement = main_element.unchecked_into();
33 html_element.set_scroll_top(0);
34 }
35 });
36 }
37
38 /// Subscribes to browser `hashchange` events and updates the given signal.
39 ///
40 /// Registers a global event listener on `window` that reads the current
41 /// route on every hash change and writes it into the provided signal.
42 /// The listener is automatically removed when the hook context is cleared.
43 ///
44 /// Increments `WINDOW_EVENT_DEPTH` before dispatching and decrements it
45 /// after, so that any code that checks re-entrancy can detect that it is
46 /// running within a window event handler context.
47 ///
48 /// Note: `navigate()` always defers `set_hash()` to a microtask, so by the
49 /// time the `hashchange` fires, all caller frames have already unwound and
50 /// there is no risk of recursive Closure invocation. The handler only needs
51 /// to update the route signal with the current URL hash value.
52 ///
53 /// # Arguments
54 ///
55 /// - `Signal<String>` - The reactive signal that holds the current route and will be updated on each hash change.
56 pub fn use_hash_change(route_signal: Signal<String>) {
57 App::use_window_event(ROUTER_WINDOW_EVENT_HASH_CHANGE, move || {
58 WINDOW_EVENT_DEPTH.with(|depth: &Cell<usize>| depth.set(depth.get() + 1));
59 route_signal.set(Self::current_route());
60 WINDOW_EVENT_DEPTH.with(|depth: &Cell<usize>| depth.set(depth.get() - 1));
61 });
62 }
63
64 /// Manages browser history for all overlays (modals, panels, drawers) so that
65 /// the back button closes the most recently opened overlay instead of navigating away.
66 ///
67 /// Uses a unified `OVERLAY_STACK` that records every overlay in the order it was opened.
68 /// A `popstate` listener pops the topmost entry and invokes its close callback, so
69 /// overlays close in reverse opening order regardless of type.
70 ///
71 /// Before consulting the overlay stack, the listener iterates over all registered
72 /// `popstate` guards (see [`register_popstate_guard`]). The first guard that returns
73 /// `true` consumes the event, preventing the overlay stack and normal navigation
74 /// from processing it.
75 ///
76 /// # Arguments
77 ///
78 /// - `Signal<bool>` - The reactive signal controlling the nav drawer visibility.
79 /// - `Signal<bool>` - The reactive signal tracking whether the viewport is mobile-sized.
80 pub fn use_overlay_history(drawer_open: Signal<bool>, mobile_signal: Signal<bool>) {
81 let was_drawer_open: Signal<bool> = App::use_signal(|| false);
82 watch!(drawer_open, |is_open: bool| {
83 let previous: bool = was_drawer_open.get();
84 if is_open && !previous && mobile_signal.get() {
85 let closer: Rc<dyn Fn()> = Rc::new(move || {
86 drawer_open.set(false);
87 });
88 Self::overlay_stack_push(closer);
89 }
90 was_drawer_open.set(is_open);
91 });
92 App::use_window_event(ROUTER_WINDOW_EVENT_POP_STATE, move || {
93 WINDOW_EVENT_DEPTH.with(|depth: &Cell<usize>| depth.set(depth.get() + 1));
94 // The guard callbacks run arbitrary page code, and the ones shipped
95 // with euv set signals and call back into `Router` (a fullscreen
96 // guard sets its tab signal, then re-enters `apply_cached_insets`
97 // and dispatches a synthetic `resize`). A `Ref` held across those
98 // calls would let that re-entry find `POPSTATE_GUARDS` already
99 // borrowed and abort the instance, so the list is cloned out and the
100 // guard dropped before a single callback is invoked. A contended
101 // list reports "no guard consumed this event", which lets the
102 // overlay stack handle it — a missed guard costs a native-fullscreen
103 // back gesture, panicking costs the app.
104 let consumed: bool = POPSTATE_GUARDS.with(|guards: &PopstateGuardList| {
105 let snapshot: Vec<PopstateGuardEntry> = match guards.try_borrow() {
106 Ok(list) => list.clone(),
107 Err(_) => Vec::new(),
108 };
109 snapshot.iter().any(|entry: &PopstateGuardEntry| entry.1())
110 });
111 if consumed {
112 WINDOW_EVENT_DEPTH.with(|depth: &Cell<usize>| depth.set(depth.get() - 1));
113 return;
114 }
115 if BACK_PENDING.with(|flag: &Cell<bool>| flag.get()) {
116 BACK_PENDING.with(|flag: &Cell<bool>| flag.set(false));
117 let pending_route: Option<String> =
118 NAVIGATE_AFTER_BACK.with(|cell: &Cell<Option<String>>| cell.take());
119 if let Some(closer) = Self::overlay_stack_pop() {
120 closer();
121 }
122 if let Some(route) = pending_route {
123 Self::navigate(&route);
124 }
125 WINDOW_EVENT_DEPTH.with(|depth: &Cell<usize>| depth.set(depth.get() - 1));
126 return;
127 }
128 if let Some(closer) = Self::overlay_stack_pop() {
129 closer();
130 WINDOW_EVENT_DEPTH.with(|depth: &Cell<usize>| depth.set(depth.get() - 1));
131 return;
132 }
133 WINDOW_EVENT_DEPTH.with(|depth: &Cell<usize>| depth.set(depth.get() - 1));
134 });
135 }
136
137 /// Watches the drawer open signal and scrolls the mobile navigation drawer
138 /// to make the currently active navigation item visible when the drawer opens.
139 ///
140 /// Uses nested `requestAnimationFrame` to defer the scroll until after the
141 /// framework has completed its DOM update cycle. The first `requestAnimationFrame`
142 /// fires after the framework's own `requestAnimationFrame`-based render pass,
143 /// and the second one fires after the browser has laid out the new DOM.
144 /// Locates the scrollable `c-nav-items-scroll` container and the active nav
145 /// item within the drawer, then sets `scrollTop` so the active item appears
146 /// near the vertical center of the container.
147 ///
148 /// # Arguments
149 ///
150 /// - `Signal<bool>` - The reactive signal controlling the mobile nav drawer visibility.
151 pub fn use_scroll_drawer_to_active(drawer_open: Signal<bool>) {
152 watch!(drawer_open, |is_open: bool| {
153 if !is_open {
154 return;
155 }
156 let Some(window_value) = window() else {
157 return;
158 };
159 let outer_raf: Window = window_value.clone();
160 let inner_raf_clone: Window = window_value.clone();
161 let inner_doc_clone: Window = window_value.clone();
162 let outer_closure: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
163 let inner_raf: Window = inner_raf_clone.clone();
164 let inner_doc: Window = inner_doc_clone.clone();
165 let inner_closure: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
166 let Some(document_value) = inner_doc.document() else {
167 return;
168 };
169 let Some(drawer_nav) = document_value
170 .query_selector(DRAWER_NAV_SELECTOR)
171 .ok()
172 .flatten()
173 else {
174 return;
175 };
176 let Some(active_element) = drawer_nav
177 .query_selector(ACTIVE_NAV_ITEM_SELECTOR)
178 .ok()
179 .flatten()
180 else {
181 return;
182 };
183 let active_html_element: HtmlElement = active_element.unchecked_into();
184 let Some(scroll_container) = drawer_nav
185 .query_selector(NAV_ITEMS_SCROLL_SELECTOR)
186 .ok()
187 .flatten()
188 else {
189 return;
190 };
191 let scroll_html_element: HtmlElement = scroll_container.unchecked_into();
192 let active_rect: DomRect = active_html_element.get_bounding_client_rect();
193 let container_rect: DomRect = scroll_html_element.get_bounding_client_rect();
194 let offset_from_container_top: f64 = active_rect.top() - container_rect.top();
195 let current_scroll_top: i32 = scroll_html_element.scroll_top();
196 let container_height: f64 = container_rect.height();
197 let active_height: f64 = active_rect.height();
198 let target_scroll_top: f64 = current_scroll_top as f64
199 + offset_from_container_top
200 - (container_height - active_height) / 2.0;
201 scroll_html_element.set_scroll_top(target_scroll_top.max(0.0) as i32);
202 }));
203 let _: Result<i32, JsValue> =
204 inner_raf.request_animation_frame(inner_closure.as_ref().unchecked_ref());
205 inner_closure.forget();
206 }));
207 let _: Result<i32, JsValue> =
208 outer_raf.request_animation_frame(outer_closure.as_ref().unchecked_ref());
209 outer_closure.forget();
210 });
211 }
212
213 /// Registers a `popstate` guard callback that is invoked on every `popstate`
214 /// event before the overlay stack is consulted.
215 ///
216 /// Guards are called in registration order. The first guard that returns `true`
217 /// consumes the `popstate` event, preventing the overlay stack and normal
218 /// navigation from processing it. This allows external modules (e.g. native
219 /// fullscreen, canvas fullscreen) to intercept the system back gesture without
220 /// registering their own independent `popstate` listener.
221 ///
222 /// Returns a guard ID that can be passed to [`Router::unregister_popstate_guard`] to
223 /// remove the guard when it is no longer needed.
224 ///
225 /// # Arguments
226 ///
227 /// - `Rc<dyn Fn() -> bool>` - The guard callback. Return `true` to consume the
228 /// `popstate` event, `false` to let subsequent guards or the overlay stack
229 /// handle it.
230 ///
231 /// # Returns
232 ///
233 /// - `usize` - A unique guard ID for later unregistration.
234 pub fn register_popstate_guard(guard: Rc<dyn Fn() -> bool>) -> usize {
235 NEXT_POPSTATE_GUARD_ID.with(|counter: &Cell<usize>| {
236 let id: usize = counter.get();
237 counter.set(id + 1);
238 POPSTATE_GUARDS.with(|guards: &PopstateGuardList| {
239 // Best-effort registration. Registration runs during a hook
240 // mount, which can itself be reached from a `popstate` guard
241 // re-entry; a contended list simply leaves the guard
242 // unregistered, and `borrow_mut` would abort the instance.
243 if let Ok(mut entries) = guards.try_borrow_mut() {
244 entries.push((id, guard.clone()));
245 }
246 });
247 id
248 })
249 }
250
251 /// Pushes a browser history entry for an overlay that is about to open.
252 ///
253 /// Call this when an overlay (vconsole panel) opens so that the browser
254 /// back button will close the overlay instead of navigating away.
255 pub fn overlay_push_state() {
256 let Some(window) = window() else {
257 return;
258 };
259 let Ok(history) = window.history() else {
260 return;
261 };
262 let _: Result<(), JsValue> = history.push_state(&JsValue::NULL, "");
263 }
264
265 /// Performs a programmatic `history.back()` to consume the overlay's
266 /// history entry, optionally scheduling a navigation to run after the
267 /// `popstate` event fires.
268 ///
269 /// # Arguments
270 ///
271 /// - `Option<String>` - An optional route to navigate to after the back completes.
272 pub fn overlay_back(navigate_target: Option<String>) {
273 BACK_PENDING.with(|flag: &Cell<bool>| flag.set(true));
274 if let Some(ref route) = navigate_target {
275 NAVIGATE_AFTER_BACK.with(|cell: &Cell<Option<String>>| cell.set(Some(route.clone())));
276 }
277 let Some(window) = window() else {
278 return;
279 };
280 let Ok(history) = window.history() else {
281 return;
282 };
283 let _: Result<(), JsValue> = history.back();
284 }
285
286 /// Pushes an overlay close callback onto the unified `OVERLAY_STACK` and
287 /// pushes a browser history entry so the back button dismisses it.
288 ///
289 /// Call this whenever any overlay (modal, panel, or drawer) opens.
290 ///
291 /// # Arguments
292 ///
293 /// - `Rc<dyn Fn()>` - The callback that closes the overlay (e.g., sets its visibility signal to `false`).
294 pub(crate) fn overlay_stack_push(closer: Rc<dyn Fn()>) {
295 OVERLAY_STACK.with(|stack: &OverlayStack| {
296 // Best-effort push. A contended cell means a re-entrant open is
297 // already being processed by an outer frame that will push its own
298 // entry, so dropping this one costs a single missing overlay-close
299 // wiring rather than aborting the instance.
300 if let Ok(mut entries) = stack.try_borrow_mut() {
301 entries.push(OverlayEntry {
302 closer: closer.clone(),
303 });
304 }
305 });
306 Self::overlay_push_state();
307 }
308
309 /// Pops the most recently opened overlay from the unified `OVERLAY_STACK` and
310 /// returns its close callback, without invoking it.
311 ///
312 /// Also synchronizes the `MODAL_STACK` by removing the matching entry if the
313 /// popped overlay is a modal.
314 ///
315 /// # Returns
316 ///
317 /// - `Option<Rc<dyn Fn()>>` - The topmost overlay's close callback, or `None` if no overlay is open.
318 pub(crate) fn overlay_stack_pop() -> Option<Rc<dyn Fn()>> {
319 let closer: Option<Rc<dyn Fn()>> = OVERLAY_STACK.with(|stack: &OverlayStack| {
320 // Best-effort pop: returning `None` under contention lets the
321 // caller fall through to normal navigation, which is a recoverable
322 // outcome. `borrow_mut` here would abort the instance instead.
323 match stack.try_borrow_mut() {
324 Ok(mut entries) => entries.pop().map(|entry: OverlayEntry| entry.closer),
325 Err(_) => None,
326 }
327 });
328 if let Some(ref closer_ref) = closer {
329 MODAL_STACK.with(|stack: &ModalStack| {
330 // The matching entry is dropped on contention: a stale modal
331 // entry is inert (it only affects identity lookup for an
332 // already-closed modal), whereas panicking kills the app.
333 let Ok(mut entries) = stack.try_borrow_mut() else {
334 return;
335 };
336 if let Some(index) = entries
337 .iter()
338 .rposition(|(_, closer): &ModalStackEntry| Rc::ptr_eq(closer, closer_ref))
339 {
340 entries.remove(index);
341 }
342 });
343 }
344 closer
345 }
346
347 /// Closes the most recently opened overlay via the UI and consumes one
348 /// browser history entry.
349 ///
350 /// Triggers `overlay_back`, which sets the `BACK_PENDING` flag and calls
351 /// `history.back()`. The resulting `popstate` handler invocation pops the
352 /// top entry from `OVERLAY_STACK` and runs its close callback, keeping the
353 /// history count in sync. Use this when the user dismisses an overlay
354 /// through a close button, overlay click, or confirm/cancel action.
355 ///
356 /// Note: this method does **not** pop `OVERLAY_STACK` itself — the popstate
357 /// handler is the single owner of the pop, so UI dismissal and the system
358 /// back gesture share one consistent path.
359 pub fn overlay_stack_close() {
360 Self::overlay_back(None);
361 }
362
363 /// Registers an open modal by pushing it onto the global modal stack and
364 /// adding a browser history entry, enabling nested modals.
365 ///
366 /// The stack is ordered with the most recently opened modal on top. When the
367 /// user triggers a system back gesture (or presses the browser back button),
368 /// the `popstate` handler pops the topmost entry from `OVERLAY_STACK` and
369 /// invokes its close callback, so the most recently opened overlay is dismissed
370 /// first instead of navigating to the previous page.
371 ///
372 /// If the given visibility signal is already on the stack, this is a no-op so
373 /// that re-opening an already-open modal does not create duplicate stack or
374 /// history entries.
375 ///
376 /// # Arguments
377 ///
378 /// - `Signal<bool>` - The modal's visibility signal, used as a stable identity for later removal.
379 /// - `Rc<dyn Fn()>` - The callback that closes the modal (e.g., sets the visibility signal to `false`).
380 pub fn modal_push(visible: Signal<bool>, closer: Rc<dyn Fn()>) {
381 let already_open: bool = MODAL_STACK.with(|stack: &ModalStack| {
382 // Cloned out so the identity scan runs with no guard held: the push
383 // below re-borrows, and a scan-in-place would also keep the guard
384 // alive across the `closer.clone()` on the next statement.
385 match stack.try_borrow() {
386 Ok(entries) => entries
387 .iter()
388 .any(|(signal, _): &ModalStackEntry| *signal == visible),
389 Err(_) => false,
390 }
391 });
392 if already_open {
393 return;
394 }
395 MODAL_STACK.with(|stack: &ModalStack| {
396 // Best-effort push; the `overlay_stack_push` below still runs and
397 // still pushes the history entry, so a contended modal stack costs
398 // identity tracking for this modal, not its dismissal.
399 if let Ok(mut entries) = stack.try_borrow_mut() {
400 entries.push((visible, closer.clone()));
401 }
402 });
403 Self::overlay_stack_push(closer);
404 }
405
406 /// Closes a modal that was opened via [`Router::modal_push`] when the user dismisses
407 /// it through the UI (close button, overlay click, confirm/cancel action)
408 /// rather than the system back gesture.
409 ///
410 /// Removes the entry matching the given visibility signal from the global
411 /// stack (by identity, not necessarily the top, so nested modals stay
412 /// consistent) and consumes one matching browser history entry via
413 /// `overlay_stack_close`, keeping the history count in sync so a subsequent back
414 /// gesture behaves correctly.
415 ///
416 /// # Arguments
417 ///
418 /// - `Signal<bool>` - The visibility signal identifying the modal to remove.
419 pub fn modal_close_via_ui(visible: Signal<bool>) {
420 let removed: bool = MODAL_STACK.with(|stack: &ModalStack| {
421 // `removed == false` under contention means the history entry below
422 // is not consumed, so the back gesture is left to the overlay stack;
423 // a stale entry is inert and `borrow_mut` would abort the instance.
424 let Ok(mut entries) = stack.try_borrow_mut() else {
425 return false;
426 };
427 if let Some(index) = entries
428 .iter()
429 .rposition(|(signal, _): &ModalStackEntry| *signal == visible)
430 {
431 entries.remove(index);
432 true
433 } else {
434 false
435 }
436 });
437 if removed {
438 Self::overlay_stack_close();
439 }
440 }
441
442 /// Opens the given URL in the system default browser using `window.open`
443 /// with the `_system` target name.
444 ///
445 /// In a bridge WebView environment, the `_system` target instructs the
446 /// shell opener plugin to delegate the URL to the operating system's
447 /// default browser. In a regular browser, `window.open` falls back to
448 /// opening a new tab or window as usual.
449 ///
450 /// # Arguments
451 ///
452 /// - `U` - The URL to open.
453 pub fn open_system_browser<U>(url: U)
454 where
455 U: AsRef<str>,
456 {
457 let Some(window_value) = window() else {
458 return;
459 };
460 if let Ok(open_fn) = Reflect::get(&window_value, &JsValue::from_str(ROUTER_WINDOW_OPEN_KEY))
461 .and_then(|value: JsValue| value.dyn_into::<Function>())
462 {
463 let _: Result<JsValue, JsValue> = open_fn.call2(
464 &window_value,
465 &JsValue::from_str(url.as_ref()),
466 &JsValue::from_str(SYSTEM_BROWSER_TARGET),
467 );
468 }
469 }
470
471 /// Creates a click event handler for external `<a>` links that opens
472 /// the URL in the system default browser.
473 ///
474 /// Calls `event.prevent_default()` to suppress the `<a>` element's
475 /// default navigation (which would open inside the WebView), then
476 /// delegates to `open_system_browser` so the URL is handled by the
477 /// operating system's default browser.
478 ///
479 /// # Arguments
480 ///
481 /// - `U` - The external URL to open on click.
482 ///
483 /// # Returns
484 ///
485 /// - `NativeEventHandler` - An event handler for click events.
486 pub fn external_link_handler<U>(url: U) -> NativeEventHandler
487 where
488 U: AsRef<str>,
489 {
490 let url_string: String = url.as_ref().to_string();
491 NativeEventHandler::create(ROUTER_EXTERNAL_LINK_EVENT_TYPE, move |event: Event| {
492 event.prevent_default();
493 Self::open_system_browser(&url_string);
494 })
495 }
496
497 /// Helper to close the drawer and navigate.
498 ///
499 /// Used internally by mobile nav items.
500 /// Closes the drawer via overlay back and schedules navigation to the target route
501 /// after the popstate event is processed.
502 ///
503 /// # Arguments
504 ///
505 /// - `Signal<bool>` - The drawer open signal.
506 /// - `T` - The target route.
507 pub fn close_drawer_and_navigate<T>(_drawer_open: Signal<bool>, target: T)
508 where
509 T: AsRef<str>,
510 {
511 Self::overlay_back(Some(target.as_ref().to_string()));
512 }
513}