Lightpanda: the headless browser designed for AI and automation
webapi: improve dialog conformance
Karl Seguinfbb2b52b3098
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex 8d8bc0406..8515463bd 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -2665,7 +2665,7 @@ pub const QueuedEvent = struct {element: *Element.Html,generation: u32 = 0, // Image/Link request generation- pub const Kind = enum { load, @"error", select, selectionchange };+ pub const Kind = enum { load, @"error", select, selectionchange, close };};pub fn queueLoad(self: *Frame, html: *Element.Html) !void {@@ -2966,6 +2966,7 @@ fn dispatchQueuedEvents(self: *Frame) !void {}try self.fireElementEvent(element, .wrap("selectionchange"), .{ .bubbles = true });},+ .close => try self.fireElementEvent(element, comptime .wrap("close"), .{}),}}@@ -4266,15 +4267,9 @@ pub fn submitForm(self: *Frame, submitter_: ?*Element, form_: ?*Element.Html.For// both reloads the page and leaves the dialog open forever.// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#form-submission-algorithmif (std.mem.eql(u8, method, "dialog")) {- // A submit button always has a value (empty when unset); with no- // submitter at all the dialog's existing returnValue is left untouched.- const result: ?[]const u8 = if (submit_button) |s| blk: {- if (s.is(Element.Html.Form.Input)) |input| {- break :blk input.getValue();- }- // if not an Input, it has to be a Button (checked above by isSubmitButton)- break :blk s.as(Element.Html.Form.Button).getValue();- } else null;+ // The submitter's optional value: its value attribute, else null. A+ // null result leaves the dialog's returnValue untouched.+ const result: ?[]const u8 = if (submit_button) |s| s.getAttributeSafe(comptime .wrap("value")) else null;var ancestor: ?*Element = form_element;while (ancestor) |el| : (ancestor = el.parentElement()) {diff --git a/src/browser/tests/element/html/dialog.html b/src/browser/tests/element/html/dialog.htmlindex 59aecd4db..27dab8331 100644--- a/src/browser/tests/element/html/dialog.html+++ b/src/browser/tests/element/html/dialog.html@@ -1,4 +1,5 @@<!DOCTYPE html>+<meta name=lp-mode content=test><script src="../../testing.js"></script><!-- Dialog elements -->@@ -50,22 +51,21 @@dialog.returnValue = 'success'testing.expectEqual('success', dialog.returnValue)- testing.expectEqual('success', dialog.getAttribute('returnvalue'))dialog.returnValue = 'cancel'testing.expectEqual('cancel', dialog.returnValue)- testing.expectEqual('cancel', dialog.getAttribute('returnvalue'))}</script>-<script id="returnValue_reflects_to_attribute">+<script id="returnValue_is_not_an_attribute">{const dialog = document.createElement('dialog')+ dialog.returnValue = 'confirmed'testing.expectEqual(null, dialog.getAttribute('returnvalue'))- dialog.returnValue = 'confirmed'- testing.expectEqual('confirmed', dialog.getAttribute('returnvalue'))- testing.expectTrue(dialog.outerHTML.includes('returnvalue="confirmed"'))+ dialog.setAttribute('returnvalue', 'other')+ testing.expectEqual('confirmed', dialog.returnValue)+ testing.expectEqual('', dialog.cloneNode().returnValue)}</script>@@ -102,11 +102,50 @@<script id="showModal_sets_open">{const dialog = document.createElement('dialog')+ document.body.append(dialog)testing.expectEqual(false, dialog.open)dialog.showModal()testing.expectEqual(true, dialog.open)testing.expectEqual('', dialog.getAttribute('open'))++ // already modal: a no-op+ dialog.showModal()+ testing.expectEqual(true, dialog.open)+ dialog.close()+ dialog.remove()+ }+</script>++<script id="showModal_throws_when_disconnected">+ {+ const dialog = document.createElement('dialog')+ testing.expectError('InvalidStateError', () => dialog.showModal())+ testing.expectEqual(false, dialog.open)+ }+</script>++<script id="showModal_throws_when_open_non_modal">+ {+ const dialog = document.createElement('dialog')+ document.body.append(dialog)+ dialog.show()+ testing.expectError('InvalidStateError', () => dialog.showModal())+ dialog.close()+ dialog.remove()+ }+</script>++<script id="showModal_throws_when_popover_showing">+ {+ const dialog = document.createElement('dialog')+ dialog.popover = 'manual'+ document.body.append(dialog)+ dialog.showPopover()+ testing.expectError('InvalidStateError', () => dialog.showModal())+ testing.expectEqual(false, dialog.open)+ dialog.hidePopover()+ dialog.remove()}</script>@@ -149,7 +188,6 @@dialog.close('confirmed')testing.expectEqual('confirmed', dialog.returnValue)- testing.expectEqual('confirmed', dialog.getAttribute('returnvalue'))}</script>@@ -180,9 +218,13 @@document.addEventListener('close', () => { bubbled = true })dialog.close('done')- testing.expectEqual(1, fired)- testing.expectEqual(false, bubbled)- testing.expectEqual(false, cancelable)+ // queued, not fired synchronously+ testing.expectEqual(0, fired)+ testing.onload(() => {+ testing.expectEqual(1, fired)+ testing.expectEqual(false, bubbled)+ testing.expectEqual(false, cancelable)+ })}</script>@@ -214,13 +256,13 @@$('#b_submit').click()- testing.expectEqual(1, fired)testing.expectEqual(false, dialog.open)testing.expectEqual('confirm', dialog.returnValue)+ testing.onload(() => testing.expectEqual(1, fired))}</script>-<script id="dialog_method_uses_empty_value_when_submitter_has_none">+<script id="dialog_method_keeps_returnValue_when_submitter_has_no_value">{document.body.insertAdjacentHTML('beforeend','<dialog id="d_novalue"><form method="dialog">' +@@ -233,8 +275,9 @@$('#b_novalue').click()+ // no value attribute: the result is null, which keeps returnValuetesting.expectEqual(false, dialog.open)- testing.expectEqual('', dialog.returnValue)+ testing.expectEqual('preset', dialog.returnValue)}</script>diff --git a/src/browser/tests/element/html/dialog_close_request.html b/src/browser/tests/element/html/dialog_close_request.htmlindex e3bc55aaa..2396a1fee 100644--- a/src/browser/tests/element/html/dialog_close_request.html+++ b/src/browser/tests/element/html/dialog_close_request.html@@ -16,6 +16,10 @@for (const d of [A, B]) {for (const type of ['cancel', 'close']) {d.addEventListener(type, (e) => {+ if (type === 'close' && d.resetClose) {+ d.resetClose = false;+ return;+ }// A trailing "!" marks an event that was not cancelable.log.push(`${type}@${d.id}${e.cancelable ? '' : '!'}`);if (type === 'cancel' && preventCancel) e.preventDefault();@@ -29,6 +33,8 @@window.reset = () => {for (const d of [A, B]) {if (!d.isConnected) document.body.append(d);+ // close is queued: skip the one this queues, it fires in a later step+ if (d.open) d.resetClose = true;d.close();d.returnValue = '';}diff --git a/src/browser/webapi/element/html/Dialog.zig b/src/browser/webapi/element/html/Dialog.zigindex 2f952d904..a90d3c0d8 100644--- a/src/browser/webapi/element/html/Dialog.zig+++ b/src/browser/webapi/element/html/Dialog.zig@@ -16,6 +16,7 @@// You should have received a copy of the GNU Affero General Public License// along with this program. If not, see <https://www.gnu.org/licenses/>.+const std = @import("std");const lp = @import("lightpanda");const js = @import("../../../js/js.zig");@@ -25,6 +26,7 @@ const Factory = @import("../../../Factory.zig");const Event = @import("../../Event.zig");const Node = @import("../../Node.zig");const Element = @import("../../Element.zig");+const popover = @import("../popover.zig");const HtmlElement = @import("../Html.zig");@@ -33,7 +35,8 @@ const Dialog = @This();pub const Proto = HtmlElement;-_pad: bool = false,+// internal state, not reflected to an attribute+_return_value: []const u8 = "",_proto_canary: if (lp.IS_DEBUG) *HtmlElement else void = undefined,pub fn asElement(self: *Dialog) *Element {@@ -55,19 +58,27 @@ pub fn show(self: *Dialog, frame: *Frame) !void {}/// https://html.spec.whatwg.org/multipage/interactive-elements.html#dom-dialog-showmodal-/// Throws InvalidStateError if [open] is already set. Sets [open] otherwise./// Focus trap, backdrop, and top-layer placement are no-ops — Lightpanda has/// no layout/compositor; [open] reflecting through to selectors is what/// downstream consumers rely on.fn showModal(self: *Dialog, frame: *Frame) !void {- if (self.getOpen()) return error.InvalidStateError;- try self.asElement().setAttributeSafe(comptime .wrap("open"), .wrap(""), frame);- // Only a connected dialog joins its document's top layer. That's the- // dialog's own document, which isn't the caller's for a cross-frame call.const node = self.asNode();- if (node.isConnected()) {- try node.getDocument(frame)._modal_dialogs.append(frame.page_arena, self);+ // The dialog's own document, which isn't the caller's for a cross-frame call.+ const modal_dialogs = &node.getDocument(frame)._modal_dialogs;+ if (self.getOpen()) {+ if (std.mem.findScalar(*Dialog, modal_dialogs.items, self) != null) {+ // no-op if already opend+ return;+ }+ // error if opened non-modally+ return error.InvalidStateError;}+ if (node.isConnected() == false or popover.isOpen(self.asElement(), frame)) {+ // invalid if disconnected or showing a popover+ return error.InvalidStateError;+ }+ try self.asElement().setAttributeSafe(comptime .wrap("open"), .wrap(""), frame);+ try modal_dialogs.append(frame.page_arena, self);}/// https://html.spec.whatwg.org/multipage/interactive-elements.html#close-requests@@ -101,15 +112,25 @@ fn removeModal(element: *Element, frame: *Frame) void {/// https://html.spec.whatwg.org/multipage/interactive-elements.html#dom-dialog-close/// If [open] is unset, return. Otherwise remove [open], optionally update-/// returnValue, and fire a `close` event (non-bubbling, non-cancelable).+/// returnValue, and queue a `close` event (non-bubbling, non-cancelable).pub fn close(self: *Dialog, return_value: ?[]const u8, frame: *Frame) !void {if (!self.getOpen()) return;try self.asElement().removeAttribute(comptime .wrap("open"), frame);if (return_value) |v| {- try self.asElement().setAttributeSafe(comptime .wrap("returnvalue"), .wrap(v), frame);+ try self.setReturnValue(v, frame);+ }+ try frame.queueElementEvent(Factory.protoOf(self), .close);+}++pub fn getReturnValue(self: *const Dialog) []const u8 {+ return self._return_value;+}++pub fn setReturnValue(self: *Dialog, value: []const u8, frame: *Frame) !void {+ if (std.mem.eql(u8, self._return_value, value)) {+ return;}- const event = try Event.init("close", .{ .bubbles = false, .cancelable = false }, frame.page);- try frame._event_manager.dispatch(self.asElement().asEventTarget(), event);+ self._return_value = try frame.page_arena.dupe(u8, value);}pub fn getOpen(self: *const Dialog) bool {@@ -141,7 +162,7 @@ pub const JsApi = struct {const reflect = Element.Reflect(Dialog);pub const open = reflect.boolean("open");- pub const returnValue = reflect.string("returnvalue");+ pub const returnValue = bridge.accessor(Dialog.getReturnValue, Dialog.setReturnValue, .{});pub const show = bridge.function(Dialog.show, .{});pub const showModal = bridge.function(Dialog.showModal, .{});@@ -162,7 +183,7 @@ test "WebApi: HTML.Dialog close request" {defer ls.deinit();// Each step runs its script, presses a trusted Escape when `press` is set,- // then compares the page's state() summary.+ // runs the queued events, then compares the page's state() summary.const steps = [_]struct { []const u8, bool, []const u8 }{// The modal dialog closes; returnValue is left unchanged..{ "reset(); A.returnValue = 'keep'; A.showModal()", true, "a:false b:false rv:keep| log:cancel@a,close@a!" },@@ -189,6 +210,8 @@ test "WebApi: HTML.Dialog close request" {if (press) {try pressEscape(frame);}+ // close is a queued event+ try frame.js.scheduler.run();const actual = try (try ls.local.compileAndRun("state()", null)).toStringSliceWithAlloc(testing.arena_allocator);try testing.expectString(expected, actual);}