Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: match browsers for step, time strings, empty patterns and tooLong

Adrià Arrufat20ac0baa99f6
diff --git a/src/browser/tests/element/html/input-validity.html b/src/browser/tests/element/html/input-validity.html
index 95fcfdbe6..5fb153d72 100644
--- a/src/browser/tests/element/html/input-validity.html
+++ b/src/browser/tests/element/html/input-validity.html
@@ -81,10 +81,11 @@
<script id="too_long">
{
const el = $('#too-long');
- // Pristine value (default) does not trigger tooLong per spec
+ // Only values last changed by a user edit count, so neither the attribute
+ // nor a script-set value ever trips tooLong.
testing.expectEqual(false, el.validity.tooLong);
el.value = 'abcdef';
- testing.expectEqual(true, el.validity.tooLong);
+ testing.expectEqual(false, el.validity.tooLong);
el.value = 'ab';
testing.expectEqual(false, el.validity.tooLong);
}
@@ -151,9 +152,10 @@
<script id="validation_message">
{
- testing.expectEqual('Please fill out this field.', $('#empty-required').validationMessage);
- testing.expectEqual('Please enter an email address.', $('#bad-email').validationMessage);
- testing.expectEqual('Value is too small.', $('#too-low').validationMessage);
+ // The wording is browser-specific; only presence is checked.
+ testing.expectEqual(true, $('#empty-required').validationMessage.length > 0);
+ testing.expectEqual(true, $('#bad-email').validationMessage.length > 0);
+ testing.expectEqual(true, $('#too-low').validationMessage.length > 0);
testing.expectEqual('', $('#filled-required').validationMessage);
// Disabled returns empty
testing.expectEqual('', $('#disabled-required').validationMessage);
@@ -177,7 +179,8 @@
testing.expectEqual(-1, $('#filled-required').maxLength);
testing.expectEqual(3, $('#too-short').minLength);
testing.expectEqual(-1, $('#filled-required').minLength);
- testing.expectEqual(true, $('#too-short').validity.tooShort);
+ // Attribute values are not user edits.
+ testing.expectEqual(false, $('#too-short').validity.tooShort);
const el = $('#filled-required');
el.minLength = 2;
@@ -211,6 +214,8 @@
testing.expectEqual('foo', el.pattern);
el.pattern = '';
testing.expectEqual('', el.getAttribute('pattern'));
+ el.removeAttribute('pattern');
+ testing.expectEqual('', el.pattern);
}
</script>
@@ -277,6 +282,11 @@
testing.expectEqual(true, el.validity.patternMismatch);
el.value = '42';
testing.expectEqual(false, el.validity.patternMismatch);
+ // An empty pattern compiles to ^(?:)$ and matches only the empty string.
+ el.pattern = '';
+ testing.expectEqual(true, el.validity.patternMismatch);
+ el.removeAttribute('pattern');
+ testing.expectEqual(false, el.validity.patternMismatch);
}
</script>
@@ -293,8 +303,11 @@
testing.expectEqual(false, $('#date-ok').validity.rangeUnderflow);
testing.expectEqual(false, $('#date-ok').validity.rangeOverflow);
testing.expectEqual(true, $('#time-high').validity.rangeOverflow);
- testing.expectEqual(true, $('#month-low').validity.rangeUnderflow);
- testing.expectEqual(false, $('#week-ok').validity.rangeUnderflow);
+ // Firefox has no month/week inputs; they fall back to text there.
+ if ($('#month-low').type === 'month') {
+ testing.expectEqual(true, $('#month-low').validity.rangeUnderflow);
+ testing.expectEqual(false, $('#week-ok').validity.rangeUnderflow);
+ }
$('#date-ok').value = '2025-01-01';
testing.expectEqual(true, $('#date-ok').validity.rangeOverflow);
testing.expectEqual(false, $('#date-ok').checkValidity());
diff --git a/src/browser/tests/element/html/input-value-as.html b/src/browser/tests/element/html/input-value-as.html
index d224d040d..fafaa9741 100644
--- a/src/browser/tests/element/html/input-value-as.html
+++ b/src/browser/tests/element/html/input-value-as.html
@@ -15,11 +15,14 @@
{
testing.expectEqual(2.5, $('#num').valueAsNumber);
testing.expectEqual(Date.UTC(2024, 2, 10), $('#date').valueAsNumber);
- testing.expectEqual(650, $('#month').valueAsNumber);
- testing.expectEqual(Date.UTC(2024, 2, 4), $('#week').valueAsNumber);
testing.expectEqual(49530250, $('#time').valueAsNumber);
testing.expectEqual(Date.UTC(2024, 2, 10, 13, 45), $('#dtl').valueAsNumber);
testing.expectEqual(true, Number.isNaN($('#text').valueAsNumber));
+ // Firefox has no month/week inputs; they fall back to text there.
+ if ($('#month').type === 'month') {
+ testing.expectEqual(650, $('#month').valueAsNumber);
+ testing.expectEqual(Date.UTC(2024, 2, 4), $('#week').valueAsNumber);
+ }
const empty = document.createElement('input');
empty.type = 'date';
testing.expectEqual(true, Number.isNaN(empty.valueAsNumber));
@@ -38,19 +41,21 @@
time.valueAsNumber = 3600000;
testing.expectEqual('01:00', time.value);
time.valueAsNumber = 3661500;
- testing.expectEqual('01:01:01.5', time.value);
-
- const month = $('#month');
- month.valueAsNumber = 0;
- testing.expectEqual('1970-01', month.value);
- month.valueAsNumber = 13;
- testing.expectEqual('1971-02', month.value);
-
- const week = $('#week');
- week.valueAsNumber = Date.UTC(2021, 0, 4);
- testing.expectEqual('2021-W01', week.value);
- week.valueAsNumber = Date.UTC(2020, 11, 31);
- testing.expectEqual('2020-W53', week.value);
+ testing.expectEqual('01:01:01.500', time.value);
+
+ if ($('#month').type === 'month') {
+ const month = $('#month');
+ month.valueAsNumber = 0;
+ testing.expectEqual('1970-01', month.value);
+ month.valueAsNumber = 13;
+ testing.expectEqual('1971-02', month.value);
+
+ const week = $('#week');
+ week.valueAsNumber = Date.UTC(2021, 0, 4);
+ testing.expectEqual('2021-W01', week.value);
+ week.valueAsNumber = Date.UTC(2020, 11, 31);
+ testing.expectEqual('2020-W53', week.value);
+ }
const dtl = $('#dtl');
dtl.valueAsNumber = Date.UTC(2024, 2, 10, 13, 45, 5);
@@ -73,10 +78,6 @@
date.value = '2024-03-10';
testing.expectEqual(true, date.valueAsDate instanceof Date);
testing.expectEqual(Date.UTC(2024, 2, 10), date.valueAsDate.getTime());
- $('#month').value = '2024-03';
- testing.expectEqual(Date.UTC(2024, 2, 1), $('#month').valueAsDate.getTime());
- $('#week').value = '2024-W10';
- testing.expectEqual(Date.UTC(2024, 2, 4), $('#week').valueAsDate.getTime());
$('#time').value = '13:45:30.250';
testing.expectEqual(49530250, $('#time').valueAsDate.getTime());
testing.expectEqual(null, $('#num').valueAsDate);
@@ -88,10 +89,17 @@
testing.expectEqual('2022-05-01', date.value);
date.valueAsDate = null;
testing.expectEqual('', date.value);
- $('#month').valueAsDate = new Date(Date.UTC(1999, 11, 31));
- testing.expectEqual('1999-12', $('#month').value);
testing.expectError('TypeError', () => { date.valueAsDate = 'x'; });
testing.expectError('InvalidStateError', () => { $('#num').valueAsDate = new Date(); });
+
+ if ($('#month').type === 'month') {
+ $('#month').value = '2024-03';
+ testing.expectEqual(Date.UTC(2024, 2, 1), $('#month').valueAsDate.getTime());
+ $('#week').value = '2024-W10';
+ testing.expectEqual(Date.UTC(2024, 2, 4), $('#week').valueAsDate.getTime());
+ $('#month').valueAsDate = new Date(Date.UTC(1999, 11, 31));
+ testing.expectEqual('1999-12', $('#month').value);
+ }
}
</script>
@@ -105,11 +113,26 @@
testing.expectEqual('4.5', num.value);
num.stepDown();
testing.expectEqual('4', num.value);
+ // Clamped to the last rung within max/min.
num.stepUp(100);
testing.expectEqual('10', num.value);
num.stepDown(100);
testing.expectEqual('0', num.value);
+ // Off the ladder: the snap to the next rung counts as the first step.
+ num.value = '2.7';
+ num.stepUp(5);
+ testing.expectEqual('5', num.value);
+ num.value = '2.7';
+ num.stepUp();
+ testing.expectEqual('3', num.value);
+ num.value = '2.7';
+ num.stepDown();
+ testing.expectEqual('2.5', num.value);
+ num.value = '2.7';
+ num.stepDown(3);
+ testing.expectEqual('1.5', num.value);
+ // No min: the value attribute is the step base.
const date = $('#date');
date.value = '2024-03-10';
date.stepUp();
@@ -120,7 +143,10 @@
const time = $('#time');
time.value = '13:45:30.250';
time.stepUp();
- testing.expectEqual('13:46:30.25', time.value);
+ testing.expectEqual('13:46:30.250', time.value);
+ time.value = '13:45';
+ time.stepUp();
+ testing.expectEqual('13:45:30.250', time.value);
const range = $('#range');
range.stepUp();
@@ -130,7 +156,3 @@
testing.expectError('InvalidStateError', () => $('#text').stepUp());
}
</script>
-
-<script id=showPicker>
- testing.expectEqual(undefined, $('#date').showPicker());
-</script>
diff --git a/src/browser/tests/element/html/textarea-validity.html b/src/browser/tests/element/html/textarea-validity.html
index 7f2a5e0e0..9754b9bec 100644
--- a/src/browser/tests/element/html/textarea-validity.html
+++ b/src/browser/tests/element/html/textarea-validity.html
@@ -28,9 +28,10 @@
<script id="too_long">
{
const t = $('#too-long');
+ // Only values last changed by a user edit count; script-set values don't.
testing.expectEqual(false, t.validity.tooLong);
t.value = 'abcdef';
- testing.expectEqual(true, t.validity.tooLong);
+ testing.expectEqual(false, t.validity.tooLong);
t.value = 'ab';
testing.expectEqual(false, t.validity.tooLong);
}
@@ -42,7 +43,7 @@
// empty value never triggers tooShort
testing.expectEqual(false, t.validity.tooShort);
t.value = 'ab';
- testing.expectEqual(true, t.validity.tooShort);
+ testing.expectEqual(false, t.validity.tooShort);
t.value = 'abcde';
testing.expectEqual(false, t.validity.tooShort);
}
diff --git a/src/browser/webapi/element/html/Input.zig b/src/browser/webapi/element/html/Input.zig
index 709922864..1497f48a2 100644
--- a/src/browser/webapi/element/html/Input.zig
+++ b/src/browser/webapi/element/html/Input.zig
@@ -88,6 +88,8 @@ _default_checked: bool = false,
_value: ?[]const u8 = null,
_checked: bool = false,
_checked_dirty: bool = false,
+// Only user edits count for tooLong/tooShort; script and attribute values don't.
+_user_edited: bool = false,
_input_type: Type = .text,
_indeterminate: bool = false,
_custom_validity: ?[]const u8 = null,
@@ -156,6 +158,12 @@ pub fn setValue(self: *Input, value: []const u8, frame: *Frame) !void {
}
// This should _not_ call setAttribute. It updates the current state only
self._value = try self.sanitizeValue(true, value, frame);
+ self._user_edited = false;
+}
+
+pub fn setUserValue(self: *Input, value: []const u8, frame: *Frame) !void {
+ try self.setValue(value, frame);
+ self._user_edited = true;
}
pub fn getDefaultValue(self: *const Input) []const u8 {
@@ -393,8 +401,8 @@ pub fn suffersPatternMismatch(self: *const Input, frame: *Frame) bool {
}
const value = self._value orelse return false;
if (value.len == 0) return false;
+ // An empty pattern is still a pattern: ^(?:)$ matches only "".
const pattern = self.asConstElement().getAttributeSafe(comptime .wrap("pattern")) orelse return false;
- if (pattern.len == 0) return false;
// Per HTML spec, anchor the pattern with ^(?:...)$ and compile under the
// "v" (Unicode sets) flag. An invalid pattern is ignored — V8 throws and
@@ -416,9 +424,7 @@ pub fn suffersPatternMismatch(self: *const Input, frame: *Frame) bool {
}
pub fn suffersTooLong(self: *const Input) bool {
- // Per spec, only the dirty value flag triggers tooLong / tooShort. We treat
- // the presence of an explicit _value (vs. attribute-derived _default_value)
- // as an approximation of dirty.
+ if (!self._user_edited) return false;
const value = self._value orelse return false;
const max = self.getMaxLength();
if (max < 0) return false;
@@ -426,6 +432,7 @@ pub fn suffersTooLong(self: *const Input) bool {
}
pub fn suffersTooShort(self: *const Input) bool {
+ if (!self._user_edited) return false;
const value = self._value orelse return false;
if (value.len == 0) return false;
const min = self.getMinLength();
@@ -846,10 +853,34 @@ fn stepBy(self: *Input, n: i32, frame: *Frame) !void {
// A range with no value sits at its sanitized default, not at 0.
const current = try self.sanitizeValue(false, self.getValue(), frame);
- var next = (valueToNumber(typ, current) orelse 0) + @as(f64, @floatFromInt(n)) * step;
- if (valueToNumber(typ, self.getMin())) |min| next = @max(next, min);
- if (valueToNumber(typ, self.getMax())) |max| next = @min(next, max);
- return self.setValueAsNumber(next, frame);
+ const before = valueToNumber(typ, current) orelse 0;
+ if (n == 0) return;
+ const base = self.stepBase();
+ const rungs = (before - base) / step;
+ const steps: f64 = @floatFromInt(n);
+ var value = if (@abs(rungs - @round(rungs)) > 1e-9)
+ // Off the ladder: the snap to the next rung counts as the first step
+ // (what browsers do; the spec text ignores n here).
+ base + (if (n < 0) @floor(rungs) + steps + 1 else @ceil(rungs) + steps - 1) * step
+ else
+ before + steps * step;
+ if (valueToNumber(typ, self.getMin())) |min| {
+ if (value < min) value = base + @ceil((min - base) / step - 1e-9) * step;
+ }
+ if (valueToNumber(typ, self.getMax())) |max| {
+ if (value > max) value = base + @floor((max - base) / step + 1e-9) * step;
+ }
+ // Clamping never moves against the direction of travel.
+ if ((n < 0 and value > before) or (n > 0 and value < before)) return;
+ return self.setValueAsNumber(value, frame);
+}
+
+/// HTML "step base": min, else the value content attribute, else the type's default.
+fn stepBase(self: *const Input) f64 {
+ const typ = self._input_type;
+ if (valueToNumber(typ, self.getMin())) |min| return min;
+ if (valueToNumber(typ, self.asConstElement().getAttributeSafe(comptime .wrap("value")) orelse "")) |v| return v;
+ return if (typ == .week) -259_200_000 else 0;
}
/// The step in value-as-number units; null for step="any".
@@ -871,10 +902,6 @@ fn allowedValueStep(self: *const Input) ?f64 {
return (if (parsed > 0) parsed else default) * scale;
}
-pub fn showPicker(_: *const Input) void {
- lp.log.debug(.not_implemented, "Input.showPicker", .{});
-}
-
/// HTML "value as number": floats for number/range; for the date types,
/// milliseconds (months for type=month) since the epoch or midnight.
fn valueToNumber(typ: Type, value: []const u8) ?f64 {
@@ -986,7 +1013,7 @@ fn formatDate(civil: Civil, buf: []u8) ?[]const u8 {
return std.fmt.bufPrint(buf, "{d:0>4}-{d:0>2}-{d:0>2}", .{ @as(u64, @intCast(civil.year)), @as(u64, @intCast(civil.month)), @as(u64, @intCast(civil.day)) }) catch null;
}
-/// Shortest valid time string: seconds and fraction only when non-zero.
+/// Normalized time string: seconds only when needed, fraction always 3 digits.
fn formatTime(ms_in_day: f64, buf: []u8) ?[]const u8 {
const total: u64 = @floor(ms_in_day);
const hour = total / 3_600_000;
@@ -999,8 +1026,7 @@ fn formatTime(ms_in_day: f64, buf: []u8) ?[]const u8 {
if (millis == 0) {
return std.fmt.bufPrint(buf, "{d:0>2}:{d:0>2}:{d:0>2}", .{ hour, minute, second }) catch null;
}
- const text = std.fmt.bufPrint(buf, "{d:0>2}:{d:0>2}:{d:0>2}.{d:0>3}", .{ hour, minute, second, millis }) catch return null;
- return std.mem.trimEnd(u8, text, "0");
+ return std.fmt.bufPrint(buf, "{d:0>2}:{d:0>2}:{d:0>2}.{d:0>3}", .{ hour, minute, second, millis }) catch null;
}
// Howard Hinnant's civil-from-days and days-from-civil.
@@ -1428,7 +1454,6 @@ pub const JsApi = struct {
pub const valueAsDate = bridge.accessor(Input.getValueAsDate, Input.setValueAsDate, .{});
pub const stepUp = bridge.function(Input.stepUp, .{});
pub const stepDown = bridge.function(Input.stepDown, .{});
- pub const showPicker = bridge.function(Input.showPicker, .{});
pub const files = bridge.accessor(Input.getFiles, Input.setFiles, .{});
pub const defaultValue = bridge.accessor(Input.getDefaultValue, Input.setDefaultValue, .{ .ce_reactions = true });
pub const checked = bridge.accessor(Input.getChecked, Input.setChecked, .{});
@@ -1559,6 +1584,7 @@ pub const Build = struct {
clone._value = source._value;
clone._checked = source._checked;
clone._checked_dirty = source._checked_dirty;
+ clone._user_edited = source._user_edited;
clone._selection_direction = source._selection_direction;
clone._selection_start = source._selection_start;
clone._selection_end = source._selection_end;
diff --git a/src/browser/webapi/element/html/TextArea.zig b/src/browser/webapi/element/html/TextArea.zig
index 4e596fa3a..7e1688ec2 100644
--- a/src/browser/webapi/element/html/TextArea.zig
+++ b/src/browser/webapi/element/html/TextArea.zig
@@ -38,6 +38,8 @@ pub const Proto = HtmlElement;
_proto_canary: if (lp.IS_DEBUG) *HtmlElement else void = undefined,
_value: ?[]const u8 = null,
+// Only user edits count for tooLong/tooShort; script and attribute values don't.
+_user_edited: bool = false,
_selection_start: u32 = 0,
_selection_end: u32 = 0,
@@ -79,6 +81,12 @@ pub fn getValue(self: *const TextArea) []const u8 {
pub fn setValue(self: *TextArea, value: []const u8, frame: *Frame) !void {
const owned = try frame.arena.dupe(u8, value);
self._value = owned;
+ self._user_edited = false;
+}
+
+pub fn setUserValue(self: *TextArea, value: []const u8, frame: *Frame) !void {
+ try self.setValue(value, frame);
+ self._user_edited = true;
}
pub fn getDefaultValue(self: *const TextArea) []const u8 {
@@ -221,6 +229,7 @@ pub fn suffersValueMissing(self: *const TextArea) bool {
}
pub fn suffersTooLong(self: *const TextArea) bool {
+ if (!self._user_edited) return false;
const value = self._value orelse return false;
const max = self.getMaxLength();
if (max < 0) return false;
@@ -229,6 +238,7 @@ pub fn suffersTooLong(self: *const TextArea) bool {
}
pub fn suffersTooShort(self: *const TextArea) bool {
+ if (!self._user_edited) return false;
const value = self._value orelse return false;
if (value.len == 0) return false;
const min = self.getMinLength();
diff --git a/src/browser/webapi/element/text_entry.zig b/src/browser/webapi/element/text_entry.zig
index e87aa8e28..096b0b210 100644
--- a/src/browser/webapi/element/text_entry.zig
+++ b/src/browser/webapi/element/text_entry.zig
@@ -43,7 +43,7 @@ pub fn TextEntry(comptime T: type) type {
.full => {
// fully selected, replace the content.
const new_value = try arena.dupe(u8, str);
- try self.setValue(new_value, frame);
+ try self.setUserValue(new_value, frame);
self._selection_start = @intCast(new_value.len);
self._selection_end = @intCast(new_value.len);
self._selection_direction = .none;
@@ -60,7 +60,7 @@ pub fn TextEntry(comptime T: type) type {
u8,
&.{ before, str, remaining },
);
- try self.setValue(new_value, frame);
+ try self.setUserValue(new_value, frame);
const new_pos = range[0] + str.len;
self._selection_start = @intCast(new_pos);
@@ -72,7 +72,7 @@ pub fn TextEntry(comptime T: type) type {
// nothing selected, just insert at cursor.
const current_value = self.getValue();
const new_value = try std.mem.concat(arena, u8, &.{ current_value, str });
- try self.setValue(new_value, frame);
+ try self.setUserValue(new_value, frame);
},
}
try dispatchInputEvent(self, str, "insertText", frame);
@@ -120,7 +120,7 @@ pub fn TextEntry(comptime T: type) type {
current_value[0..start],
current_value[@min(end, value_len)..],
});
- try self.setValue(new_value, frame);
+ try self.setUserValue(new_value, frame);
self._selection_start = start;
self._selection_end = start;
self._selection_direction = .none;
diff --git a/src/server/cdp/domains/input.zig b/src/server/cdp/domains/input.zig
index a71b80d51..1f3c0c15e 100644
--- a/src/server/cdp/domains/input.zig
+++ b/src/server/cdp/domains/input.zig
@@ -150,6 +150,36 @@ fn insertText(cmd: *CDP.Command) !void {
const lp = @import("lightpanda");
const testing = @import("../testing.zig");
+test "cdp.input: insertText is a user edit for tooLong" {
+ var ctx = try testing.context();
+ defer ctx.deinit();
+
+ const bc = try ctx.loadBrowserContext(.{});
+ const page = try bc.session.createPage();
+ const frame = page.frame().?;
+
+ try frame.navigate("http://localhost:9582/src/browser/tests/mcp_actions.html", .{ .reason = .address_bar, .kind = .{ .push = null } });
+ try testing.waitForPage(bc);
+
+ var ls: lp.js.Local.Scope = undefined;
+ frame.js.localScope(&ls);
+ defer ls.deinit();
+
+ _ = try ls.local.compileAndRun(
+ \\const inp = document.getElementById('inp');
+ \\inp.maxLength = 3;
+ \\inp.value = 'abcdef';
+ \\inp.focus();
+ , null);
+ try testing.expect((try ls.local.compileAndRun("inp.validity.tooLong === false", null)).isTrue());
+
+ try ctx.processMessage(.{ .id = 1, .method = "Input.insertText", .params = .{ .text = "g" } });
+ try testing.expect((try ls.local.compileAndRun("inp.value === 'abcdefg' && inp.validity.tooLong === true", null)).isTrue());
+
+ _ = try ls.local.compileAndRun("inp.value = 'abcdefgh'", null);
+ try testing.expect((try ls.local.compileAndRun("inp.validity.tooLong === false", null)).isTrue());
+}
+
test "cdp.input: dispatchMouseEvent mouseMoved fires hover events" {
var ctx = try testing.context();
defer ctx.deinit();