1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#![cfg_attr(feature = "ssr", allow(unused_variables, unused_imports))]

use crate::{use_document, use_event_listener_with_options, use_window, UseEventListenerOptions};
use leptos::ev::{blur, focus};
use leptos::html::{AnyElement, ToHtmlElement};
use leptos::*;

/// Reactive `document.activeElement`
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_active_element)
///
/// ## Usage
///
/// ```
/// # use leptos::*;
/// # use leptos::logging::log;
/// use leptos_use::use_active_element;
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let active_element = use_active_element();
///
/// create_effect(move |_| {
///     log!("focus changed to {:?}", active_element.get());
/// });
/// #
/// # view! { }
/// # }
/// ```
///
/// ## Server-Side Rendering
///
/// On the server this returns a `Signal` that always contains the value `None`.
pub fn use_active_element() -> Signal<Option<HtmlElement<AnyElement>>> {
    let get_active_element = move || {
        use_document()
            .active_element()
            .map(|el| el.to_leptos_element())
    };

    let (active_element, set_active_element) = create_signal(get_active_element());

    let listener_options = UseEventListenerOptions::default().capture(true);

    let _ = use_event_listener_with_options(
        use_window(),
        blur,
        move |event| {
            if event.related_target().is_some() {
                return;
            }

            set_active_element.update(|el| *el = get_active_element());
        },
        listener_options,
    );

    let _ = use_event_listener_with_options(
        use_window(),
        focus,
        move |_| {
            set_active_element.update(|el| *el = get_active_element());
        },
        listener_options,
    );

    active_element.into()
}