Lightpanda: the headless browser designed for AI and automation
webapi: input valueAsNumber, valueAsDate, stepUp/stepDown, showPicker
Adrià Arrufat396ec5fe1834
diff --git a/src/browser/tests/element/html/input-validity.html b/src/browser/tests/element/html/input-validity.htmlindex d84f38745..95fcfdbe6 100644--- a/src/browser/tests/element/html/input-validity.html+++ b/src/browser/tests/element/html/input-validity.html@@ -279,3 +279,24 @@testing.expectEqual(false, el.validity.patternMismatch);}</script>++<input id="date-low" type="date" min="2024-01-01" value="2023-12-31">+<input id="date-ok" type="date" min="2024-01-01" max="2024-12-31" value="2024-06-15">+<input id="time-high" type="time" max="17:00" value="17:30">+<input id="month-low" type="month" min="2024-02" value="2024-01">+<input id="week-ok" type="week" min="2024-W01" value="2024-W10">++<script id="date_time_ranges">+ {+ testing.expectEqual(true, $('#date-low').validity.rangeUnderflow);+ testing.expectEqual(false, $('#date-low').validity.rangeOverflow);+ 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);+ $('#date-ok').value = '2025-01-01';+ testing.expectEqual(true, $('#date-ok').validity.rangeOverflow);+ testing.expectEqual(false, $('#date-ok').checkValidity());+ }+</script>diff --git a/src/browser/tests/element/html/input-value-as.html b/src/browser/tests/element/html/input-value-as.htmlnew file mode 100644index 000000000..d224d040d--- /dev/null+++ b/src/browser/tests/element/html/input-value-as.html@@ -0,0 +1,136 @@+<!DOCTYPE html>+<script src="../../testing.js"></script>++<input id=num type=number value="2.5" min="0" max="10" step="0.5">+<input id=any type=number value="1" step="any">+<input id=date type=date value="2024-03-10">+<input id=month type=month value="2024-03">+<input id=week type=week value="2024-W10">+<input id=time type=time value="13:45:30.250">+<input id=dtl type=datetime-local value="2024-03-10T13:45">+<input id=text type=text value="x">+<input id=range type=range min="0" max="10" step="2">++<script id=valueAsNumber_get>+{+ 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));+ const empty = document.createElement('input');+ empty.type = 'date';+ testing.expectEqual(true, Number.isNaN(empty.valueAsNumber));+}+</script>++<script id=valueAsNumber_set>+{+ const date = $('#date');+ date.valueAsNumber = Date.UTC(2020, 0, 31);+ testing.expectEqual('2020-01-31', date.value);+ date.valueAsNumber = NaN;+ testing.expectEqual('', date.value);++ const time = $('#time');+ 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);++ const dtl = $('#dtl');+ dtl.valueAsNumber = Date.UTC(2024, 2, 10, 13, 45, 5);+ testing.expectEqual('2024-03-10T13:45:05', dtl.value);++ const num = $('#num');+ num.valueAsNumber = 7;+ testing.expectEqual('7', num.value);+ num.valueAsNumber = 1.5;+ testing.expectEqual('1.5', num.value);++ testing.expectError('InvalidStateError', () => { $('#text').valueAsNumber = 1; });+ testing.expectError('TypeError', () => { num.valueAsNumber = Infinity; });+}+</script>++<script id=valueAsDate>+{+ const date = $('#date');+ 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);+ testing.expectEqual(null, $('#text').valueAsDate);+ date.value = '';+ testing.expectEqual(null, date.valueAsDate);++ date.valueAsDate = new Date(Date.UTC(2022, 4, 1));+ 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(); });+}+</script>++<script id=stepUp_stepDown>+{+ const num = $('#num');+ num.value = '2.5';+ num.stepUp();+ testing.expectEqual('3', num.value);+ num.stepUp(3);+ testing.expectEqual('4.5', num.value);+ num.stepDown();+ testing.expectEqual('4', num.value);+ num.stepUp(100);+ testing.expectEqual('10', num.value);+ num.stepDown(100);+ testing.expectEqual('0', num.value);++ const date = $('#date');+ date.value = '2024-03-10';+ date.stepUp();+ testing.expectEqual('2024-03-11', date.value);+ date.stepDown(11);+ testing.expectEqual('2024-02-29', date.value);++ const time = $('#time');+ time.value = '13:45:30.250';+ time.stepUp();+ testing.expectEqual('13:46:30.25', time.value);++ const range = $('#range');+ range.stepUp();+ testing.expectEqual('8', range.value);++ testing.expectError('InvalidStateError', () => $('#any').stepUp());+ testing.expectError('InvalidStateError', () => $('#text').stepUp());+}+</script>++<script id=showPicker>+ testing.expectEqual(undefined, $('#date').showPicker());+</script>diff --git a/src/browser/webapi/element/html/Input.zig b/src/browser/webapi/element/html/Input.zigindex 88276c052..709922864 100644--- a/src/browser/webapi/element/html/Input.zig+++ b/src/browser/webapi/element/html/Input.zig@@ -442,32 +442,16 @@ pub fn suffersRangeOverflow(self: *const Input) bool {}fn numericRangeBreach(self: *const Input, comptime kind: enum { underflow, overflow }) bool {- // Only number/range use floating-point comparison. date/time/month/week/- // datetime-local also have range constraints per spec, but their values- // require type-specific conversion (date → days since epoch, time → ms- // since midnight, etc.) before comparison — not yet implemented.- // TODO: implement range checks for date/time/month/week/datetime-local.- switch (self._input_type) {- .number, .range => {},- else => return false,- }-- const value = self._value orelse return false;- if (value.len == 0) return false;- if (!isValidFloatingPoint(value)) return false;- const v = std.fmt.parseFloat(f64, value) catch return false;-- const attr = switch (kind) {+ const typ = self._input_type;+ if (!hasNumericValue(typ)) return false;+ const value = valueToNumber(typ, self.getValue()) orelse return false;+ const bound = valueToNumber(typ, switch (kind) {.underflow => self.getMin(),.overflow => self.getMax(),- };- if (attr.len == 0) return false;- if (!isValidFloatingPoint(attr)) return false;- const bound = std.fmt.parseFloat(f64, attr) catch return false;-+ }) orelse return false;return switch (kind) {- .underflow => v < bound,- .overflow => v > bound,+ .underflow => value < bound,+ .overflow => value > bound,};}@@ -803,6 +787,251 @@ fn sanitizeValue(self: *Input, comptime dupe: bool, value: []const u8, frame: *F}}+const ms_per_day: f64 = 86_400_000;+// ECMAScript time value range; beyond it Date is invalid.+const max_time_value: f64 = 8.64e15;++fn hasNumericValue(typ: Type) bool {+ return switch (typ) {+ .number, .range, .date, .month, .week, .time, .@"datetime-local" => true,+ else => false,+ };+}++pub fn getValueAsNumber(self: *const Input) f64 {+ return valueToNumber(self._input_type, self.getValue()) orelse std.math.nan(f64);+}++pub fn setValueAsNumber(self: *Input, number: f64, frame: *Frame) !void {+ if (!hasNumericValue(self._input_type)) return error.InvalidStateError;+ if (std.math.isInf(number)) return error.TypeError;+ var buf: [64]u8 = undefined;+ const text = numberToValue(self._input_type, number, &buf) orelse "";+ return self.setValue(text, frame);+}++pub fn getValueAsDate(self: *const Input, exec: *const js.Execution) !?js.Value {+ const ms = switch (self._input_type) {+ .date, .week, .time => valueToNumber(self._input_type, self.getValue()),+ .month => if (valueToNumber(.month, self.getValue())) |months| monthsToMs(months) else null,+ else => null,+ } orelse return null;+ return try exec.js.local.?.newDate(ms);+}++pub fn setValueAsDate(self: *Input, value: js.Value, frame: *Frame) !void {+ switch (self._input_type) {+ .date, .month, .week, .time => {},+ else => return error.InvalidStateError,+ }+ if (value.isNull()) return self.setValue("", frame);+ if (!value.isDate()) return error.TypeError;+ const ms = value.dateValue();+ const number = if (self._input_type == .month and !std.math.isNan(ms)) msToMonths(ms) else ms;+ return self.setValueAsNumber(number, frame);+}++pub fn stepUp(self: *Input, n_: ?i32, frame: *Frame) !void {+ return self.stepBy(n_ orelse 1, frame);+}++pub fn stepDown(self: *Input, n_: ?i32, frame: *Frame) !void {+ return self.stepBy(-(n_ orelse 1), frame);+}++fn stepBy(self: *Input, n: i32, frame: *Frame) !void {+ const typ = self._input_type;+ if (!hasNumericValue(typ)) return error.InvalidStateError;+ const step = self.allowedValueStep() orelse return error.InvalidStateError;++ // 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);+}++/// The step in value-as-number units; null for step="any".+fn allowedValueStep(self: *const Input) ?f64 {+ const typ = self._input_type;+ const attr = self.getStep();+ if (std.ascii.eqlIgnoreCase(attr, "any")) return null;+ const default: f64 = switch (typ) {+ .time, .@"datetime-local" => 60,+ else => 1,+ };+ const scale: f64 = switch (typ) {+ .date => ms_per_day,+ .week => 7 * ms_per_day,+ .time, .@"datetime-local" => 1000,+ else => 1,+ };+ const parsed = if (isValidFloatingPoint(attr)) std.fmt.parseFloat(f64, attr) catch default else default;+ 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 {+ if (value.len == 0) return null;+ switch (typ) {+ .number, .range => return if (isValidFloatingPoint(value)) std.fmt.parseFloat(f64, value) catch null else null,+ .date => {+ if (!isValidDate(value)) return null;+ return dateToDays(value) * ms_per_day;+ },+ .month => {+ if (!isValidMonth(value)) return null;+ const year: i64 = parseAllDigits(value[0 .. value.len - 3]).?;+ const month: i64 = parseAllDigits(value[value.len - 2 ..]).?;+ return @floatFromInt((year - 1970) * 12 + month - 1);+ },+ .week => {+ if (!isValidWeek(value)) return null;+ const year: i64 = parseAllDigits(value[0 .. value.len - 4]).?;+ const week: i64 = parseAllDigits(value[value.len - 2 ..]).?;+ return @as(f64, @floatFromInt(isoWeekMonday(year, week))) * ms_per_day;+ },+ .time => {+ if (!isValidTime(value)) return null;+ return timeToMs(value);+ },+ .@"datetime-local" => {+ const sep = std.mem.indexOfAny(u8, value, "T ") orelse return null;+ const date = value[0..sep];+ const time = value[sep + 1 ..];+ if (!isValidDate(date) or !isValidTime(time)) return null;+ return dateToDays(date) * ms_per_day + timeToMs(time);+ },+ else => return null,+ }+}++fn numberToValue(typ: Type, number: f64, buf: []u8) ?[]const u8 {+ if (std.math.isNan(number) or @abs(number) > max_time_value) return null;+ switch (typ) {+ .number, .range => return std.fmt.bufPrint(buf, "{d}", .{number}) catch null,+ .date => {+ const days: i64 = @floor(number / ms_per_day);+ return formatDate(civilFromDays(days), buf);+ },+ .month => {+ const months: i64 = @floor(number);+ const year = 1970 + @divFloor(months, 12);+ if (year < 1) return null;+ return std.fmt.bufPrint(buf, "{d:0>4}-{d:0>2}", .{ @as(u64, @intCast(year)), @as(u64, @intCast(@mod(months, 12) + 1)) }) catch null;+ },+ .week => {+ const days: i64 = @floor(number / ms_per_day);+ // The ISO week-year is the year of the week's Thursday.+ const thursday = days - @mod(days + 3, 7) + 3;+ const year = civilFromDays(thursday).year;+ if (year < 1) return null;+ const week = @divFloor(thursday - isoWeekMonday(year, 1), 7) + 1;+ return std.fmt.bufPrint(buf, "{d:0>4}-W{d:0>2}", .{ @as(u64, @intCast(year)), @as(u64, @intCast(week)) }) catch null;+ },+ .time => return formatTime(@mod(number, ms_per_day), buf),+ .@"datetime-local" => {+ const days: i64 = @floor(number / ms_per_day);+ const date = formatDate(civilFromDays(days), buf) orelse return null;+ buf[date.len] = 'T';+ const time = formatTime(number - @as(f64, @floatFromInt(days)) * ms_per_day, buf[date.len + 1 ..]) orelse return null;+ return buf[0 .. date.len + 1 + time.len];+ },+ else => return null,+ }+}++fn monthsToMs(months: f64) f64 {+ const m: i64 = @floor(months);+ return daysFromCivil(1970 + @divFloor(m, 12), @mod(m, 12) + 1, 1) * ms_per_day;+}++fn msToMonths(ms: f64) f64 {+ const days: i64 = @floor(ms / ms_per_day);+ const civil = civilFromDays(days);+ return @floatFromInt((civil.year - 1970) * 12 + civil.month - 1);+}++/// Days since 1970-01-01 of a valid date string (any year length).+fn dateToDays(value: []const u8) f64 {+ const year: i64 = parseAllDigits(value[0 .. value.len - 6]).?;+ const month: i64 = parseAllDigits(value[value.len - 5 .. value.len - 3]).?;+ const day: i64 = parseAllDigits(value[value.len - 2 ..]).?;+ return daysFromCivil(year, month, day);+}++/// Milliseconds since midnight of a valid time string.+fn timeToMs(value: []const u8) f64 {+ var ms: f64 = @floatFromInt(parseAllDigits(value[0..2]).? * 3_600_000 + parseAllDigits(value[3..5]).? * 60_000);+ if (value.len >= 8) ms += @floatFromInt(parseAllDigits(value[6..8]).? * 1000);+ if (value.len > 9) {+ var frac: u32 = parseAllDigits(value[9..]).?;+ var digits = value.len - 9;+ while (digits < 3) : (digits += 1) frac *= 10;+ ms += @floatFromInt(frac);+ }+ return ms;+}++const Civil = struct { year: i64, month: i64, day: i64 };++fn formatDate(civil: Civil, buf: []u8) ?[]const u8 {+ if (civil.year < 1) return null;+ 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.+fn formatTime(ms_in_day: f64, buf: []u8) ?[]const u8 {+ const total: u64 = @floor(ms_in_day);+ const hour = total / 3_600_000;+ const minute = (total / 60_000) % 60;+ const second = (total / 1000) % 60;+ const millis = total % 1000;+ if (second == 0 and millis == 0) {+ return std.fmt.bufPrint(buf, "{d:0>2}:{d:0>2}", .{ hour, minute }) catch null;+ }+ 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");+}++// Howard Hinnant's civil-from-days and days-from-civil.+fn daysFromCivil(year: i64, month: i64, day: i64) f64 {+ const y = if (month <= 2) year - 1 else year;+ const era = @divFloor(y, 400);+ const yoe = y - era * 400;+ const mp = @mod(month + 9, 12);+ const doy = @divFloor(153 * mp + 2, 5) + day - 1;+ const doe = yoe * 365 + @divFloor(yoe, 4) - @divFloor(yoe, 100) + doy;+ return @floatFromInt(era * 146_097 + doe - 719_468);+}++fn civilFromDays(days: i64) Civil {+ const z = days + 719_468;+ const era = @divFloor(z, 146_097);+ const doe = z - era * 146_097;+ const yoe = @divFloor(doe - @divFloor(doe, 1460) + @divFloor(doe, 36_524) - @divFloor(doe, 146_096), 365);+ const doy = doe - (365 * yoe + @divFloor(yoe, 4) - @divFloor(yoe, 100));+ const mp = @divFloor(5 * doy + 2, 153);+ const day = doy - @divFloor(153 * mp + 2, 5) + 1;+ const month = if (mp < 10) mp + 3 else mp - 9;+ return .{ .year = yoe + era * 400 + @intFromBool(month <= 2), .month = month, .day = day };+}++/// Days since the epoch of the Monday starting ISO week `week` of `year`.+fn isoWeekMonday(year: i64, week: i64) i64 {+ const jan4: i64 = @intFromFloat(daysFromCivil(year, 1, 4));+ return jan4 - @mod(jan4 + 3, 7) + (week - 1) * 7;+}+/// WHATWG "valid floating-point number" grammar check + overflow detection./// Rejects "+1", "1.", "Infinity", "NaN", "2e308", leading whitespace, trailing junk.fn isValidFloatingPoint(value: []const u8) bool {@@ -1195,6 +1424,11 @@ pub const JsApi = struct {pub const onselectionchange = bridge.accessor(Input.getOnSelectionChange, Input.setOnSelectionChange, .{});pub const @"type" = bridge.accessor(Input.getType, Input.setType, .{ .ce_reactions = true });pub const value = bridge.accessor(Input.getValueForJS, setValueFromJS, .{ .ce_reactions = true });+ pub const valueAsNumber = bridge.accessor(Input.getValueAsNumber, Input.setValueAsNumber, .{});+ 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, .{});@@ -1341,6 +1575,7 @@ test "WebApi: HTML.Input" {try testing.htmlRunner("element/html/input-attrs.html", .{});try testing.htmlRunner("element/html/input-validity.html", .{});try testing.htmlRunner("element/html/input_file.html", .{});+ try testing.htmlRunner("element/html/input-value-as.html", .{});}test "isValidFloatingPoint" {