Lightpanda: the headless browser designed for AI and automation
webapi: execCommand(insertText)
Karl Seguin2dd6de97dd23
diff --git a/src/browser/frame/exec_command.zig b/src/browser/frame/exec_command.zignew file mode 100644index 000000000..7ceb38337--- /dev/null+++ b/src/browser/frame/exec_command.zig@@ -0,0 +1,199 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// 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/>.++// document.execCommand and the queryCommand* methods.+// https://w3c.github.io/editing/docs/execCommand/+//+// A command is supported only once it does what Chrome does, events included:+// a caller that gets true skips its fallback. Every other command is+// unsupported, which the spec answers with false (or "" for the value), not an+// exception.++const std = @import("std");+const lp = @import("lightpanda");++const Frame = @import("../Frame.zig");+const Node = @import("../webapi/Node.zig");+const Element = @import("../webapi/Element.zig");+const Document = @import("../webapi/Document.zig");+const user_input = @import("user_input.zig");++const log = lp.log;++const Command = enum {+ insertText,++ // Command names are ASCII case-insensitive.+ fn parse(name: []const u8) ?Command {+ const info = @typeInfo(Command).@"enum";+ inline for (info.field_names, info.field_values) |field_name, field_value| {+ if (std.ascii.eqlIgnoreCase(field_name, name)) {+ return @fromBackingInt(@intCast(field_value));+ }+ }+ return null;+ }+};++pub fn exec(doc: *Document, name: []const u8, value: []const u8) !bool {+ const command = Command.parse(name) orelse {+ log.info(.not_implemented, "document.execCommand", .{ .command = name });+ return false;+ };+ const frame = doc._frame orelse return false;+ if (doc._exec_command_running) {+ return false;+ }+ doc._exec_command_running = true;+ defer doc._exec_command_running = false;++ return switch (command) {+ .insertText => insertText(frame, value),+ };+}++pub fn isSupported(doc: *const Document, name: []const u8) bool {+ return doc._frame != null and Command.parse(name) != null;+}++pub fn isEnabled(doc: *Document, name: []const u8) bool {+ if (doc._frame == null) {+ return false;+ }+ const command = Command.parse(name) orelse return false;+ return switch (command) {+ .insertText => editTarget(doc) != null,+ };+}++const EditTarget = union(enum) {+ input: *Element.Html.Input,+ textarea: *Element.Html.TextArea,+ host: *Element,+};++fn editTarget(doc: *Document) ?EditTarget {+ const active = doc._active_element;+ if (active) |el| {+ if (el.is(Element.Html.Input)) |input| {+ if (input.acceptsTextEntry() == false or user_input.acceptsEdit(el) == false) {+ return null;+ }+ return .{ .input = input };+ }+ if (el.is(Element.Html.TextArea)) |textarea| {+ if (user_input.acceptsEdit(el) == false) {+ return null;+ }+ return .{ .textarea = textarea };+ }+ }++ if (doc._selection._range) |range| {+ const node = range.asAbstractRange().getStartContainer();+ if (node.is(Element) orelse node.parentElement()) |el| {+ if (el.isEditable()) {+ if (user_input.outermostEditingHost(el)) |host| {+ return .{ .host = host };+ }+ }+ }+ }++ const el = active orelse return null;+ if (el.isEditable() == false) {+ return null;+ }+ const host = user_input.outermostEditingHost(el) orelse return null;+ return .{ .host = host };+}++// Unlike typed text, no beforeinput or textInput: just the edit and input.+fn insertText(frame: *Frame, text: []const u8) !bool {+ const target = editTarget(frame.document) orelse return false;+ if (text.len == 0 and isCollapsed(frame.document, target)) {+ // nothing to replace and nothing to insert+ return true;+ }++ switch (target) {+ .input => |input| {+ // a single-line control turns line breaks into spaces+ const scratch = try frame.getArena(text.len, "execCommand.insertText");+ defer scratch.release();+ const line = try scratch.allocator().dupe(u8, text);+ std.mem.replaceScalar(u8, line, '\n', ' ');+ try input.rememberValueBeforeEdit(frame);+ try input.innerInsert(line, line, "insertText", frame);+ },+ .textarea => |textarea| {+ try textarea.rememberValueBeforeEdit(frame);+ var it = std.mem.splitScalar(u8, text, '\n');+ if (it.next()) |line| {+ if (line.len > 0) {+ try textarea.innerInsert(line, line, "insertText", frame);+ }+ }+ while (it.next()) |line| {+ try textarea.innerInsert("\n", null, "insertText", frame);+ if (line.len > 0) {+ try textarea.innerInsert(line, line, "insertText", frame);+ }+ }+ },+ .host => |host| {+ if (std.mem.indexOfScalar(u8, text, '\n') != null) {+ // Chrome splits the block at a line break, which needs an editing+ // pipeline. Safer to refuse (return false) and hope the caller+ // has a fallback when we return false.+ log.info(.not_implemented, "execCommand.insertText", .{ .line_break = true });+ return false;+ }+ if (frame.document._selection._range) |range| {+ const abstract = range.asAbstractRange();+ if (inSelect(abstract.getStartContainer()) or inSelect(abstract.getEndContainer())) {+ return false;+ }+ }+ try user_input.insertAtSelection(frame, host, text);+ },+ }+ return true;+}++// Edits never land inside a <select>, no mater the selection.+fn inSelect(node: *Node) bool {+ var current: ?*Node = node;+ while (current) |n| : (current = n.parentNode()) {+ const el = n.is(Element) orelse continue;+ if (el.is(Element.Html.Select) != null or el.is(Element.Html.Option) != null or el.is(Element.Html.OptGroup) != null) {+ return true;+ }+ }+ return false;+}++fn isCollapsed(doc: *Document, target: EditTarget) bool {+ return switch (target) {+ inline .input, .textarea => |ctl| ctl._selection_start == ctl._selection_end,+ .host => {+ const range = doc._selection._range orelse return true;+ return range.asAbstractRange().getCollapsed();+ },+ };+}diff --git a/src/browser/frame/user_input.zig b/src/browser/frame/user_input.zigindex d5d5ac5bc..f667369b6 100644--- a/src/browser/frame/user_input.zig+++ b/src/browser/frame/user_input.zig@@ -1162,7 +1162,7 @@ fn isEditingHost(node: *Node) bool {return element.isEditingHost();}-fn outermostEditingHost(target: *Element) ?*Element {+pub fn outermostEditingHost(target: *Element) ?*Element {var host: ?*Element = null;var current: ?*Element = target;while (current) |el| : (current = el.parentElement()) {@@ -1667,12 +1667,19 @@ fn insertIntoEditingHost(frame: *Frame, target: *Element, text: []const u8) !booif (!try allowEdit(frame, host_el, text, text, "insertText")) {return false;}- 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()) {+ if (!host_el.isEditable() or !host_el.asNode().isConnected()) {return false;}+ try insertAtSelection(frame, host_el, text);+ return true;+}+/// The edit part of insertIntoEditingHost, without the events that can cancel+/// it: replaces the selection in `host_el` with `text`, leaves the caret after+/// it and fires input.+pub fn insertAtSelection(frame: *Frame, host_el: *Element, text: []const u8) !void {+ const host = host_el.asNode();const selection = &frame.document._selection;var container: *Node, var offset: u32 = firstCaretPosition(host);if (selection._range) |range| {@@ -1735,7 +1742,6 @@ fn insertIntoEditingHost(frame: *Frame, target: *Element, text: []const u8) !boo.inputType = "insertText",}, frame);try frame._event_manager.dispatch(host_el.asEventTarget(), event.asEvent());- return true;}// Where Chrome puts the caret when an editing host is focused: its firstdiff --git a/src/browser/tests/document/exec_command.html b/src/browser/tests/document/exec_command.htmlindex 4de875cc8..811f32be4 100644--- a/src/browser/tests/document/exec_command.html+++ b/src/browser/tests/document/exec_command.html@@ -1,7 +1,27 @@<!DOCTYPE html><meta name=lp-mode content=test><script src="../testing.js"></script>-<body><div id="host" contenteditable>abc</div></body>+<body>+<div id="host" contenteditable>abc</div>+<div id="plain">plain</div>+<input id="text" value="hello">+<input id="ro" readonly value="ro">+<textarea id="area">abc</textarea>+</body>++<script>+ // Events from the last edit, as "type:target:inputType:data".+ let events = [];+ for (const type of ['beforeinput', 'textInput', 'input']) {+ document.addEventListener(type, e => {+ events.push(`${type}:${e.target.id}:${e.inputType ?? ''}:${e.data}`);+ }, true);+ }+ function exec(value) {+ events = [];+ return document.execCommand('insertText', false, value);+ }+</script><script id="unsupported">{@@ -17,25 +37,206 @@}</script>-<script id="editing_commands">+<script id="not_yet_supported">{const host = $('#host');- for (const cmd of ['bold', 'insertText']) {- host.innerHTML = 'abc';- getSelection().selectAllChildren(host);- testing.expectEqual(false, document.queryCommandState(cmd));- testing.expectEqual(false, document.queryCommandIndeterm(cmd));- testing.diverges('no editing pipeline', () => {- testing.expectEqual(false, document.queryCommandSupported(cmd));- testing.expectEqual(false, document.queryCommandEnabled(cmd));- testing.expectEqual(false, document.execCommand(cmd, false, 'x'));- testing.expectEqual('abc', host.innerHTML);- });- }+ host.innerHTML = 'abc';+ getSelection().selectAllChildren(host);+ testing.expectEqual(false, document.queryCommandState('bold'));+ testing.expectEqual(false, document.queryCommandIndeterm('bold'));+ testing.diverges('no formatting commands', () => {+ testing.expectEqual(false, document.queryCommandSupported('bold'));+ testing.expectEqual(false, document.execCommand('bold'));+ testing.expectEqual('abc', host.innerHTML);+ });// supported in Chrome whether or not there's a user click; exec isn'ttesting.diverges('no clipboard', () => {testing.expectEqual(false, document.queryCommandSupported('copy'));});+ getSelection().removeAllRanges();+}+</script>++<script id="insert_text_nothing_editable">+{+ document.activeElement.blur();+ getSelection().selectAllChildren($('#plain'));+ testing.expectEqual(true, document.queryCommandSupported('insertText'));+ testing.expectEqual(false, document.queryCommandEnabled('insertText'));+ testing.expectEqual(false, exec('X'));+ testing.expectEqual('plain', $('#plain').innerHTML);+ testing.expectEqual([], events);+ getSelection().removeAllRanges();+}+</script>++<script id="insert_text_input">+{+ const input = $('#text');+ input.focus();+ input.setSelectionRange(1, 3);+ testing.expectEqual(true, document.queryCommandEnabled('insertText'));+ testing.expectEqual(false, document.queryCommandState('insertText'));+ testing.expectEqual('', document.queryCommandValue('insertText'));++ // no beforeinput or textInput, unlike typing+ testing.expectEqual(true, exec('XY'));+ testing.expectEqual('hXYlo', input.value);+ testing.expectEqual(3, input.selectionStart);+ testing.expectEqual(3, input.selectionEnd);+ testing.expectEqual(['input:text:insertText:XY'], events);++ // case-insensitive+ events = [];+ testing.expectEqual(true, document.execCommand('INSERTtext', false, 'Z'));+ testing.expectEqual('hXYZlo', input.value);++ // nothing to insert at a caret: nothing happens, but it succeeds+ testing.expectEqual(true, exec(undefined));+ testing.expectEqual('hXYZlo', input.value);+ testing.expectEqual([], events);++ // empty text over a selection deletes it+ input.setSelectionRange(0, 2);+ testing.expectEqual(true, exec(''));+ testing.expectEqual('YZlo', input.value);+ testing.expectEqual(['input:text:insertText:'], events);++ input.setSelectionRange(0, 0);+ testing.expectEqual(true, exec('a\nb'));+ testing.expectEqual('a bYZlo', input.value);+}+</script>++<script id="insert_text_not_cancelable">+{+ const input = $('#text');+ input.value = '';+ input.focus();+ let cancelable = null;+ input.addEventListener('input', e => {+ cancelable = e.cancelable;+ e.preventDefault();+ }, {once: true});+ testing.expectEqual(true, exec('P'));+ testing.expectEqual('P', input.value);+ testing.expectEqual(false, cancelable);+}+</script>++<script id="insert_text_nested">+{+ const input = $('#text');+ input.value = '';+ input.focus();+ let nested = null;+ input.addEventListener('input', () => {+ nested = document.execCommand('insertText', false, 'N');+ }, {once: true});+ testing.expectEqual(true, exec('Q'));+ testing.expectEqual(false, nested);+ testing.expectEqual('Q', input.value);+}+</script>++<script id="insert_text_change_on_blur">+{+ const input = $('#text');+ input.value = '';+ input.focus();+ let changes = 0;+ input.addEventListener('change', () => changes += 1);+ exec('C');+ testing.expectEqual(0, changes);+ input.blur();+ testing.expectEqual(1, changes);+}+</script>++<script id="insert_text_readonly">+{+ const ro = $('#ro');+ ro.focus();+ testing.expectEqual(false, document.queryCommandEnabled('insertText'));+ testing.expectEqual(false, exec('X'));+ testing.expectEqual('ro', ro.value);+ testing.expectEqual([], events);+}+</script>++<script id="insert_text_textarea">+{+ const area = $('#area');+ area.focus();+ area.setSelectionRange(3, 3);+ // one input event per line and per line break+ testing.expectEqual(true, exec('\nline'));+ testing.expectEqual('abc\nline', area.value);+ testing.expectEqual(['input:area:insertText:null', 'input:area:insertText:line'], events);+}+</script>++<script id="insert_text_contenteditable">+{+ const host = $('#host');+ host.innerHTML = 'abc';+ host.focus();+ getSelection().setBaseAndExtent(host.firstChild, 1, host.firstChild, 2);+ testing.expectEqual(true, document.queryCommandEnabled('insertText'));+ testing.expectEqual(true, exec('XY'));+ testing.expectEqual('aXYc', host.innerHTML);+ testing.expectEqual(3, getSelection().anchorOffset);+ testing.expectEqual(['input:host:insertText:XY'], events);++ // text, not markup+ testing.expectEqual(true, exec('<b>'));+ testing.expectEqual('aXY<b>c', host.innerHTML);++ // Chrome splits the block: aXY<b>a<div>bc</div>+ testing.diverges('no block splitting', () => {+ testing.expectEqual(false, exec('a\nb'));+ testing.expectEqual('aXY<b>c', host.innerHTML);+ });+}+</script>++<script id="insert_text_not_in_select">+{+ // the Selection API can reach into a <select>; editing there is refused+ const host = $('#host');+ host.innerHTML = '<p>abc</p><select><option>def</option></select>';+ host.focus();+ getSelection().selectAllChildren(host.querySelector('option'));+ exec('X');+ testing.expectEqual('<p>abc</p><select><option>def</option></select>', host.innerHTML);+ getSelection().removeAllRanges();+}+</script>++<script id="insert_text_follows_selection">+{+ // Chrome focuses the host when the selection moves into it; the command+ // follows the selection either way.+ const host = $('#host');+ host.innerHTML = 'abc';+ document.activeElement.blur();+ getSelection().setBaseAndExtent(host.firstChild, 0, host.firstChild, 0);+ testing.expectEqual(true, document.queryCommandEnabled('insertText'));+ testing.expectEqual(true, exec('S'));+ testing.expectEqual('Sabc', host.innerHTML);+ getSelection().removeAllRanges();+}+</script>++<script id="insert_text_other_document">+{+ const doc = document.implementation.createHTMLDocument();+ doc.body.innerHTML = '<div contenteditable>x</div>';+ doc.getSelection?.()?.selectAllChildren(doc.body.firstChild);+ testing.expectEqual(false, doc.queryCommandSupported('insertText'));+ testing.expectEqual(false, doc.queryCommandEnabled('insertText'));+ testing.expectEqual(false, doc.execCommand('insertText', false, 'y'));+ testing.expectEqual('x', doc.body.firstChild.innerHTML);}</script>diff --git a/src/browser/webapi/Document.zig b/src/browser/webapi/Document.zigindex 6ee637fff..91d03a071 100644--- a/src/browser/webapi/Document.zig+++ b/src/browser/webapi/Document.zig@@ -46,6 +46,7 @@ const Selection = @import("Selection.zig");const Sanitizer = @import("Sanitizer.zig");const XPathResult = @import("XPathResult.zig");const XPathExpression = @import("XPathExpression.zig");+const exec_command = @import("../frame/exec_command.zig");pub const XMLDocument = @import("XMLDocument.zig");pub const HTMLDocument = @import("HTMLDocument.zig");@@ -88,6 +89,8 @@ _fonts: ?*FontFaceSet = null,_write_insertion_point: ?*Node = null,_script_created_parser: ?Parser.Streaming = null,_close_requested: bool = false,+// an execCommand is running: a nested one is refused+_exec_command_running: bool = false,_adopted_style_sheets: ?js.Object.Global = null,_selection: Selection = .{ ._rc = .init(1) },// extent() cache, keyed on style version and viewport.@@ -1434,15 +1437,21 @@ fn exitFullscreen(_: *Document, frame: *Frame) js.Promise {return frame.js.local.?.rejectPromise(.{ .type_error = "Document not in fullscreen" });}-// There's no editing pipeline or clipboard, so every execCommand command is-// unsupported. The spec's answer for that is false (or "" for the value), not-// an exception, which keeps callers on their fallbacks.-fn execCommand(_: *const Document, command: []const u8) bool {- log.info(.not_implemented, "document.execCommand", .{ .command = command });- return false;+// See frame/exec_command.zig. A null value is "" rather than "null".+fn execCommand(self: *Document, command: []const u8, _: ?bool, value: ?[]const u8) !bool {+ return exec_command.exec(self, command, value orelse "");+}++fn queryCommandSupported(self: *const Document, command: []const u8) bool {+ return exec_command.isSupported(self, command);+}++fn queryCommandEnabled(self: *Document, command: []const u8) bool {+ return exec_command.isEnabled(self, command);}-fn queryCommand(_: *const Document, _: []const u8) bool {+// No supported command has a state or value yet.+fn queryCommandState(_: *const Document, _: []const u8) bool {return false;}@@ -1913,10 +1922,10 @@ pub const JsApi = struct {pub const fullscreenElement = bridge.accessor(Document.getFullscreenElement, null, .{});pub const exitFullscreen = bridge.function(Document.exitFullscreen, .{});pub const execCommand = bridge.function(Document.execCommand, .{});- pub const queryCommandEnabled = bridge.function(Document.queryCommand, .{});- pub const queryCommandIndeterm = bridge.function(Document.queryCommand, .{});- pub const queryCommandState = bridge.function(Document.queryCommand, .{});- pub const queryCommandSupported = bridge.function(Document.queryCommand, .{});+ pub const queryCommandEnabled = bridge.function(Document.queryCommandEnabled, .{});+ pub const queryCommandIndeterm = bridge.function(Document.queryCommandState, .{});+ pub const queryCommandState = bridge.function(Document.queryCommandState, .{});+ pub const queryCommandSupported = bridge.function(Document.queryCommandSupported, .{});pub const queryCommandValue = bridge.function(Document.queryCommandValue, .{});pub const prerendering = bridge.property(false, .{ .template = false });