Truly independent web browser
LibWeb: Preload the selected image source of `<link imagesrcset>`
Tim Ledbetter032bed881e6a
diff --git a/Libraries/LibWeb/CSS/Parser/Parser.cpp b/Libraries/LibWeb/CSS/Parser/Parser.cppindex 436dfff5442..a2940d47f06 100644--- a/Libraries/LibWeb/CSS/Parser/Parser.cpp+++ b/Libraries/LibWeb/CSS/Parser/Parser.cpp@@ -113,11 +113,11 @@ static Optional<double> sizes_attribute_auto_width(HTML::HTMLImageElement const*return concrete_size.width().to_double();}-// AD-HOC: If element has no sizes attribute, this algorithm always logs a parse error and then returns 100vw.+// AD-HOC: If the sizes are empty, this algorithm always logs a parse error and then returns 100vw.// The attribute is optional, so avoid spamming the debug log with false positives by just returning early.-NonnullRefPtr<StyleValue const> Parser::parse_as_sizes_attribute(Utf16View source, DOM::Element const& element, HTML::HTMLImageElement const* img)+NonnullRefPtr<StyleValue const> Parser::parse_as_sizes_attribute(Utf16View source, HTML::HTMLImageElement const* img){- if (!element.has_attribute(HTML::AttributeNames::sizes))+ if (source.is_empty())return LengthStyleValue::create(Length(100, LengthUnit::Vw));auto auto_width = sizes_attribute_auto_width(img);auto context = make_parse_context(ParseContextMode::Value);diff --git a/Libraries/LibWeb/CSS/Parser/Parser.h b/Libraries/LibWeb/CSS/Parser/Parser.hindex 1c84977ee15..c9a50d3a237 100644--- a/Libraries/LibWeb/CSS/Parser/Parser.h+++ b/Libraries/LibWeb/CSS/Parser/Parser.h@@ -114,7 +114,7 @@ public:RefPtr<StyleValue const> parse_as_descriptor_value(Utf16View, AtRuleID, DescriptorNameAndID const&);RefPtr<StyleValue const> parse_primitive_value_from_source(ValueType, Utf16View, NumericRange const& = infinite_range);- [[nodiscard]] NonnullRefPtr<StyleValue const> parse_as_sizes_attribute(Utf16View, DOM::Element const& element, HTML::HTMLImageElement const* img = nullptr);+ [[nodiscard]] NonnullRefPtr<StyleValue const> parse_as_sizes_attribute(Utf16View, HTML::HTMLImageElement const* img = nullptr);NonnullRefPtr<StyleValue const> parse_with_a_syntax(Utf16View input, RustSyntaxHandle const& syntax);diff --git a/Libraries/LibWeb/HTML/HTMLImageElement.cpp b/Libraries/LibWeb/HTML/HTMLImageElement.cppindex 4f433bdefbd..0cb280d7585 100644--- a/Libraries/LibWeb/HTML/HTMLImageElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLImageElement.cpp@@ -1444,16 +1444,17 @@ void HTMLImageElement::restart_the_animation()}// https://html.spec.whatwg.org/multipage/images.html#update-the-source-set-static void update_the_source_set(DOM::Element& element)+void update_the_source_set(DOM::Element& element){// When asked to update the source set for a given img or link element el, user agents must do the following:VERIFY(is<HTMLImageElement>(element) || is<HTMLLinkElement>(element));// 1. Set el's source set to an empty source set.- if (auto* image_element = as_if<HTMLImageElement>(element))+ if (auto* image_element = as_if<HTMLImageElement>(element)) {image_element->set_source_set(SourceSet {});- else if (is<HTMLLinkElement>(element))- TODO();+ } else if (auto* link_element = as_if<HTMLLinkElement>(element)) {+ link_element->set_source_set(SourceSet {});+ }// 2. Let elements be « el ».GC::RootVector<DOM::Element*> elements;@@ -1524,10 +1525,12 @@ static void update_the_source_set(DOM::Element& element)}// 10. Set el's source set to the result of creating a source set given default source, srcset, sizes, and img.- if (is<HTMLImageElement>(element))- static_cast<HTMLImageElement&>(element).set_source_set(SourceSet::create(element, default_source, srcset, sizes, img));- else if (is<HTMLLinkElement>(element))- TODO();+ auto source_set = SourceSet::create(element.document(), default_source, srcset, sizes, img);+ if (auto* image_element = as_if<HTMLImageElement>(element)) {+ image_element->set_source_set(move(source_set));+ } else if (auto* link_element = as_if<HTMLLinkElement>(element)) {+ link_element->set_source_set(move(source_set));+ }// 11. Return.return;@@ -1554,7 +1557,7 @@ static void update_the_source_set(DOM::Element& element)}// 7. Parse child's sizes attribute with img, and let source set's source size be the returned value.- source_set.m_source_size = parse_a_sizes_attribute(*child, child->attribute(HTML::AttributeNames::sizes).value_or({}), img);+ source_set.m_source_size = parse_a_sizes_attribute(element.document(), child->attribute(HTML::AttributeNames::sizes).value_or({}), img);// 8. If child has a type attribute, and its value is an unknown or unsupported MIME type, continue to the next child.if (child->has_attribute(HTML::AttributeNames::type)) {@@ -1571,7 +1574,7 @@ static void update_the_source_set(DOM::Element& element)img->set_dimension_attribute_source(nullptr);// 10. Normalize the source densities of source set.- source_set.normalize_source_densities(element);+ source_set.normalize_source_densities(element.document());// 11. Set el's source set to source set.img->set_source_set(move(source_set));diff --git a/Libraries/LibWeb/HTML/HTMLImageElement.h b/Libraries/LibWeb/HTML/HTMLImageElement.hindex a7c95cab475..e20d3d12f4c 100644--- a/Libraries/LibWeb/HTML/HTMLImageElement.h+++ b/Libraries/LibWeb/HTML/HTMLImageElement.h@@ -188,6 +188,8 @@ private:Optional<u64> m_cached_associated_map_element_dom_tree_version;};+void update_the_source_set(DOM::Element&);+}namespace Web::DOM {diff --git a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp b/Libraries/LibWeb/HTML/HTMLLinkElement.cppindex ec83fb5ba65..d4c120d71c2 100644--- a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLLinkElement.cpp@@ -32,11 +32,13 @@#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>#include <LibWeb/HTML/BrowsingContext.h>#include <LibWeb/HTML/EventNames.h>+#include <LibWeb/HTML/HTMLImageElement.h>#include <LibWeb/HTML/HTMLLinkElement.h>#include <LibWeb/HTML/LocalTraversableNavigable.h>#include <LibWeb/HTML/PotentialCORSRequest.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Scripting/Fetching.h>+#include <LibWeb/HTML/Window.h>#include <LibWeb/HighResolutionTime/TimeOrigin.h>#include <LibWeb/Loader/ResourceLoader.h>#include <LibWeb/Page/Page.h>@@ -361,8 +363,9 @@ GC::Ref<HTMLLinkElement::LinkProcessingOptions> HTMLLinkElement::create_link_opt// the state of el's referrerpolicy content attributeReferrerPolicy::from_string(referrerpolicy_value).value_or(ReferrerPolicy::ReferrerPolicy::EmptyString),- // FIXME: source set+ // source set// el's source set+ m_source_set,// base URL// document's document base URL@@ -588,7 +591,8 @@ void HTMLLinkElement::fetch_and_process_linked_preconnect_resource()// https://html.spec.whatwg.org/multipage/links.html#link-type-preload:fetch-and-process-the-linked-resource-2void HTMLLinkElement::fetch_and_process_linked_preload_resource(){- // FIXME: 1. Update the source set for el.+ // 1. Update the source set for el.+ update_the_source_set(*this);// 2. Let options be the result of creating link options from el.auto options = create_link_options();@@ -940,8 +944,15 @@ void HTMLLinkElement::preload(LinkProcessingOptions& options, Function<void(Fetcif (!type_matches_destination(options.type, options.destination))return;- // FIXME: 2. If options's destination is "image" and options's source set is not null, then set options's href to the- // result of selecting an image source from options's source set.+ // 2. If options's destination is "image" and options's source set is not null, then set options's href to the+ // result of selecting an image source from options's source set.+ // NB: A link with neither an href nor an imagesrcset has an empty source set, with no image source to select.+ if (options.destination == Fetch::Infrastructure::Request::Destination::Image && options.source_set.has_value() && !options.source_set->is_empty()) {+ auto device_pixel_ratio = 1.0;+ if (auto const* window = window_from_global_object(options.environment->global_object()))+ device_pixel_ratio = window->device_pixel_ratio();+ options.href = options.source_set->select_an_image_source(device_pixel_ratio).source.url;+ }if (options.href.is_empty())return;@@ -1400,6 +1411,7 @@ bool HTMLLinkElement::should_fetch_and_process_resource_type() constHTMLLinkElement::LinkProcessingOptions::LinkProcessingOptions(CORSSettingAttribute crossorigin,ReferrerPolicy::ReferrerPolicy referrer_policy,+ Optional<SourceSet> source_set,URL::URL base_url,URL::Origin origin,GC::Ref<HTML::EnvironmentSettingsObject> environment,@@ -1410,6 +1422,7 @@ HTMLLinkElement::LinkProcessingOptions::LinkProcessingOptions(: cryptographic_nonce_metadata(move(cryptographic_nonce_metadata)), crossorigin(crossorigin), referrer_policy(referrer_policy)+ , source_set(move(source_set)), base_url(move(base_url)), origin(move(origin)), environment(environment)diff --git a/Libraries/LibWeb/HTML/HTMLLinkElement.h b/Libraries/LibWeb/HTML/HTMLLinkElement.hindex 64bc7fde8c6..a2a7be09f11 100644--- a/Libraries/LibWeb/HTML/HTMLLinkElement.h+++ b/Libraries/LibWeb/HTML/HTMLLinkElement.h@@ -19,6 +19,7 @@#include <LibWeb/HTML/CORSSettingAttribute.h>#include <LibWeb/HTML/HTMLElement.h>#include <LibWeb/HTML/PreloadEntry.h>+#include <LibWeb/HTML/SourceSet.h>#include <LibWebCommon/MimeSniff/MimeType.h>namespace Web::HTML {@@ -59,6 +60,8 @@ public:RefPtr<CSS::StyleSheetState> sheet() const;CSS::CSSStyleSheet* cssom_sheet() const;+ void set_source_set(SourceSet source_set) { m_source_set = move(source_set); }+enum class AnyFailed : u8 {No,Yes,@@ -74,6 +77,7 @@ private:LinkProcessingOptions(CORSSettingAttribute crossorigin,ReferrerPolicy::ReferrerPolicy referrer_policy,+ Optional<SourceSet> source_set,URL::URL base_url,URL::Origin origin,GC::Ref<HTML::EnvironmentSettingsObject> environment,@@ -112,8 +116,9 @@ private:// A referrer policyReferrerPolicy::ReferrerPolicy referrer_policy { ReferrerPolicy::ReferrerPolicy::EmptyString };- // FIXME: source set (default null)+ // source set (default null)// Null or a source set+ Optional<SourceSet> source_set;// base URL// A URL@@ -216,6 +221,8 @@ private:Optional<Utf16String> m_mime_type;+ SourceSet m_source_set;+GC::Weak<DOM::Document> m_parser_document;};diff --git a/Libraries/LibWeb/HTML/SourceSet.cpp b/Libraries/LibWeb/HTML/SourceSet.cppindex 030dfbb770b..61719f30697 100644--- a/Libraries/LibWeb/HTML/SourceSet.cpp+++ b/Libraries/LibWeb/HTML/SourceSet.cpp@@ -343,14 +343,14 @@ descriptor_parser:}// https://html.spec.whatwg.org/multipage/images.html#parse-a-sizes-attribute-NonnullRefPtr<CSS::StyleValue const> parse_a_sizes_attribute(DOM::Element const& element, Utf16View sizes, HTML::HTMLImageElement const* img)+NonnullRefPtr<CSS::StyleValue const> parse_a_sizes_attribute(DOM::Document const& document, Utf16View sizes, HTML::HTMLImageElement const* img){- CSS::Parser::Parser css_parser { CSS::Parser::ParsingParams { element.document() } };- return css_parser.parse_as_sizes_attribute(sizes, element, img);+ CSS::Parser::Parser css_parser { CSS::Parser::ParsingParams { document } };+ return css_parser.parse_as_sizes_attribute(sizes, img);}// https://html.spec.whatwg.org/multipage/images.html#create-a-source-set-SourceSet SourceSet::create(DOM::Element const& element, Utf16View default_source, Utf16View srcset, Utf16View sizes, HTML::HTMLImageElement const* img)+SourceSet SourceSet::create(DOM::Document const& document, Utf16View default_source, Utf16View srcset, Utf16View sizes, HTML::HTMLImageElement const* img){// When asked to create a source set given a string default source, a string srcset, a string sizes, and an element or null img:@@ -362,7 +362,7 @@ SourceSet SourceSet::create(DOM::Element const& element, Utf16View default_sourcsource_set = parse_a_srcset_attribute(srcset);// 3. Set source set's source size to the result of parsing sizes with img.- source_set.m_source_size = parse_a_sizes_attribute(element, sizes, img);+ source_set.m_source_size = parse_a_sizes_attribute(document, sizes, img);// 4. If default source is not the empty string and source set does not contain an image source// with a pixel density descriptor value of 1, and no image source with a width descriptor,@@ -383,14 +383,14 @@ SourceSet SourceSet::create(DOM::Element const& element, Utf16View default_sourc}// 5. Normalize the source densities of source set.- source_set.normalize_source_densities(element);+ source_set.normalize_source_densities(document);// 6. Return source set.return source_set;}// https://html.spec.whatwg.org/multipage/images.html#normalise-the-source-densities-void SourceSet::normalize_source_densities(DOM::Element const& element)+void SourceSet::normalize_source_densities(DOM::Document const& document){// 1. Let source size be source set's source size.@@ -401,7 +401,7 @@ void SourceSet::normalize_source_densities(DOM::Element const& element)// https://drafts.csswg.org/mediaqueries/#units// Relative length units in media queries are based on the initial value, which means that units are never based on// results of declarations.- auto const& length_resolution_context = CSS::Length::ResolutionContext::for_document(element.document());+ auto const& length_resolution_context = CSS::Length::ResolutionContext::for_document(document);auto source_size = CSS::Length::from_style_value(m_source_size->absolutized({ length_resolution_context }), {}).absolute_length_to_px();diff --git a/Libraries/LibWeb/HTML/SourceSet.h b/Libraries/LibWeb/HTML/SourceSet.hindex 0db997e2802..553a5266c0a 100644--- a/Libraries/LibWeb/HTML/SourceSet.h+++ b/Libraries/LibWeb/HTML/SourceSet.h@@ -35,7 +35,7 @@ struct ImageSourceAndPixelDensity {// https://html.spec.whatwg.org/multipage/images.html#source-setstruct SourceSet {- static SourceSet create(DOM::Element const& element, Utf16View default_source, Utf16View srcset, Utf16View sizes, HTML::HTMLImageElement const* img = nullptr);+ static SourceSet create(DOM::Document const&, Utf16View default_source, Utf16View srcset, Utf16View sizes, HTML::HTMLImageElement const* img = nullptr);[[nodiscard]] bool is_empty() const;@@ -43,7 +43,7 @@ struct SourceSet {[[nodiscard]] ImageSourceAndPixelDensity select_an_image_source(double device_pixel_ratio);// https://html.spec.whatwg.org/multipage/images.html#normalise-the-source-densities- void normalize_source_densities(DOM::Element const&);+ void normalize_source_densities(DOM::Document const&);SourceSet();@@ -52,6 +52,6 @@ struct SourceSet {};SourceSet parse_a_srcset_attribute(Utf16View);-[[nodiscard]] NonnullRefPtr<CSS::StyleValue const> parse_a_sizes_attribute(DOM::Element const& element, Utf16View sizes, HTML::HTMLImageElement const* img = nullptr);+[[nodiscard]] NonnullRefPtr<CSS::StyleValue const> parse_a_sizes_attribute(DOM::Document const&, Utf16View sizes, HTML::HTMLImageElement const* img = nullptr);}diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex c3ad3911a8c..b997c7bca14 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -632,6 +632,7 @@ Text/input/wpt-import/worklets/audio-worklet-import.https.htmlText/input/wpt-import/streams/transferable/audioworklet.https.htmlText/input/wpt-import/preload/prefetch-load-event.htmlText/input/wpt-import/preload/prefetch-events.html+Text/input/HTML/link-preload-image-source-set.htmlText/input/wpt-import/resource-timing/initiator-type/img.htmlText/input/wpt-import/resource-timing/initiator-type/img-srcset.htmlText/input/wpt-import/resource-timing/initiator-type/picture.htmldiff --git a/Tests/LibWeb/Text/expected/HTML/link-preload-image-source-set.txt b/Tests/LibWeb/Text/expected/HTML/link-preload-image-source-set.txtnew file mode 100644index 00000000000..1d1cc49758e--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/link-preload-image-source-set.txt@@ -0,0 +1,3 @@+fallback: not requested+small: requested+large: not requesteddiff --git a/Tests/LibWeb/Text/input/HTML/link-preload-image-source-set.html b/Tests/LibWeb/Text/input/HTML/link-preload-image-source-set.htmlnew file mode 100644index 00000000000..5d88930082c--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/link-preload-image-source-set.html@@ -0,0 +1,25 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const server = httpTestServer();+ const createImage = name => server.createEcho("GET", `/link-preload-image-source-set/${name}.png`, { status: 200, headers: { "Content-Type": "image/png" } });+ const [fallback, small, large] = await Promise.all([createImage("fallback"), createImage("small"), createImage("large")]);++ const link = document.createElement("link");+ link.rel = "preload";+ link.as = "image";+ link.href = fallback;+ link.setAttribute("imagesrcset", `${small} 200w, ${large} 800w`);+ link.setAttribute("imagesizes", "100px");+ await new Promise(resolve => {+ link.onload = link.onerror = resolve;+ document.head.appendChild(link);+ });++ for (const [name, url] of Object.entries({ fallback, small, large })) {+ const response = await fetch(server.recordedRequestHeadersURL(url));+ println(`${name}: ${response.ok ? "requested" : "not requested"}`);+ }+ });+</script>