Skip to content

Truly independent web browser

LibWeb: Dispatch focus events when system focus changes

Callum Lawa57a097bc1f9
diff --git a/Libraries/LibWeb/HTML/Focus.cpp b/Libraries/LibWeb/HTML/Focus.cpp
index be4d6b0d834..92533b40c92 100644
--- a/Libraries/LibWeb/HTML/Focus.cpp
+++ b/Libraries/LibWeb/HTML/Focus.cpp
@@ -67,6 +67,36 @@ static void fire_a_focus_event(GC::Ptr<DOM::EventTarget> focus_event_target, GC:
focus_event_target->dispatch_event(focus_event);
}
+void dispatch_system_focus_events(DOM::Document& document, bool has_focus)
+{
+ TemporaryExecutionContext execution_context { document.relevant_settings_object() };
+
+ GC::Ptr<DOM::Element> element = as_if<DOM::Element>(document.focused_area().ptr());
+
+ auto dispatch_element_events = [&] {
+ if (!element || document.focused_area() != element)
+ return;
+
+ fire_a_focus_event(element, nullptr, has_focus ? EventNames::focus : EventNames::blur, false);
+
+ if (document.focused_area() == element && document.page().client().has_focus() == has_focus)
+ fire_a_focus_event(element, nullptr, has_focus ? EventNames::focusin : EventNames::focusout, true);
+ };
+
+ if (!has_focus)
+ dispatch_element_events();
+
+ if (document.page().client().has_focus() != has_focus)
+ return;
+
+ fire_a_focus_event(document.window(), nullptr, has_focus ? EventNames::focus : EventNames::blur, false);
+
+ auto navigable = document.page().hosted_focused_navigable();
+
+ if (has_focus && document.page().client().has_focus() && navigable && navigable->active_document().ptr() == &document)
+ dispatch_element_events();
+}
+
static void designate_document_viewport_as_focused_area(DOM::Document& document)
{
if (document.focused_area() == nullptr)
diff --git a/Libraries/LibWeb/HTML/Focus.h b/Libraries/LibWeb/HTML/Focus.h
index 6205d9d6422..e9a44d9cd8a 100644
--- a/Libraries/LibWeb/HTML/Focus.h
+++ b/Libraries/LibWeb/HTML/Focus.h
@@ -22,6 +22,7 @@ enum class ScrollIntoView : u8 {
};
WEB_API Vector<GC::Root<DOM::Node>> focus_chain(GC::Ptr<DOM::Node> subject);
+void dispatch_system_focus_events(DOM::Document&, bool has_focus);
WEB_API void run_focus_update_steps(Vector<GC::Root<DOM::Node>> old_chain, Vector<GC::Root<DOM::Node>> new_chain, GC::Ptr<DOM::Node> new_focus_target, GC::Ptr<NavigableContainer> explicitly_focused_container = nullptr);
WEB_API void run_focusing_steps(GC::Ptr<DOM::Node> new_focus_target, GC::Ptr<DOM::Node> fallback_target = nullptr, FocusTrigger focus_trigger = FocusTrigger::Other, ScrollIntoView = ScrollIntoView::Yes, Optional<bool> focus_visible = {});
WEB_API void run_unfocusing_steps(GC::Ptr<DOM::Node> old_focus_target);
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index 697d66d98a8..f4026f81a43 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -3237,8 +3237,9 @@ void Internals::set_preferred_color_scheme(Utf16String const& color_scheme)
void Internals::set_page_focus(bool has_focus)
{
- page().client().set_has_focus(has_focus);
+ // Publish before dispatching events so a handler's later focus change supersedes this one.
page().client().page_did_request_set_system_focus(has_focus);
+ page().client().set_has_focus(has_focus);
}
void Internals::set_system_visibility_state(Utf16String const& state)
diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cpp
index 701a42bc248..a0cf61ade39 100644
--- a/Libraries/LibWeb/Page/Page.cpp
+++ b/Libraries/LibWeb/Page/Page.cpp
@@ -232,6 +232,11 @@ void Page::system_focus_changed()
media_devices->system_focus_changed();
}
}
+
+ if (auto focused_navigable = hosted_focused_navigable()) {
+ if (auto focused_document = focused_navigable->active_document())
+ HTML::dispatch_system_focus_events(*focused_document, client().has_focus());
+ }
}
void Page::set_focused_navigable(HTML::Navigable& navigable)
diff --git a/Tests/LibWeb/Text/expected/HTML/system-focus-events.txt b/Tests/LibWeb/Text/expected/HTML/system-focus-events.txt
new file mode 100644
index 00000000000..b6bb912ed30
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/system-focus-events.txt
@@ -0,0 +1,8 @@
+System focus loss with the top-level input focused: top input.blur, top input.focusout, top window.blur; active focus chain preserved=true
+Repeated system focus loss with the top-level input focused: none; active focus chain preserved=true
+System focus gain with the top-level input focused: top window.focus, top input.focus, top input.focusin; active focus chain preserved=true
+Repeated system focus gain with the top-level input focused: none; active focus chain preserved=true
+System focus loss with the iframe input focused: iframe input.blur, iframe input.focusout, iframe window.blur; active focus chain preserved=true
+Repeated system focus loss with the iframe input focused: none; active focus chain preserved=true
+System focus gain with the iframe input focused: iframe window.focus, iframe input.focus, iframe input.focusin; active focus chain preserved=true
+Repeated system focus gain with the iframe input focused: none; active focus chain preserved=true
diff --git a/Tests/LibWeb/Text/expected/HTML/system-focus-reentrant-handlers.txt b/Tests/LibWeb/Text/expected/HTML/system-focus-reentrant-handlers.txt
new file mode 100644
index 00000000000..3662a3f784d
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/system-focus-reentrant-handlers.txt
@@ -0,0 +1,2 @@
+Window blur handler restores system focus: window.blur, window.focus, original.focus, original.focusin; original input still active=true; document.hasFocus()=true
+Window focus handler redirects focus without duplicate events: window.focus, redirected.focus, redirected.focusin; redirected input active=true
diff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/system-focus-events.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/system-focus-events.txt
new file mode 100644
index 00000000000..87dfcd17f44
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/system-focus-events.txt
@@ -0,0 +1,2 @@
+System focus loss with an isolated iframe focused: input.blur, input.focusout, window.blur; active focus chain preserved=true; ancestor and sibling window events=none
+System focus gain with an isolated iframe focused: window.focus, input.focus, input.focusin; active focus chain preserved=true; ancestor and sibling window events=none
diff --git a/Tests/LibWeb/Text/input/HTML/system-focus-events.html b/Tests/LibWeb/Text/input/HTML/system-focus-events.html
new file mode 100644
index 00000000000..bfe528fd247
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/system-focus-events.html
@@ -0,0 +1,47 @@
+<!doctype html>
+<script src="../include.js"></script>
+<input id="top-input" />
+<iframe id="frame" srcdoc="<input>"></iframe>
+<script>
+ promiseTest(async () => {
+ await new Promise(resolve => window.addEventListener("load", resolve, { once: true }));
+
+ const frame = document.getElementById("frame");
+ const topInput = document.getElementById("top-input");
+ const frameInput = frame.contentDocument.querySelector("input");
+ const events = [];
+ for (const [name, target] of [
+ ["top input", topInput],
+ ["iframe input", frameInput],
+ ["top window", window],
+ ["iframe window", frame.contentWindow],
+ ]) {
+ for (const type of ["blur", "focusout", "focus", "focusin"])
+ target.addEventListener(type, event => {
+ if (event.target === target) events.push(`${name}.${type}`);
+ });
+ }
+
+ for (const [name, input] of [
+ ["top-level", topInput],
+ ["iframe", frameInput],
+ ]) {
+ input.focus();
+ events.length = 0;
+ for (const [phase, focused] of [
+ ["System focus loss", false],
+ ["Repeated system focus loss", false],
+ ["System focus gain", true],
+ ["Repeated system focus gain", true],
+ ]) {
+ internals.setPageFocus(focused);
+ const active =
+ input.ownerDocument.activeElement === input &&
+ (input === topInput || document.activeElement === frame);
+ println(
+ `${phase} with the ${name} input focused: ${events.splice(0).join(", ") || "none"}; active focus chain preserved=${active}`
+ );
+ }
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/HTML/system-focus-reentrant-handlers.html b/Tests/LibWeb/Text/input/HTML/system-focus-reentrant-handlers.html
new file mode 100644
index 00000000000..7a186dc2018
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/system-focus-reentrant-handlers.html
@@ -0,0 +1,30 @@
+<!doctype html>
+<script src="../include.js"></script>
+<input id="original" />
+<input id="redirected" />
+<script>
+ test(() => {
+ const originalInput = document.getElementById("original");
+ const redirectedInput = document.getElementById("redirected");
+ const events = [];
+ for (const type of ["focus", "focusin"])
+ document.addEventListener(type, event => events.push(`${event.target.id}.${type}`), true);
+ for (const type of ["blur", "focus"]) window.addEventListener(type, () => events.push(`window.${type}`));
+
+ originalInput.focus();
+ events.length = 0;
+ window.addEventListener("blur", () => internals.setPageFocus(true), { once: true });
+ internals.setPageFocus(false);
+ println(
+ `Window blur handler restores system focus: ${events.splice(0).join(", ")}; original input still active=${document.activeElement === originalInput}; document.hasFocus()=${document.hasFocus()}`
+ );
+
+ internals.setPageFocus(false);
+ events.length = 0;
+ window.addEventListener("focus", () => redirectedInput.focus(), { once: true });
+ internals.setPageFocus(true);
+ println(
+ `Window focus handler redirects focus without duplicate events: ${events.join(", ")}; redirected input active=${document.activeElement === redirectedInput}`
+ );
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/system-focus-events.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/system-focus-events.html
new file mode 100644
index 00000000000..145ad516237
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/system-focus-events.html
@@ -0,0 +1,63 @@
+<!doctype html>
+<script src="../../include.js"></script>
+<iframe id="child"></iframe>
+<iframe id="sibling"></iframe>
+<script>
+ promiseTest(async () => {
+ const remoteUrl = new URL(
+ await httpTestServer().createEcho("GET", "/system-focus-events", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><input id="input"><script>
+ const events = [];
+ for (const type of ["blur", "focusout", "focus", "focusin"])
+ addEventListener(type, event => {
+ events.push((event.target === window ? "window" : "input") + "." + type);
+ }, true);
+ addEventListener("message", event => {
+ if (event.data === "focus")
+ input.focus();
+ parent.postMessage({ events: events.splice(0), active: document.activeElement === input }, "*");
+ });
+ parent.postMessage("ready", "*");
+ <\/script>`,
+ })
+ );
+ remoteUrl.hostname = uniqueLocalhostHostname("system-focus-events");
+
+ const nextMessage = () =>
+ new Promise(resolve => window.addEventListener("message", event => resolve(event.data), { once: true }));
+
+ function ask(child, message) {
+ const reply = nextMessage();
+ child.contentWindow.postMessage(message, "*");
+ return reply;
+ }
+
+ const child = document.getElementById("child");
+ const sibling = document.getElementById("sibling");
+ for (const frame of [child, sibling]) {
+ const ready = nextMessage();
+ frame.src = remoteUrl;
+ await ready;
+ }
+ const otherEvents = [];
+ for (const type of ["blur", "focus"]) window.addEventListener(type, () => otherEvents.push(`top.${type}`));
+
+ await ask(child, "focus");
+ otherEvents.length = 0;
+ for (const [phase, focused] of [
+ ["System focus loss", false],
+ ["System focus gain", true],
+ ]) {
+ internals.setPageFocus(focused);
+ const report = await ask(child, "report");
+ const siblingReport = await ask(sibling, "report");
+ const active = document.activeElement === child && report.active;
+ const other = [...otherEvents.splice(0), ...siblingReport.events].join(", ") || "none";
+ println(
+ `${phase} with an isolated iframe focused: ${report.events.join(", ") || "none"}; active focus chain preserved=${active}; ancestor and sibling window events=${other}`
+ );
+ }
+ });
+</script>