Skip to content

Lightpanda: the headless browser designed for AI and automation

input: target the editing host when inserting into contenteditable

a.dmitryuk3010bb49a2d0
diff --git a/src/browser/frame/user_input.zig b/src/browser/frame/user_input.zig
index 3f23ea2ef..46ce5be78 100644
--- a/src/browser/frame/user_input.zig
+++ b/src/browser/frame/user_input.zig
@@ -1655,23 +1655,26 @@ pub fn applyEdit(frame: *Frame, ctl: anytype, edit: Edit) !bool {
/// 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.
+/// leaves the caret after the text. The events target the editing host of
+/// `target`, as in Chrome. A selection outside the editable content of the
+/// host puts the text at the start of the host, where Chrome places the caret
+/// when the host is focused. 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")) {
+ const host_el = outermostEditingHost(target) orelse return false;
+ if (!try allowEdit(frame, host_el, text, text, "insertText")) {
return false;
}
- // a beforeinput or textInput listener can make it non-editable
- if (!target.isEditable()) {
+ const host = host_el.asNode();
+ // a beforeinput or textInput listener can make it non-editable or remove it
+ if (!host_el.isEditable() or !host.isConnected()) {
return false;
}
- const host = target.asNode();
const selection = &frame.document._selection;
var container = host;
- var offset: u32 = @intCast(host.getChildrenCount());
+ var offset: u32 = 0;
if (selection._range) |range| {
const abstract = range.asAbstractRange();
if (isEditableIn(host, abstract.getStartContainer()) and isEditableIn(host, abstract.getEndContainer())) {
@@ -1686,7 +1689,11 @@ fn insertIntoEditingHost(frame: *Frame, target: *Element, text: []const u8) !boo
// 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 (text_node) |t| {
+ // a caret inside a surrogate pair: before the pair
+ const data = t.asCData().getData().str();
+ offset = @intCast(Node.CData.utf16Len(data[0..Node.CData.utf16OffsetToUtf8Floor(data, offset)]));
+ } else {
if (container.is(Node.CData) != null) {
// a caret in a comment or processing instruction: after it
offset = @intCast(container.parentNode().?.getChildIndex(container).? + 1);
@@ -1710,16 +1717,15 @@ fn insertIntoEditingHost(frame: *Frame, target: *Element, text: []const u8) !boo
}
}
- 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 caret: u32 = if (text_node) |t| blk: {
+ try t.asCData().insertData(offset, text, frame);
+ break :blk offset + @as(u32, @intCast(Node.CData.utf16Len(text)));
+ } else blk: {
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));
- }
+ break :blk @intCast(Node.CData.utf16Len(text));
+ };
try selection.collapse(text_node.?.asCData().asNode(), caret, frame);
const event = try InputEvent.initTrusted(comptime .wrap("input"), .{
@@ -1728,12 +1734,12 @@ fn insertIntoEditingHost(frame: *Frame, target: *Element, text: []const u8) !boo
.data = text,
.inputType = "insertText",
}, frame);
- try frame._event_manager.dispatch(target.asEventTarget(), event.asEvent());
+ try frame._event_manager.dispatch(host_el.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.
+// Whether `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;
diff --git a/src/browser/webapi/CData.zig b/src/browser/webapi/CData.zig
index 5d4bb8bfc..c847eaa2f 100644
--- a/src/browser/webapi/CData.zig
+++ b/src/browser/webapi/CData.zig
@@ -392,7 +392,7 @@ fn deleteData(self: *CData, offset: usize, count: usize, frame: *Frame) !void {
self.dataChanged(old_data, frame);
}
-fn insertData(self: *CData, offset: usize, data: []const u8, frame: *Frame) !void {
+pub fn insertData(self: *CData, offset: usize, data: []const u8, frame: *Frame) !void {
const byte_offset = try utf16OffsetToUtf8(self._data.str(), offset);
// Update live ranges per DOM spec replaceData steps (insertData = replaceData with count=0)
diff --git a/src/server/cdp/domains/input.zig b/src/server/cdp/domains/input.zig
index 8a19d7464..00eb1f570 100644
--- a/src/server/cdp/domains/input.zig
+++ b/src/server/cdp/domains/input.zig
@@ -3554,7 +3554,9 @@ const EditingHostInput = union(enum) {
// 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`.
+// Every test records the events the document sees in `window.seen` as
+// `type:target id:inputType or key:data:cancelable:composed:bubbles:isTrusted`;
+// `window.types()` lists only `type:target id`.
fn expectEditingHostInput(setup: []const u8, input: EditingHostInput, expected: []const u8) !void {
var ctx = try testing.context();
defer ctx.deinit();
@@ -3578,8 +3580,10 @@ fn expectEditingHostInput(setup: []const u8, input: EditingHostInput, expected:
_ = 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)));
+ \\ document.addEventListener(t, (e) => window.seen.push(
+ \\ `${t}:${e.target.id}:${e.inputType || e.key}:${e.data}:${e.cancelable}:${e.composed}:${e.bubbles}:${e.isTrusted}`));
\\}
+ \\window.types = () => window.seen.map((s) => s.split(':', 2).join(':')).join(',');
, null);
_ = try ls.local.compileAndRun(setup, null);
@@ -3599,17 +3603,35 @@ fn expectEditingHostInput(setup: []const u8, input: EditingHostInput, expected:
try testing.expect((try ls.local.compileAndRun(expected, null)).isTrue());
}
-test "cdp.input: typing into an editing host without a selection appends the text" {
+test "cdp.input: typing into an editing host without a selection inserts at its start" {
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' &&
+ \\host.innerHTML === 'cab' &&
+ \\JSON.stringify(window.seen) === JSON.stringify([
+ \\ 'keypress:host:c:undefined:true:true:true:true',
+ \\ 'beforeinput:host:insertText:c:true:true:true:true',
+ \\ 'textInput:host:undefined:c:true:false:true:true',
+ \\ 'input:host:insertText:c:false:true:true:true',
+ \\]) &&
\\getSelection().isCollapsed &&
- \\getSelection().anchorNode === host.firstChild && getSelection().anchorOffset === 3
+ \\getSelection().anchorNode === host.firstChild && getSelection().anchorOffset === 1
+ );
+}
+
+test "cdp.input: text typed into an editing host's descendant targets the host" {
+ try expectEditingHostInput(
+ \\document.body.insertAdjacentHTML('beforeend', '<div id="host" contenteditable><span id="s" tabindex="0">ab</span></div>');
+ \\const host = document.getElementById('host');
+ \\const s = document.getElementById('s');
+ \\s.focus();
+ \\getSelection().collapse(s.firstChild, 1);
+ , .{ .key = "c" },
+ \\document.activeElement === s && s.textContent === 'acb' &&
+ \\window.types() === 'keypress:s,beforeinput:host,textInput:host,input:host'
);
}
@@ -3621,11 +3643,48 @@ test "cdp.input: insertText into an editing host inserts at the caret" {
\\getSelection().collapse(host.firstChild, 2);
, .{ .insert_text = "XY" },
\\host.innerHTML === 'abXYcd' &&
- \\window.seen.join(',') === 'beforeinput:insertText,textInput:XY,input:insertText' &&
+ \\window.types() === 'beforeinput:host,textInput:host,input:host' &&
+ \\getSelection().anchorNode === host.firstChild && getSelection().anchorOffset === 4
+ );
+}
+
+test "cdp.input: insertText into an editing host counts the caret in UTF-16 code units" {
+ 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 = "é😀" },
+ \\host.textContent === 'abé😀cd' &&
+ \\getSelection().anchorNode === host.firstChild && getSelection().anchorOffset === 5
+ );
+}
+
+test "cdp.input: typing after non-ASCII text in an editing host" {
+ try expectEditingHostInput(
+ \\document.body.insertAdjacentHTML('beforeend', '<div id="host" contenteditable>é😀x</div>');
+ \\const host = document.getElementById('host');
+ \\host.focus();
+ \\getSelection().collapse(host.firstChild, 3);
+ , .{ .key = "Z" },
+ \\host.textContent === 'é😀Zx' &&
\\getSelection().anchorNode === host.firstChild && getSelection().anchorOffset === 4
);
}
+test "cdp.input: a caret inside a surrogate pair inserts before the pair" {
+ try expectEditingHostInput(
+ \\document.body.insertAdjacentHTML('beforeend', '<div id="host" contenteditable>a😀b</div>');
+ \\const host = document.getElementById('host');
+ \\host.focus();
+ \\getSelection().collapse(host.firstChild, 2);
+ , .{ .insert_text = "X" },
+ \\host.textContent === 'aX😀b' &&
+ \\window.types() === 'beforeinput:host,textInput:host,input:host' &&
+ \\getSelection().anchorNode === host.firstChild && getSelection().anchorOffset === 2
+ );
+}
+
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>');
@@ -3639,6 +3698,30 @@ test "cdp.input: typing into an empty editing element creates a text node" {
);
}
+test "cdp.input: text before a text node in an editing host joins it" {
+ try expectEditingHostInput(
+ \\document.body.insertAdjacentHTML('beforeend', '<div id="host" contenteditable><b>x</b>tail</div>');
+ \\const host = document.getElementById('host');
+ \\host.focus();
+ \\getSelection().collapse(host, 1);
+ , .{ .insert_text = "Y" },
+ \\host.innerHTML === '<b>x</b>Ytail' && host.childNodes.length === 2 &&
+ \\getSelection().anchorNode === host.lastChild && getSelection().anchorOffset === 1
+ );
+}
+
+test "cdp.input: a caret in a comment of an editing host inserts after the comment" {
+ try expectEditingHostInput(
+ \\document.body.insertAdjacentHTML('beforeend', '<div id="host" contenteditable>ab<!--c--><b>cd</b></div>');
+ \\const host = document.getElementById('host');
+ \\host.focus();
+ \\getSelection().collapse(host.childNodes[1], 1);
+ , .{ .insert_text = "X" },
+ \\host.innerHTML === 'ab<!--c-->X<b>cd</b>' &&
+ \\getSelection().anchorNode === host.childNodes[2] && 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>');
@@ -3665,7 +3748,33 @@ test "cdp.input: a cancelled beforeinput leaves an editing host unchanged" {
\\host.addEventListener('beforeinput', (e) => e.preventDefault());
, .{ .key = "c" },
\\host.innerHTML === 'ab' &&
- \\window.seen.join(',') === 'keypress:c,beforeinput:insertText'
+ \\window.types() === 'keypress:host,beforeinput:host'
+ );
+}
+
+test "cdp.input: a beforeinput listener that ends editing 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', () => host.removeAttribute('contenteditable'));
+ , .{ .insert_text = "c" },
+ \\host.innerHTML === 'ab' &&
+ \\window.types() === 'beforeinput:host,textInput:host'
+ );
+}
+
+test "cdp.input: a beforeinput listener that removes an editing host leaves it 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', () => host.remove());
+ , .{ .insert_text = "c" },
+ \\host.innerHTML === 'ab' && !host.isConnected &&
+ \\!window.seen.some((s) => s.startsWith('input:'))
);
}
@@ -3678,7 +3787,7 @@ test "cdp.input: a cancelled keypress fires no beforeinput on an editing host" {
\\host.addEventListener('keypress', (e) => e.preventDefault());
, .{ .key = "c" },
\\host.innerHTML === 'ab' &&
- \\window.seen.join(',') === 'keypress:c'
+ \\window.types() === 'keypress:host'
);
}
@@ -3690,7 +3799,7 @@ test "cdp.input: text for an editing host stays out of a contenteditable=false i
\\getSelection().collapse(document.getElementById('island').firstChild, 2);
, .{ .insert_text = "X" },
\\document.getElementById('island').textContent === 'lock' &&
- \\host.textContent === 'locktailX'
+ \\host.textContent === 'Xlocktail' && host.firstChild.data === 'X'
);
}
@@ -3701,6 +3810,6 @@ test "cdp.input: typing into a non-editable focused element inserts nothing" {
\\host.focus();
\\getSelection().collapse(host.firstChild, 1);
, .{ .key = "c" },
- \\host.innerHTML === 'ab' && window.seen.join(',') === 'keypress:c'
+ \\host.innerHTML === 'ab' && window.types() === 'keypress:host'
);
}