Skip to content

Commit

Permalink
docs for focused_element + add has_focus helper
Browse files Browse the repository at this point in the history
  • Loading branch information
jprochazk committed May 29, 2024
1 parent 0d80de4 commit 0b9911b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
22 changes: 19 additions & 3 deletions crates/eframe/src/web/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,27 @@ pub(crate) fn string_from_js_value(value: &JsValue) -> String {
value.as_string().unwrap_or_else(|| format!("{value:#?}"))
}

pub(crate) fn focused_element() -> Option<web_sys::HtmlElement> {
/// Returns the `Element` with active focus.
///
/// Elements can only be focused if they are:
/// - `<a>`/`<area>` with an `href` attribute
/// - `<input>`/`<select>`/`<textarea>`/`<button>` which aren't `disabled`
/// - any other element with a `tabindex` attribute
pub(crate) fn focused_element() -> Option<web_sys::Element> {
web_sys::window()?
.document()?
.active_element()
.and_then(|v| v.dyn_into().ok())
.active_element()?
.dyn_into()
.ok()
}

pub(crate) fn has_focus<T: Clone + JsCast>(element: &T) -> bool {
fn inner<T: Clone + JsCast>(element: &T) -> Option<bool> {
let element = element.dyn_ref::<web_sys::Element>()?;
let focused_element = focused_element()?;
Some(element == &focused_element)
}
inner(element).unwrap_or(false)
}

/// Current time in seconds (since undefined point in time).
Expand Down
3 changes: 1 addition & 2 deletions crates/eframe/src/web/text_agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,7 @@ impl TextAgent {
}

pub fn has_focus(&self) -> bool {
let active_element = super::focused_element();
self.input.clone().dyn_into().ok() == active_element
super::has_focus(&self.input)
}

fn focus(&self) {
Expand Down

0 comments on commit 0b9911b

Please sign in to comment.