leptos_use/
use_window_focus.rs

1#![cfg_attr(feature = "ssr", allow(unused_variables, unused_imports))]
2
3use crate::use_event_listener;
4use cfg_if::cfg_if;
5use leptos::ev::{blur, focus};
6use leptos::prelude::*;
7
8/// Reactively track window focus
9/// with `window.onfocus` and `window.onblur` events.
10///
11/// ## Demo
12///
13/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_window_focus)
14///
15/// ## Usage
16///
17/// ```
18/// # use leptos::prelude::*;
19/// # use leptos_use::use_window_focus;
20/// #
21/// # #[component]
22/// # fn Demo() -> impl IntoView {
23/// let focused = use_window_focus();
24/// #
25/// # view! { }
26/// # }
27/// ```
28///
29/// ## Server-Side Rendering
30///
31/// On the server this returns a `Signal` that is always `true`.
32pub fn use_window_focus() -> Signal<bool> {
33    cfg_if! { if #[cfg(feature = "ssr")] {
34        let initial_focus = true;
35    } else {
36        let initial_focus = document().has_focus().unwrap_or_default();
37    }}
38
39    let (focused, set_focused) = signal(initial_focus);
40
41    cfg_if! { if #[cfg(not(feature = "ssr"))] {
42        let _ = use_event_listener(window(), blur, move |_| set_focused.set(false));
43        let _ = use_event_listener(window(), focus, move |_| set_focused.set(true));
44    }}
45
46    focused.into()
47}