Lightpanda: the headless browser designed for AI and automation
webapi: implement document.hasFocus()
Karl Seguin19caa808a3d5
diff --git a/src/browser/tests/frames/cross_realm_focus.html b/src/browser/tests/frames/cross_realm_focus.htmlindex 992b03dbe..1c0108f49 100644--- a/src/browser/tests/frames/cross_realm_focus.html+++ b/src/browser/tests/frames/cross_realm_focus.html@@ -93,6 +93,36 @@ Chrome to cross-check.});</script>+<script id="has_focus_follows_focus_chain">+ testing.onload(() => {+ const idf = document.getElementById('idf');+ const idoc = idf.contentDocument;+ const inp = idoc.getElementById('fin');+ const pout = document.getElementById('pout');++ // The top-level document always has focus; an iframe's only while its+ // <iframe> is the parent's focused area.+ pout.focus();+ testing.expectTrue(document.hasFocus());+ testing.expectFalse(idoc.hasFocus());++ inp.focus();+ testing.expectTrue(document.hasFocus());+ testing.expectTrue(idoc.hasFocus());++ // Blurring inside the iframe leaves focus on its viewport.+ inp.blur();+ testing.expectTrue(idoc.hasFocus());++ pout.focus();+ testing.expectFalse(idoc.hasFocus());+ pout.blur();++ testing.expectFalse(new DOMParser().parseFromString('', 'text/html').hasFocus());+ testing.expectFalse(document.implementation.createHTMLDocument('').hasFocus());+ });+</script>+<script id="frameless_document_is_not_focusable">testing.onload(() => {const doc = new DOMParser().parseFromString('<input id=x>', 'text/html');diff --git a/src/browser/webapi/Document.zig b/src/browser/webapi/Document.zigindex 3c98b5377..b0769a655 100644--- a/src/browser/webapi/Document.zig+++ b/src/browser/webapi/Document.zig@@ -1381,9 +1381,22 @@ fn exitFullscreen(_: *Document, frame: *Frame) js.Promise {return frame.js.local.?.rejectPromise(.{ .type_error = "Document not in fullscreen" });}-pub fn hasFocus(_: *Document) bool {- log.debug(.not_implemented, "Document.hasFocus", .{});- return true;+pub fn hasFocus(self: *Document) bool {+ var top = self._frame orelse return false;+ while (top.parent) |parent| {+ top = parent;+ }++ var candidate = top;+ while (true) {+ if (candidate.document == self) {+ return true;+ }+ const active = candidate.document._active_element orelse return false;+ const iframe = active.is(Element.Html.IFrame) orelse return false;+ const window = iframe._window orelse return false;+ candidate = window._frame;+ }}fn setAdoptedStyleSheets(self: *Document, sheets: js.Object) !void {