Skip to content

Truly independent web browser

LibWeb: Accept any CSS color as the value of input type=color

Andreas Klingf08a0ec370be
diff --git a/Libraries/LibWeb/HTML/AttributeNames.h b/Libraries/LibWeb/HTML/AttributeNames.h
index 0d86d5fe077..f38879c43e5 100644
--- a/Libraries/LibWeb/HTML/AttributeNames.h
+++ b/Libraries/LibWeb/HTML/AttributeNames.h
@@ -22,6 +22,7 @@ namespace AttributeNames {
__ENUMERATE_HTML_ATTRIBUTE(alink, "alink") \
__ENUMERATE_HTML_ATTRIBUTE(allow, "allow") \
__ENUMERATE_HTML_ATTRIBUTE(allowfullscreen, "allowfullscreen") \
+ __ENUMERATE_HTML_ATTRIBUTE(alpha, "alpha") \
__ENUMERATE_HTML_ATTRIBUTE(alt, "alt") \
__ENUMERATE_HTML_ATTRIBUTE(archive, "archive") \
__ENUMERATE_HTML_ATTRIBUTE(as, "as") \
@@ -53,6 +54,7 @@ namespace AttributeNames {
__ENUMERATE_HTML_ATTRIBUTE(codebase, "codebase") \
__ENUMERATE_HTML_ATTRIBUTE(codetype, "codetype") \
__ENUMERATE_HTML_ATTRIBUTE(color, "color") \
+ __ENUMERATE_HTML_ATTRIBUTE(colorspace, "colorspace") \
__ENUMERATE_HTML_ATTRIBUTE(cols, "cols") \
__ENUMERATE_HTML_ATTRIBUTE(colspan, "colspan") \
__ENUMERATE_HTML_ATTRIBUTE(command, "command") \
diff --git a/Libraries/LibWeb/HTML/HTMLInputElement.cpp b/Libraries/LibWeb/HTML/HTMLInputElement.cpp
index a0f921ff7ce..00454a897dc 100644
--- a/Libraries/LibWeb/HTML/HTMLInputElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLInputElement.cpp
@@ -29,9 +29,11 @@
#include <LibWeb/CSS/PropertyID.h>
#include <LibWeb/CSS/SelectorMatching.h>
#include <LibWeb/CSS/StyleEngineInput.h>
+#include <LibWeb/CSS/StyleValues/ColorFunctionStyleValue.h>
#include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>
#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
+#include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/ElementFactory.h>
#include <LibWeb/DOM/Event.h>
@@ -446,7 +448,7 @@ static void show_the_picker_if_applicable(HTMLInputElement& element)
if (element.type_state() == HTMLInputElement::TypeAttributeState::Color) {
auto weak_element = GC::Weak<HTMLInputElement> { element };
element.set_is_open(true);
- element.document().page().did_request_color_picker(weak_element, Color::from_utf16_string(element.value()).value_or(Color(0, 0, 0)));
+ element.document().page().did_request_color_picker(weak_element, element.value_as_color());
}
}
}
@@ -579,8 +581,8 @@ void HTMLInputElement::did_pick_color(Optional<Color> picked_color, ColorPickerU
{
if (type_state() == TypeAttributeState::Color && picked_color.has_value()) {
// then when the user changes the element's value
- m_value = value_sanitization_algorithm(picked_color->to_utf16_string_without_alpha());
m_dirty_value = true;
+ m_value = value_sanitization_algorithm(picked_color->to_utf16_string_without_alpha());
update_color_well_element();
@@ -1659,6 +1661,18 @@ void HTMLInputElement::form_associated_element_attribute_changed(Utf16FlyString
update_shadow_tree();
}
+ } else if (name == HTML::AttributeNames::alpha || name == HTML::AttributeNames::colorspace) {
+ // https://html.spec.whatwg.org/multipage/input.html#color-state-(type=color)
+ // Whenever the element's alpha or colorspace attributes are changed, the user agent must run update a color
+ // well control color given the element.
+ if (type_state() == TypeAttributeState::Color) {
+ auto old_value = move(m_value);
+ m_value = update_a_color_well_control_color(old_value);
+ if (m_value != old_value) {
+ relevant_value_was_changed();
+ update_color_well_element();
+ }
+ }
} else if (name == HTML::AttributeNames::placeholder) {
if (m_placeholder_text_node) {
m_placeholder_text_node->set_data(placeholder());
@@ -1930,21 +1944,157 @@ bool HTMLInputElement::can_have_text_editing_cursor() const
return true;
}
-// https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-simple-colour
-static bool is_valid_simple_color(Utf16View const& value)
+// https://drafts.csswg.org/css-color/#parse-a-css-color-value
+static RefPtr<CSS::StyleValue const> parse_a_css_color_value(Utf16View input)
{
- // if it is exactly seven characters long,
- if (value.length_in_code_units() != 7)
- return false;
- // and the first character is a U+0023 NUMBER SIGN character (#),
- if (!value.starts_with('#'))
- return false;
- // and the remaining six characters are all ASCII hex digits
- for (size_t i = 1; i < value.length_in_code_units(); i++)
- if (!is_ascii_hex_digit(value.code_unit_at(i)))
- return false;
+ // 1. Parse input as a <color>. If the result is failure, return failure; otherwise, let color be the result.
+ auto color = parse_css_type(CSS::Parser::ParsingParams {}, input, CSS::ValueType::Color);
+ if (!color)
+ return nullptr;
- return true;
+ // 3. Let used color be the result of resolving color to a used color. If the value of other properties on the
+ // element a <color> is on is required to do the resolution (such as resolving a 'currentcolor' or system
+ // color), use element if it was passed, or the initial values of the properties if not.
+ // 4. Return used color.
+ // NB: The used color is resolved against the initial values when it is converted to a color space.
+ return color;
+}
+
+// NB: Resolves color to a used color against the initial values of the properties, and converts it to the color
+// space of color_type.
+static Array<float, 4> used_color_components_in_color_space(CSS::StyleValue const& color, CSS::ColorStyleValue::ColorType color_type)
+{
+ auto resolved = CSS::StyleValueFFI::rust_style_value_to_color_components(color.rust_style_value_data(), nullptr, to_underlying(color_type));
+ if (!resolved.resolved)
+ return { 0, 0, 0, 1 };
+
+ // NB: Converting a color with infinite components to another color space can produce infinite or NaN
+ // components, which serialize to strings that do not parse as a color. Keep the components finite.
+ Array<float, 4> components;
+ for (size_t i = 0; i < components.size(); ++i) {
+ auto component = resolved.components[i];
+ components[i] = isnan(component) ? 0.0f : clamp(component, NumericLimits<float>::lowest(), NumericLimits<float>::max());
+ }
+ return components;
+}
+
+Color HTMLInputElement::value_as_color() const
+{
+ auto color = parse_a_css_color_value(m_value);
+ if (!color)
+ return Color::Black;
+ return color->to_color({}).value_or(Color::Black);
+}
+
+// https://html.spec.whatwg.org/multipage/input.html#update-a-color-well-control-color
+// NB: This returns the string that the element's value is set to, as the value sanitization algorithm does.
+// Callers that are about to set the element's value to element_value pass it, as the value sanitization
+// algorithm runs before the new value is stored.
+Utf16String HTMLInputElement::update_a_color_well_control_color(Utf16View element_value) const
+{
+ // 1. Assert: element is an input element whose type attribute is in the Color state.
+ VERIFY(type_state() == TypeAttributeState::Color);
+
+ // 2. Let value be the result of running these steps:
+ auto value = [&] {
+ // 1. If element's dirty value flag is false, then return the result of getting an attribute by namespace and
+ // local name given null, "value", and element.
+ if (!m_dirty_value)
+ return get_attribute_value(AttributeNames::value);
+
+ // 2. Return element's value.
+ return Utf16String::from_utf16(element_value);
+ }();
+
+ // 3. Let color be the result of parsing value.
+ auto color = parse_a_css_color_value(value);
+
+ // 4. If color is failure, then set color to opaque black.
+ if (!color)
+ color = CSS::ColorStyleValue::create_from_color(Color::Black, CSS::ColorSyntax::Legacy);
+
+ // 5. Set element's value to the result of serializing a color well control color given element and color.
+ return serialize_a_color_well_control_color(*color);
+}
+
+// https://html.spec.whatwg.org/multipage/input.html#attr-input-colorspace
+HTMLInputElement::ColorSpaceState HTMLInputElement::color_space_state() const
+{
+ // The attribute's missing value default and invalid value default are both the Limited sRGB state.
+ if (auto value = attribute(AttributeNames::colorspace); value.has_value() && value->equals_ignoring_ascii_case(u"display-p3"sv))
+ return ColorSpaceState::DisplayP3;
+ return ColorSpaceState::LimitedSRGB;
+}
+
+// https://html.spec.whatwg.org/multipage/input.html#serialize-a-color-well-control-color
+Utf16String HTMLInputElement::serialize_a_color_well_control_color(CSS::StyleValue const& color) const
+{
+ // 1. Assert: element is an input element whose type attribute is in the Color state.
+ VERIFY(type_state() == TypeAttributeState::Color);
+
+ // 2. Let htmlCompatible be false.
+ bool html_compatible = false;
+
+ // 3. If element's alpha attribute is not specified, then set color's alpha component to be fully opaque.
+ // NB: Converting color to another color space keeps its alpha component, so this is applied as part of the
+ // conversion below.
+ auto has_alpha_attribute = has_attribute(AttributeNames::alpha);
+ auto convert_color = [&](CSS::ColorStyleValue::ColorType color_type) {
+ auto components = used_color_components_in_color_space(color, color_type);
+ if (!has_alpha_attribute)
+ components[3] = 1.0f;
+ return components;
+ };
+
+ Array<float, 4> components;
+ CSS::ColorStyleValue::ColorType color_type;
+
+ // 4. If element's colorspace attribute is in the Limited sRGB state:
+ if (color_space_state() == ColorSpaceState::LimitedSRGB) {
+ // 1. Set color to color converted to the 'srgb' color space.
+ color_type = CSS::ColorStyleValue::ColorType::sRGB;
+ components = convert_color(color_type);
+
+ // 2. Round each of color's components so they are in the range 0 to 255, inclusive. Components are to be
+ // rounded towards +∞.
+ for (auto& component : components)
+ component = floorf(clamp(component * 255.0f, 0.0f, 255.0f) + 0.5f);
+
+ // 3. If element's alpha attribute is not specified, then set htmlCompatible to true.
+ if (!has_alpha_attribute) {
+ html_compatible = true;
+ }
+ // NOTE: This intentionally uses a different serialization path for compatibility with an earlier version of
+ // the color well control.
+ // 4. Otherwise, set color to color converted using the 'color()' function.
+ else {
+ for (auto& component : components)
+ component /= 255.0f;
+ }
+ }
+ // Otherwise:
+ else {
+ // 1. Assert: element's colorspace attribute is in the Display P3 state.
+ VERIFY(color_space_state() == ColorSpaceState::DisplayP3);
+
+ // 2. Set color to color converted to the 'display-p3' color space.
+ color_type = CSS::ColorStyleValue::ColorType::DisplayP3;
+ components = convert_color(color_type);
+ }
+
+ // 5. Return the result of serializing color. If htmlCompatible is true, then do so with HTML-compatible
+ // serialization requested.
+ // https://drafts.csswg.org/css-color-4/#HTML-compatible-serialization-of-srgb
+ if (html_compatible)
+ return Utf16String::formatted("#{:02x}{:02x}{:02x}", static_cast<u8>(components[0]), static_cast<u8>(components[1]), static_cast<u8>(components[2]));
+
+ auto serialized_color = CSS::ColorFunctionStyleValue::create(
+ color_type,
+ CSS::NumberStyleValue::create(components[0]),
+ CSS::NumberStyleValue::create(components[1]),
+ CSS::NumberStyleValue::create(components[2]),
+ CSS::NumberStyleValue::create(components[3]));
+ return serialized_color->to_utf16_string(CSS::SerializationMode::Normal);
}
// https://html.spec.whatwg.org/multipage/input.html#value-sanitization-algorithm
@@ -2106,11 +2256,8 @@ Utf16String HTMLInputElement::value_sanitization_algorithm(Utf16View value) cons
}
// https://html.spec.whatwg.org/multipage/input.html#color-state-(type=color):value-sanitization-algorithm
else if (type_state() == HTMLInputElement::TypeAttributeState::Color) {
- // If the value of the element is a valid simple color, then set it to the value of the element converted to
- // ASCII lowercase; otherwise, set it to the string "#000000".
- if (is_valid_simple_color(value))
- return value.to_ascii_lowercase();
- return "#000000"_utf16;
+ // Run update a color well control color for the element.
+ return update_a_color_well_control_color(value);
}
return Utf16String::from_utf16(value);
@@ -4027,7 +4174,7 @@ bool HTMLInputElement::suffering_from_bad_input() const
case TypeAttributeState::Color:
// https://html.spec.whatwg.org/multipage/input.html#color-state-(type%3Dcolor)%3Asuffering-from-bad-input
// While the element's value is not the empty string and parsing it returns failure, the control is suffering from bad input.
- return !relevant_value.is_empty() && !is_valid_simple_color(relevant_value);
+ return !relevant_value.is_empty() && !parse_a_css_color_value(relevant_value);
default:
break;
}
diff --git a/Libraries/LibWeb/HTML/HTMLInputElement.h b/Libraries/LibWeb/HTML/HTMLInputElement.h
index 584a14f055d..c2620830c7e 100644
--- a/Libraries/LibWeb/HTML/HTMLInputElement.h
+++ b/Libraries/LibWeb/HTML/HTMLInputElement.h
@@ -162,6 +162,8 @@ public:
GC::Ptr<JS::Object> value_as_date_object(JS::Object& relevant_global_object) const;
WebIDL::ExceptionOr<void> set_value_as_date_object(GC::Ptr<JS::Object>);
+ Color value_as_color() const;
+
double value_as_number() const;
WebIDL::ExceptionOr<void> set_value_as_number(double value);
@@ -355,6 +357,14 @@ private:
// https://html.spec.whatwg.org/multipage/input.html#value-sanitization-algorithm
Utf16String value_sanitization_algorithm(Utf16View) const;
+ enum class ColorSpaceState : u8 {
+ LimitedSRGB,
+ DisplayP3,
+ };
+ ColorSpaceState color_space_state() const;
+ Utf16String update_a_color_well_control_color(Utf16View element_value) const;
+ Utf16String serialize_a_color_well_control_color(CSS::StyleValue const&) const;
+
enum class ValueAttributeMode {
Value,
Default,
diff --git a/Libraries/LibWeb/HTML/HTMLInputElement.idl b/Libraries/LibWeb/HTML/HTMLInputElement.idl
index c4c24d6ac39..5a8acf363f2 100644
--- a/Libraries/LibWeb/HTML/HTMLInputElement.idl
+++ b/Libraries/LibWeb/HTML/HTMLInputElement.idl
@@ -1,13 +1,22 @@
+// https://html.spec.whatwg.org/multipage/input.html#attr-input-colorspace
+[MissingValueDefault=limited-srgb, InvalidValueDefault=limited-srgb]
+enum ColorSpaceAttribute {
+ "limited-srgb",
+ "display-p3"
+};
+
// https://html.spec.whatwg.org/multipage/input.html#htmlinputelement
[Exposed=Window]
interface HTMLInputElement : HTMLElement {
[HTMLConstructor] constructor();
[CEReactions, Reflect] attribute DOMString accept;
+ [CEReactions, Reflect] attribute boolean alpha;
[CEReactions, Reflect] attribute DOMString alt;
[CEReactions] attribute DOMString autocomplete;
[CEReactions, Reflect=checked] attribute boolean defaultChecked;
attribute boolean checked;
+ [CEReactions, Reflect=colorspace, Enumerated=ColorSpaceAttribute] attribute DOMString colorSpace;
[CEReactions, Reflect=dirname] attribute DOMString dirName;
[CEReactions, Reflect] attribute boolean disabled;
readonly attribute HTMLFormElement? form;
diff --git a/Libraries/LibWeb/Rust/src/css/color_resolution.rs b/Libraries/LibWeb/Rust/src/css/color_resolution.rs
index ce68d604676..99ab5914e15 100644
--- a/Libraries/LibWeb/Rust/src/css/color_resolution.rs
+++ b/Libraries/LibWeb/Rust/src/css/color_resolution.rs
@@ -2622,3 +2622,39 @@ pub unsafe extern "C" fn rust_style_value_to_color(
},
}
}
+
+#[repr(C)]
+pub struct FfiResolvedColorComponents {
+ pub resolved: bool,
+ pub components: [f32; 4],
+}
+
+/// Resolves a parsed style value to a used color against a style, converted to the color space of
+/// `target_color_type` (a ColorStyleValue::ColorType), or declines. Unlike rust_style_value_to_color(), the
+/// components keep their full precision and range, with missing components as 0.
+///
+/// # Safety
+/// `value` must point at live style value data, and `style` must be null or point at a style whose group payloads
+/// outlive the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_style_value_to_color_components(
+ value: *const core::ffi::c_void,
+ style: *const FfiColorResolutionStyle,
+ target_color_type: u8,
+) -> FfiResolvedColorComponents {
+ let value = unsafe { &*value.cast::<StyleValueData>() };
+ // SAFETY: Guaranteed by the caller.
+ let resolution_input = unsafe { ColorResolutionInput::for_ffi_style(style) };
+ let components = resolve_color_for_interpolation(value, &resolution_input)
+ .and_then(|resolved| color_conversion::convert(resolved.color_type, target_color_type, resolved.components));
+ match components {
+ Some(components) => FfiResolvedColorComponents {
+ resolved: true,
+ components,
+ },
+ None => FfiResolvedColorComponents {
+ resolved: false,
+ components: [0.0; 4],
+ },
+ }
+}
diff --git a/Tests/LibWeb/Text/expected/HTML/input-color-non-finite-components.txt b/Tests/LibWeb/Text/expected/HTML/input-color-non-finite-components.txt
new file mode 100644
index 00000000000..b45241f6458
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/input-color-non-finite-components.txt
@@ -0,0 +1,4 @@
+limited-srgb: color(display-p3 calc(infinity) 0 0) -> color(srgb 0 0 0)
+limited-srgb: color(srgb calc(infinity) calc(-infinity) 0) -> color(srgb 1 0 0)
+display-p3: color(display-p3 calc(infinity) 0 0) -> color(display-p3 340282346638528859811704183484516925440 0 0)
+display-p3: color(srgb calc(infinity) calc(-infinity) 0) -> color(display-p3 0 0 0)
diff --git a/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/color-attributes.window.txt b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/color-attributes.window.txt
index 4304895694d..1a9cc7a0d40 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/color-attributes.window.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/color-attributes.window.txt
@@ -2,6 +2,6 @@ Harness status: OK
Found 2 tests
-2 Fail
-Fail <input type=color>: alpha attribute
-Fail <input type=color>: colorspace attribute
\ No newline at end of file
+2 Pass
+Pass <input type=color>: alpha attribute
+Pass <input type=color>: colorspace attribute
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/color.txt b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/color.txt
index 07f176102d6..02f5fcbafe3 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/color.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/color.txt
@@ -2,32 +2,32 @@ Harness status: OK
Found 27 tests
-15 Pass
-12 Fail
+26 Pass
+1 Fail
Pass Empty value should return #000000
Pass Missing value should return #000000
Pass Valid simple color: should return #ffffff
Pass Valid simple color (containing LATIN CAPITAL LETTERS): should return #ffffff (converted to ASCII lowercase)
Pass Zero-padding
-Fail Valid simple color: 4 characters long
+Pass Valid simple color: 4 characters long
Pass Invalid simple color: 8 characters long
Pass Invalid simple color: no starting # sign
Pass Invalid simple color: non ASCII hex digits
Pass Invalid simple color: foobar
Pass Invalid color: trailing Null (U+0000)
Pass Invalid color: trailing ;
-Fail Valid color: leading space
-Fail Valid color: trailing space
-Fail Valid color: leading+trailing spaces
-Fail Valid color: keyword crimson
-Fail Valid color: keyword bisque
+Pass Valid color: leading space
+Pass Valid color: trailing space
+Pass Valid color: leading+trailing spaces
+Pass Valid color: keyword crimson
+Pass Valid color: keyword bisque
Pass Valid color: currentColor
Pass Invalid color: keyword transparent
Pass Invalid color: keyword inherit
-Fail Valid color: rgb(1,1,1)
-Fail Valid color: rgb(1,1,1,1)
+Pass Valid color: rgb(1,1,1)
+Pass Valid color: rgb(1,1,1,1)
Pass Invalid color: PILE OF POO (U+1F4A9)
-Fail Valid color: hsl(150deg 100 53.5)
-Fail Valid color: color(display-p3 .5 0 0)
-Fail Valid color: color(display-p3 1 0 0)
+Pass Valid color: hsl(150deg 100 53.5)
+Pass Valid color: color(display-p3 .5 0 0)
+Pass Valid color: color(display-p3 1 0 0)
Fail System colors are parsed
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/color.window.txt b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/color.window.txt
index eaeb5d1e886..01623b0e8d6 100644
Binary files a/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/color.window.txt and b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/color.window.txt differ
diff --git a/Tests/LibWeb/Text/input/HTML/input-color-non-finite-components.html b/Tests/LibWeb/Text/input/HTML/input-color-non-finite-components.html
new file mode 100644
index 00000000000..da9dadc453b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/input-color-non-finite-components.html
@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ test(() => {
+ for (const colorSpace of ["limited-srgb", "display-p3"]) {
+ const input = document.createElement("input");
+ input.type = "color";
+ input.alpha = true;
+ input.colorSpace = colorSpace;
+ for (const value of ["color(display-p3 calc(infinity) 0 0)", "color(srgb calc(infinity) calc(-infinity) 0)"]) {
+ input.value = value;
+ println(`${colorSpace}: ${value} -> ${input.value}`);
+ }
+ }
+ });
+</script>