Skip to content

Lightpanda: the headless browser designed for AI and automation

input: insert typed text into contenteditable

a.dmitryuk7f458dce5fea
diff --git a/src/browser/frame/user_input.zig b/src/browser/frame/user_input.zig
index 378bb52d3..3f23ea2ef 100644
--- a/src/browser/frame/user_input.zig
+++ b/src/browser/frame/user_input.zig
@@ -1516,6 +1516,8 @@ pub fn typeChar(frame: *Frame, target: *Element, keypress: *KeyboardEvent, text:
_ = try applyEdit(frame, input, .{ .insert = text });
} else if (target.is(Element.Html.TextArea)) |textarea| {
_ = try applyEdit(frame, textarea, if (is_enter) .line_break else .{ .insert = text });
+ } else if (!is_enter and target.isEditable()) {
+ _ = try insertIntoEditingHost(frame, target, text);
}
}
@@ -1651,6 +1653,95 @@ pub fn applyEdit(frame: *Frame, ctl: anytype, edit: Edit) !bool {
return true;
}
+/// Plain text typed into editable content (contenteditable): cancellable
+/// through beforeinput like a control's edit, then replaces the selection and
+/// leaves the caret after the text. A selection outside the editable content
+/// of `target` puts the text at the end of `target`. Only text insertion is
+/// supported: line breaks, deletion and formatting need an editing pipeline.
+/// Returns whether the edit happened.
+fn insertIntoEditingHost(frame: *Frame, target: *Element, text: []const u8) !bool {
+ if (!try allowEdit(frame, target, text, text, "insertText")) {
+ return false;
+ }
+ // a beforeinput or textInput listener can make it non-editable
+ if (!target.isEditable()) {
+ return false;
+ }
+
+ const host = target.asNode();
+ const selection = &frame.document._selection;
+ var container = host;
+ var offset: u32 = @intCast(host.getChildrenCount());
+ if (selection._range) |range| {
+ const abstract = range.asAbstractRange();
+ if (isEditableIn(host, abstract.getStartContainer()) and isEditableIn(host, abstract.getEndContainer())) {
+ if (!abstract.getCollapsed()) {
+ try range.deleteContents(frame);
+ }
+ container = abstract.getStartContainer();
+ offset = abstract.getStartOffset();
+ }
+ }
+
+ // Join the text node at the caret, as Chrome does, rather than adding a
+ // sibling next to it.
+ var text_node: ?*Node.CData.Text = container.is(Node.CData.Text);
+ if (text_node == null) {
+ if (container.is(Node.CData) != null) {
+ // a caret in a comment or processing instruction: after it
+ offset = @intCast(container.parentNode().?.getChildIndex(container).? + 1);
+ container = container.parentNode().?;
+ }
+ if (offset > 0) {
+ if (container.getChildAt(offset - 1)) |before| {
+ if (before.is(Node.CData.Text)) |t| {
+ text_node = t;
+ offset = @intCast(t.asCData().getLength());
+ }
+ }
+ }
+ }
+ if (text_node == null) {
+ if (container.getChildAt(offset)) |after| {
+ if (after.is(Node.CData.Text)) |t| {
+ text_node = t;
+ offset = 0;
+ }
+ }
+ }
+
+ var caret: u32 = undefined;
+ if (text_node) |t| {
+ try t.asCData().replaceData(offset, 0, text, frame);
+ caret = offset + @as(u32, @intCast(Node.CData.utf16Len(text)));
+ } else {
+ const new_node = try frame.document.createTextNode(text);
+ _ = try container.insertBefore(new_node, container.getChildAt(offset), frame);
+ text_node = new_node.is(Node.CData.Text).?;
+ caret = @intCast(Node.CData.utf16Len(text));
+ }
+ try selection.collapse(text_node.?.asCData().asNode(), caret, frame);
+
+ const event = try InputEvent.initTrusted(comptime .wrap("input"), .{
+ .bubbles = true,
+ .composed = true,
+ .data = text,
+ .inputType = "insertText",
+ }, frame);
+ try frame._event_manager.dispatch(target.asEventTarget(), event.asEvent());
+ return true;
+}
+
+// `node` is inside `host` and editable: the nearest contenteditable attribute
+// of its element (or of its parent, for a text node) allows editing.
+fn isEditableIn(host: *Node, node: *Node) bool {
+ if (!host.contains(node)) {
+ return false;
+ }
+ const element = node.is(Element) orelse node.parentElement() orelse return false;
+ return element.isEditable();
+}
+
pub fn acceptsEdit(el: *Element) bool {
if (el.isDisabled()) {
return false;
@@ -1866,6 +1957,8 @@ pub fn insertText(frame: *Frame, v: []const u8) !void {
_ = try applyEdit(frame, input, .{ .insert = v });
} else if (html_element.is(Element.Html.TextArea)) |textarea| {
_ = try applyEdit(frame, textarea, .{ .insert = v });
+ } else if (html_element.isEditable()) {
+ _ = try insertIntoEditingHost(frame, html_element, v);
}
}
diff --git a/src/server/cdp/domains/input.zig b/src/server/cdp/domains/input.zig
index e46f14133..8a19d7464 100644
--- a/src/server/cdp/domains/input.zig
+++ b/src/server/cdp/domains/input.zig
@@ -3546,3 +3546,161 @@ test "cdp.input: a missed release preserves held buttons and mouse suppression"
\\'pointerup:0:0:0:mouse:true'
);
}
+
+const EditingHostInput = union(enum) {
+ key: []const u8,
+ insert_text: []const u8,
+};
+
+// Loads a page, runs `setup` (which builds an editing host and a selection),
+// sends `input` to the focused element and checks `expected`, a JS expression.
+// Every test records the events the host sees in `window.seen`.
+fn expectEditingHostInput(setup: []const u8, input: EditingHostInput, expected: []const u8) !void {
+ var ctx = try testing.context();
+ defer ctx.deinit();
+
+ const bc = try ctx.loadBrowserContext(.{});
+ const page = try bc.session.createPage();
+ const frame = page.frame().?;
+
+ const url = "http://localhost:9582/src/browser/tests/mcp_actions.html";
+ try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });
+ try testing.waitForPage(bc);
+
+ var ls: lp.js.Local.Scope = undefined;
+ frame.js.localScope(&ls);
+ defer ls.deinit();
+
+ var try_catch: lp.js.TryCatch = undefined;
+ try_catch.init(&ls.local);
+ defer try_catch.deinit();
+
+ _ = try ls.local.compileAndRun(
+ \\window.seen = [];
+ \\for (const t of ['keypress', 'beforeinput', 'textInput', 'input']) {
+ \\ document.addEventListener(t, (e) => window.seen.push(t + ':' + (e.inputType || e.key || e.data)));
+ \\}
+ , null);
+ _ = try ls.local.compileAndRun(setup, null);
+
+ switch (input) {
+ .key => |text| try ctx.processMessage(.{
+ .id = 1,
+ .method = "Input.dispatchKeyEvent",
+ .params = .{ .type = "keyDown", .key = text, .text = text },
+ }),
+ .insert_text => |text| try ctx.processMessage(.{
+ .id = 1,
+ .method = "Input.insertText",
+ .params = .{ .text = text },
+ }),
+ }
+
+ try testing.expect((try ls.local.compileAndRun(expected, null)).isTrue());
+}
+
+test "cdp.input: typing into an editing host without a selection appends the text" {
+ try expectEditingHostInput(
+ \\document.body.insertAdjacentHTML('beforeend', '<div id="host" contenteditable="true">ab</div>');
+ \\const host = document.getElementById('host');
+ \\host.focus();
+ \\getSelection().removeAllRanges();
+ , .{ .key = "c" },
+ \\host.innerHTML === 'abc' &&
+ \\window.seen.join(',') === 'keypress:c,beforeinput:insertText,textInput:c,input:insertText' &&
+ \\getSelection().isCollapsed &&
+ \\getSelection().anchorNode === host.firstChild && getSelection().anchorOffset === 3
+ );
+}
+
+test "cdp.input: insertText into an editing host inserts at the caret" {
+ try expectEditingHostInput(
+ \\document.body.insertAdjacentHTML('beforeend', '<div id="host" contenteditable>abcd</div>');
+ \\const host = document.getElementById('host');
+ \\host.focus();
+ \\getSelection().collapse(host.firstChild, 2);
+ , .{ .insert_text = "XY" },
+ \\host.innerHTML === 'abXYcd' &&
+ \\window.seen.join(',') === 'beforeinput:insertText,textInput:XY,input:insertText' &&
+ \\getSelection().anchorNode === host.firstChild && getSelection().anchorOffset === 4
+ );
+}
+
+test "cdp.input: typing into an empty editing element creates a text node" {
+ try expectEditingHostInput(
+ \\document.body.insertAdjacentHTML('beforeend', '<div id="host" contenteditable><p id="p"></p></div>');
+ \\const host = document.getElementById('host');
+ \\const p = document.getElementById('p');
+ \\host.focus();
+ \\getSelection().collapse(p, 0);
+ , .{ .key = "z" },
+ \\host.innerHTML === '<p id="p">z</p>' &&
+ \\getSelection().anchorNode === p.firstChild && getSelection().anchorOffset === 1
+ );
+}
+
+test "cdp.input: insertText into an editing host replaces a non-collapsed selection" {
+ try expectEditingHostInput(
+ \\document.body.insertAdjacentHTML('beforeend', '<div id="host" contenteditable>ab<b>cd</b>ef</div>');
+ \\const host = document.getElementById('host');
+ \\host.focus();
+ \\const range = document.createRange();
+ \\range.setStart(host.firstChild, 1);
+ \\range.setEnd(host.lastChild, 1);
+ \\getSelection().removeAllRanges();
+ \\getSelection().addRange(range);
+ , .{ .insert_text = "Z" },
+ \\host.textContent === 'aZf' &&
+ \\getSelection().isCollapsed &&
+ \\getSelection().anchorNode.data.slice(0, getSelection().anchorOffset) === 'aZ'
+ );
+}
+
+test "cdp.input: a cancelled beforeinput leaves an editing host unchanged" {
+ try expectEditingHostInput(
+ \\document.body.insertAdjacentHTML('beforeend', '<div id="host" contenteditable>ab</div>');
+ \\const host = document.getElementById('host');
+ \\host.focus();
+ \\getSelection().collapse(host.firstChild, 1);
+ \\host.addEventListener('beforeinput', (e) => e.preventDefault());
+ , .{ .key = "c" },
+ \\host.innerHTML === 'ab' &&
+ \\window.seen.join(',') === 'keypress:c,beforeinput:insertText'
+ );
+}
+
+test "cdp.input: a cancelled keypress fires no beforeinput on an editing host" {
+ try expectEditingHostInput(
+ \\document.body.insertAdjacentHTML('beforeend', '<div id="host" contenteditable>ab</div>');
+ \\const host = document.getElementById('host');
+ \\host.focus();
+ \\getSelection().collapse(host.firstChild, 1);
+ \\host.addEventListener('keypress', (e) => e.preventDefault());
+ , .{ .key = "c" },
+ \\host.innerHTML === 'ab' &&
+ \\window.seen.join(',') === 'keypress:c'
+ );
+}
+
+test "cdp.input: text for an editing host stays out of a contenteditable=false island" {
+ try expectEditingHostInput(
+ \\document.body.insertAdjacentHTML('beforeend', '<div id="host" contenteditable><span id="island" contenteditable="false">lock</span>tail</div>');
+ \\const host = document.getElementById('host');
+ \\host.focus();
+ \\getSelection().collapse(document.getElementById('island').firstChild, 2);
+ , .{ .insert_text = "X" },
+ \\document.getElementById('island').textContent === 'lock' &&
+ \\host.textContent === 'locktailX'
+ );
+}
+
+test "cdp.input: typing into a non-editable focused element inserts nothing" {
+ try expectEditingHostInput(
+ \\document.body.insertAdjacentHTML('beforeend', '<div id="host" tabindex="0">ab</div>');
+ \\const host = document.getElementById('host');
+ \\host.focus();
+ \\getSelection().collapse(host.firstChild, 1);
+ , .{ .key = "c" },
+ \\host.innerHTML === 'ab' && window.seen.join(',') === 'keypress:c'
+ );
+}